Repository navigation
Expand file tree
/
Copy pathapp.go
More file actions
261 lines (225 loc) · 6.09 KB
/
Copy pathapp.go
File metadata and controls
261 lines (225 loc) · 6.09 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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package main
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/ruanklein/fmgo"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
type App struct {
ctx context.Context
client *fmgo.Client
store *conversationStore
setupErr error
userAvatar string
cancels map[string]context.CancelFunc
cancelsMu sync.Mutex
}
type ModelStatus struct {
Available bool `json:"available"`
Message string `json:"message"`
}
type ChatEvent struct {
ConversationID string `json:"conversationID"`
MessageID string `json:"messageID"`
Text string `json:"text"`
}
func NewApp() *App {
return &App{cancels: map[string]context.CancelFunc{}}
}
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
directory, err := os.UserConfigDir()
if err != nil {
a.setupErr = fmt.Errorf("find application support directory: %w", err)
return
}
a.store, err = newConversationStore(filepath.Join(directory, "FM Chat"))
if err != nil {
a.setupErr = err
return
}
if homeDirectory, err := os.UserHomeDir(); err == nil {
imagePath := filepath.Join(directory, "FM Chat", accountImageFile)
if err := captureAccountImage(ctx, homeDirectory, imagePath); err == nil {
if imageData, readErr := os.ReadFile(imagePath); readErr == nil {
a.userAvatar = imageDataURL(imageData)
}
}
}
a.client, err = fmgo.New()
if err != nil {
a.setupErr = err
}
}
func (a *App) GetUserAvatar() string {
return a.userAvatar
}
func (a *App) GetModelStatus() ModelStatus {
if a.setupErr != nil {
return ModelStatus{Message: a.setupErr.Error()}
}
ctx, cancel := context.WithTimeout(a.ctx, 10*time.Second)
defer cancel()
availability, err := a.client.Available(ctx)
if err != nil {
return ModelStatus{Message: err.Error()}
}
for _, model := range availability.Models {
if model.Model != fmgo.ModelSystem {
continue
}
if model.Available {
return ModelStatus{Available: true, Message: "On-device model ready"}
}
return ModelStatus{Message: model.Reason}
}
return ModelStatus{Message: "The on-device model is unavailable"}
}
func (a *App) ListConversations() ([]Conversation, error) {
if a.setupErr != nil {
return nil, a.setupErr
}
return a.store.list(), nil
}
func (a *App) CreateConversation() (Conversation, error) {
if a.setupErr != nil {
return Conversation{}, a.setupErr
}
return a.store.create()
}
func (a *App) GetConversation(id string) (Conversation, error) {
if a.setupErr != nil {
return Conversation{}, a.setupErr
}
return a.store.get(id)
}
func (a *App) DeleteConversation(id string) error {
if a.setupErr != nil {
return a.setupErr
}
if a.isGenerating(id) {
return errors.New("stop the response before deleting this chat")
}
return a.store.delete(id)
}
func (a *App) ChooseImages() ([]Attachment, error) {
if a.setupErr != nil {
return nil, a.setupErr
}
paths, err := runtime.OpenMultipleFilesDialog(a.ctx, runtime.OpenDialogOptions{
Title: "Choose images",
Filters: []runtime.FileFilter{{
DisplayName: "Images",
Pattern: "*.png;*.jpg;*.jpeg;*.heic;*.gif;*.webp",
}},
})
if err != nil {
return nil, err
}
return a.store.importImages(paths)
}
func (a *App) SendMessage(conversationID, prompt string, attachments []Attachment) (Message, error) {
if a.setupErr != nil {
return Message{}, a.setupErr
}
if strings.TrimSpace(prompt) == "" && len(attachments) == 0 {
return Message{}, errors.New("write a message or attach an image")
}
if a.isGenerating(conversationID) {
return Message{}, errors.New("this conversation is already generating a response")
}
imagePaths, err := a.store.imagePaths(attachments)
if err != nil {
return Message{}, err
}
userMessage, assistantMessage, transcriptPath, err := a.store.startResponse(
conversationID,
strings.TrimSpace(prompt),
attachments,
)
if err != nil {
return Message{}, err
}
ctx, cancel := context.WithCancel(a.ctx)
a.setCancel(conversationID, cancel)
request := fmgo.Request{
Prompt: userMessage.Content,
Images: imagePaths,
Model: fmgo.ModelSystem,
SaveTranscript: transcriptPath,
}
if _, err := os.Stat(transcriptPath); err == nil {
request.Resume = transcriptPath
}
go a.streamResponse(ctx, conversationID, assistantMessage.ID, request)
return assistantMessage, nil
}
func (a *App) CancelGeneration(conversationID string) {
a.cancelsMu.Lock()
cancel := a.cancels[conversationID]
a.cancelsMu.Unlock()
if cancel != nil {
cancel()
}
}
func (a *App) streamResponse(ctx context.Context, conversationID, messageID string, request fmgo.Request) {
defer a.clearCancel(conversationID)
stream, err := a.client.Stream(ctx, request)
if err != nil {
a.emitError(conversationID, messageID, err)
return
}
defer stream.Close()
var response strings.Builder
for stream.Next() {
chunk := stream.Text()
response.WriteString(chunk)
if err := a.store.updateMessage(conversationID, messageID, response.String()); err != nil {
a.emitError(conversationID, messageID, err)
return
}
runtime.EventsEmit(a.ctx, "chat:chunk", ChatEvent{
ConversationID: conversationID,
MessageID: messageID,
Text: chunk,
})
}
if err := stream.Err(); err != nil && !errors.Is(ctx.Err(), context.Canceled) {
a.emitError(conversationID, messageID, err)
return
}
runtime.EventsEmit(a.ctx, "chat:complete", ChatEvent{
ConversationID: conversationID,
MessageID: messageID,
Text: response.String(),
})
}
func (a *App) emitError(conversationID, messageID string, err error) {
runtime.EventsEmit(a.ctx, "chat:error", ChatEvent{
ConversationID: conversationID,
MessageID: messageID,
Text: err.Error(),
})
}
func (a *App) isGenerating(conversationID string) bool {
a.cancelsMu.Lock()
defer a.cancelsMu.Unlock()
_, generating := a.cancels[conversationID]
return generating
}
func (a *App) setCancel(conversationID string, cancel context.CancelFunc) {
a.cancelsMu.Lock()
defer a.cancelsMu.Unlock()
a.cancels[conversationID] = cancel
}
func (a *App) clearCancel(conversationID string) {
a.cancelsMu.Lock()
defer a.cancelsMu.Unlock()
delete(a.cancels, conversationID)
}