-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat_input.go
More file actions
168 lines (150 loc) · 5.2 KB
/
Copy pathchat_input.go
File metadata and controls
168 lines (150 loc) · 5.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
// SPDX-License-Identifier: MIT
// Purpose: TUI-side adapter for the chat.Input widget. Avoids the
// `*chat.Input` direct dep in model.go by wrapping it in a local type.
// Submits are routed through a chat.Runner (lazy-init singleton) and the
// LLM call runs in a background goroutine so the UI stays responsive.
package tui
import (
tea "charm.land/bubbletea/v2"
"github.com/OpenSIN-Code/SIN-Code/cmd/sin-code/internal/attachments"
"github.com/OpenSIN-Code/SIN-Code/cmd/sin-code/tui/chat"
)
type chatInput = chat.Input
// newChatRunnerHook is a test seam for chat runner construction.
var newChatRunnerHook = func() (*chat.Runner, error) { return chat.NewRunner() }
// chatRunnerRunHook is a test seam for chat runner execution.
var chatRunnerRunHook = func(r *chat.Runner, ctx context.Context, prompt string, history []string) (string, error) {
return r.Run(ctx, prompt, history)
}
func newChatInput() *chatInput {
store, err := attachments.NewStore()
if err != nil {
store = nil
}
return chat.NewInput(store)
}
func (m *Model) initChatInput() {
if m.ChatInput == nil {
m.ChatInput = newChatInput()
}
}
// initChatRunner lazily initializes the chat LLM runner. If no API key is
// configured the runner stays nil and the submit handler prints an
// in-band error rather than calling the LLM.
func (m *Model) initChatRunner() {
if m.ChatRunner != nil {
return
}
r, err := newChatRunnerHook()
if err != nil {
m.ChatRunner = nil
return
}
m.ChatRunner = r
}
type chatSubmitMsg struct {
Text string
Attachments []*attachments.Attachment
}
// handleChatSubmit appends the user entry to history and, when a runner
// is available, kicks off an async LLM call. A "thinking..." placeholder
// is shown immediately; the background goroutine dispatches a
// chat.ChatResponseMsg back into the Update loop via *tea.Program.Send
// (or, when no program is set, blocks synchronously — used by tests).
//
// Returns a tea.Cmd that subscribes to the AgentRunner's event stream
// (issue #53) so the user sees the full agentloop progress in chat
// history. Returns nil when no agent runner is available.
func handleChatSubmit(m *Model, submit chat.SubmitMsg) tea.Cmd {
entry := submit.Text
if len(submit.Attachments) > 0 {
entry += "\n[attachments:"
for _, a := range submit.Attachments {
entry += " " + a.Marker()
}
entry += "]"
}
m.ChatHistory = append(m.ChatHistory, entry)
if len(m.ChatHistory) > 500 {
m.ChatHistory = m.ChatHistory[len(m.ChatHistory)-500:]
}
m.AppendHistory(ViewChat.String(), "chat-submit", entry, true)
m.initChatRunner()
if m.ChatRunner == nil {
m.ChatHistory = append(m.ChatHistory, "assistant: (no API key — set SIN_NIM_API_KEY)")
if len(m.ChatHistory) > 500 {
m.ChatHistory = m.ChatHistory[len(m.ChatHistory)-500:]
}
}
// Issue #53: also kick off the full agentloop in parallel. The
// agent runner emits AgentRunnerMsg events that the update loop
// folds back into ChatHistory, so the user sees the agent's tool
// calls, asks, and final summary alongside the LLM chat reply.
// Falls back to nil (no-op) when the runner cannot be constructed
// (e.g. workspace not writable).
agentCmd := m.submitAgentPrompt(submit.Text)
if m.ChatRunner == nil {
return agentCmd
}
// Show "thinking..." placeholder right away so the user sees feedback.
m.ChatHistory = append(m.ChatHistory, "assistant: thinking...")
if len(m.ChatHistory) > 500 {
m.ChatHistory = m.ChatHistory[len(m.ChatHistory)-500:]
}
thinkingIdx := len(m.ChatHistory) - 1
// Snapshot the runner + history so the goroutine doesn't race the
// Update loop's mutations.
runner := m.ChatRunner
historySnapshot := append([]string(nil), m.ChatHistory[:thinkingIdx]...)
prompt := submit.Text
prog := m.Program
if prog == nil {
// No program wired up (e.g. test path): run synchronously so the
// caller sees the final history immediately and the model is never
// mutated by a background goroutine.
text, err := runner.Run(m.ctx(), prompt, historySnapshot)
applyChatResponseMsg(m, chat.ChatResponseMsg{Text: text, Error: err}, thinkingIdx)
return nil
}
go func() {
text, err := runner.Run(m.ctx(), prompt, historySnapshot)
prog.Send(chat.ChatResponseMsg{Text: text, Error: err})
}()
return nil
}
// applyChatResponseMsg replaces the "thinking..." placeholder at idx with
// the real assistant text (or error). Used by the synchronous fallback path
// when no *tea.Program is wired up.
func applyChatResponseMsg(m *Model, msg chat.ChatResponseMsg, idx int) {
if idx < 0 || idx >= len(m.ChatHistory) {
return
}
if msg.Error != nil {
m.ChatHistory[idx] = "assistant: (error: " + msg.Error.Error() + ")"
return
}
text := msg.Text
if text == "" {
text = "(empty response)"
}
m.ChatHistory[idx] = "assistant: " + text
}
func (m *Model) updateChat(msg tea.Msg) tea.Cmd {
if m.ChatInput == nil {
return nil
}
cmd, submit := m.ChatInput.Update(msg)
if submit != nil {
agentCmd := handleChatSubmit(m, *submit)
m.ChatInput.Clear()
// Combine the input's tea.Cmd with the agent-runner
// subscription so both fire on the next tick. The agent
// subscription re-arms itself in update.go's AgentRunnerMsg
// handler.
if agentCmd != nil {
return tea.Batch(cmd, agentCmd)
}
return cmd
}
return cmd
}