// Package appui is the MyGo client: the windows, screens and state of the // OpenChamber app. package appui import ( "context" "fmt" "log" "strings" "time" "github.com/egoist/mygo" "github.com/egoist/mygo/ui" "github.com/openchamber/openchamber-native/internal/ocapi" "github.com/openchamber/openchamber-native/internal/storage" ) // App is the whole application's state. Its view functions build the // windows' interfaces from it, on the main thread, whenever a frame is // needed. type App struct { store storage.Store // Windows. win *mygo.Window // the root window: servers or sessions chatWin *mygo.Window // the pushed chat window, when a session is open // The active connection. client *ocapi.Client conn storage.Connection busy bool // a connect is in progress // Server list / connect form state. phase string // "" = disconnected, "form" = editing/adding, else connected formTitle string formLabel string formURL string formProxy string formInsecure bool formFinger string formPassword string formEditing *storage.Connection formError string // Sessions list state. sessions []ocapi.Session sessionsCursor string sessionsLoad bool searchOpen bool searchText string searchTimer *time.Timer errorText string // Live state from the event stream. active map[string]bool perms []ocapi.PermissionRequest // The open chat, if any. chat *chat sessionListState ui.ListState instancesOpen bool serverActionOpen *bool serverActionTarget *storage.Connection confirmDelete bool deleteTarget *storage.Connection // Session list sheet state. newOpen bool newTitle string sessionActionOpen bool sessionActionTarget ocapi.Session renameOpen bool renameTarget ocapi.Session renameText string sessionDeleteOpen bool sessionDeleteTarget *ocapi.Session // Tables the UI needs on the main thread. modelNames map[string]string // The event stream. streamCancel context.CancelFunc } // New makes the app. Call it before mygo.App.Run. A nil store makes the // persistent store on Ready, once the app can name its data directory. func New(store storage.Store) *App { if store == nil { store = &lazyStore{} } return &App{ store: store, active: map[string]bool{}, modelNames: map[string]string{}, } } // lazyStore creates the persistent store on first use, on the main thread. type lazyStore struct{ s storage.Store } func (l *lazyStore) get() storage.Store { if l.s == nil { l.s = storage.New() } return l.s } func (l *lazyStore) Connections() []storage.Connection { return l.get().Connections() } func (l *lazyStore) SaveConnections(c []storage.Connection) { l.get().SaveConnections(c) } func (l *lazyStore) InstallID() string { return l.get().InstallID() } func (l *lazyStore) LoadToken(c storage.Connection) (string, bool, error) { return l.get().LoadToken(c) } func (l *lazyStore) SaveToken(id, token string) error { return l.get().SaveToken(id, token) } func (l *lazyStore) ClearToken(c storage.Connection) error { return l.get().ClearToken(c) } // Ready runs when the app is ready (mygo.App.WhenReady): it makes the root // window and reconnects to the most recently used server. func (a *App) Ready() { a.win = mygo.NewWindow(mygo.WindowOptions{ Title: "OpenChamber", Content: ui.View(a.view), }) a.reconnectLast() } // view is the root window's interface: the server list when disconnected, // the sessions list when connected. func (a *App) view(c *ui.Context) { if a.client == nil { a.serversView(c) return } a.sessionsView(c) } // post runs fn on the main thread and redraws the root window. func (a *App) post(fn func()) { if a.win != nil { a.win.Update(fn) } } // chatPost runs fn on the main thread and redraws the chat window. func (a *App) chatPost(fn func()) { if a.chat != nil && a.chatWin != nil { a.chatWin.Update(fn) return } a.post(fn) } func (a *App) reconnectLast() { conns := a.store.Connections() if len(conns) == 0 { return } conn := conns[0] a.connectTo(conn, "", true) } // connectTo builds a client for conn and authenticates. When password is // empty it tries the saved device token first. Silent connections (the // recent server on startup) show errors in the server list instead of a // modal form. func (a *App) connectTo(conn storage.Connection, password string, silent bool) { if a.busy { return } a.busy = true a.errorText = "" go func() { client, err := ocapi.New(conn.URL, ocapi.Options{ Proxy: conn.Proxy, InsecureSkipVerify: conn.Insecure, CertFingerprint: conn.Fingerprint, Timeout: 20 * time.Second, }) if err != nil { a.post(func() { a.busy = false a.failConnect(conn, silent, friendlyError(err)) }) return } token, ok, err := a.store.LoadToken(conn) if err == nil && !ok { // No saved token: a passwordless server needs none. Probe it. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) st, serr := client.SessionStatus(ctx) cancel() if serr == nil && st.Disabled && !st.Locked { a.post(func() { a.busy = false a.connected(client, conn, silent) }) return } } if err != nil || (!ok && password == "") { if ok { err = fmt.Errorf("无法读取已保存的凭据") } if err != nil { a.post(func() { a.busy = false a.failConnect(conn, silent, friendlyError(err)) }) return } // Needs a password: ask in the form. a.post(func() { a.busy = false a.promptPassword(conn) }) return } if ok { client.SetToken(token) if err := a.verifyConnection(client); err != nil { a.post(func() { a.busy = false a.failConnect(conn, silent, friendlyError(err)) }) return } a.post(func() { a.connected(client, conn, silent) }) return } // Login with the password the form gave. res, err := client.Login(context.Background(), ocapi.LoginRequest{ Password: password, DedupeKey: a.store.InstallID(), ClientLabel: "OpenChamber Native", ClientKind: "mobile", DevicePlatform: "android", }) if err != nil { a.post(func() { a.busy = false a.failConnect(conn, false, friendlyError(err)) }) return } if res.ClientToken == "" { a.post(func() { a.busy = false a.failConnect(conn, false, "登录成功但没有返回令牌") }) return } client.SetToken(res.ClientToken) if err := a.store.SaveToken(conn.ID, res.ClientToken); err != nil { log.Printf("appui: save token: %v", err) } a.post(func() { a.busy = false a.connected(client, conn, silent) }) }() } // verifyConnection checks the device token is accepted. func (a *App) verifyConnection(client *ocapi.Client) error { ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() st, err := client.SessionStatus(ctx) if err != nil { return err } if !st.Authenticated { return fmt.Errorf("已保存的凭据已失效,请重新登录") } return nil } // connected switches to the sessions list and starts the event stream. func (a *App) connected(client *ocapi.Client, conn storage.Connection, silent bool) { a.client = client a.conn = conn a.phase = "connected" conns := a.store.Connections() found := false for i := range conns { if conns[i].ID == conn.ID { conns[i].LastUsedAt = time.Now().UnixMilli() found = true break } } if !found { conn.LastUsedAt = time.Now().UnixMilli() conns = append([]storage.Connection{conn}, conns...) } a.store.SaveConnections(conns) a.startStream() a.loadSessions() a.loadActive() a.loadPerms() a.loadModels() } // failConnect surfaces a connect error: the connect form when not silent. func (a *App) failConnect(conn storage.Connection, silent bool, msg string) { a.client = nil a.conn = storage.Connection{} a.phase = "" if silent { a.errorText = fmt.Sprintf("无法连接 %s:%s", conn.Label, msg) } else { a.promptPassword(conn) a.formError = msg } } // promptPassword shows the connect form for conn with its password field. func (a *App) promptPassword(conn storage.Connection) { a.phase = "form" a.formEditing = &conn a.formTitle = "连接 " + conn.Label a.formLabel = conn.Label a.formURL = conn.URL a.formProxy = conn.Proxy a.formInsecure = conn.Insecure a.formFinger = conn.Fingerprint a.formPassword = "" a.formError = "" } // disconnect drops the connection and returns to the server list. func (a *App) disconnect() { a.stopStream() a.client = nil a.conn = storage.Connection{} a.phase = "" a.sessions = nil a.errorText = "" if a.chat != nil { a.closeChat() } } // ---------------------------------------------------------------- sessions func (a *App) loadSessions() { if a.client == nil { return } a.sessionsLoad = true go func() { page, err := a.client.ListSessions(context.Background(), ocapi.ListSessionsOptions{ Limit: 50, Order: "desc", }) a.post(func() { a.sessionsLoad = false if err != nil { a.errorText = friendlyError(err) return } a.sessions = page.Data a.sessionsCursor = page.Cursor.Next }) }() } func (a *App) searchSessions(q string) { if a.client == nil { return } a.sessionsLoad = true dir := "" if len(a.sessions) > 0 && a.sessions[0].Location != nil { dir = a.sessions[0].Location.Directory } go func() { page, err := a.client.ListSessions(context.Background(), ocapi.ListSessionsOptions{ Limit: 50, Order: "desc", Search: q, Directory: dir, }) a.post(func() { a.sessionsLoad = false if err != nil { return } a.sessions = page.Data }) }() } func (a *App) loadActive() { go func() { m, err := a.client.ActiveSessions(context.Background()) a.post(func() { if err != nil { return } next := map[string]bool{} for id := range m { next[id] = true } a.active = next }) }() } func (a *App) loadPerms() { go func() { list, err := a.client.PendingPermissions(context.Background(), a.dir()) a.post(func() { if err != nil { return } a.perms = list }) }() } func (a *App) loadModels() { go func() { models, err := a.client.Models(context.Background(), a.dir()) a.post(func() { if err != nil { return } names := map[string]string{} for _, m := range models { name := m.Name if name == "" { name = m.ID } names[m.ProviderID+"/"+m.ID] = name names[m.ID] = name } a.modelNames = names }) }() } func (a *App) dir() string { if len(a.sessions) > 0 && a.sessions[0].Location != nil { return a.sessions[0].Location.Directory } if a.chat != nil { return a.chat.dir } return "" } func (a *App) modelName(m *ocapi.ModelRef) string { if m == nil { return "" } if name := a.modelNames[m.ProviderID+"/"+m.ID]; name != "" { return name } if name := a.modelNames[m.ID]; name != "" { return name } return m.ID } func friendlyError(err error) string { if err == nil { return "" } msg := err.Error() msg = strings.TrimSpace(msg) if msg == "" { return "请求失败" } if len(msg) > 300 { msg = msg[:300] + "…" } return msg }