package workspace import ( "context" "encoding/json" "path" "strings" "time" "100gex/internal/rex" ) // Summary is what a list of sessions says about one: what runs in it, what // happened in it since it was last shown, and who else has it open. type Summary struct { // Programs names what runs in each window's focused block, in the // windows' order: the program in the foreground, or the directory of // a shell at its prompt. Programs []string // Since the session was last shown here: Bell bool // a bell rang, or a program asked for a notification Exited bool // a program exited Failed bool // a program exited with an error Waiting bool // a program says it's waiting for the person Working bool // a program says it's working // Elsewhere names the other clients attached to the session. Elsewhere []string } // tracker follows one session for its summary. Guarded by Workspace.mu. type tracker struct { view rex.View viewing bool // a session.view is running again bool // and another is due when it ends programs map[string]string // by block asked map[string]bool // blocks whose processes were asked for status map[string]map[string]string // each block's program status records' states, by record ID clients []string bell bool exited bool failed bool clientsDue bool // a client.list is running or due } func newTracker() *tracker { return &tracker{programs: make(map[string]string), asked: make(map[string]bool), status: make(map[string]map[string]string)} } // Summary returns what the workspace knows about a session. func (w *Workspace) Summary(sessionID string) Summary { w.mu.Lock() defer w.mu.Unlock() t := w.trackers[sessionID] if t == nil { return Summary{} } s := Summary{Bell: t.bell, Exited: t.exited, Failed: t.failed, Elsewhere: t.clients} for _, win := range t.view.Windows { block := win.FocusedBlockID if win.ZoomedBlockID != "" { block = win.ZoomedBlockID } if p := t.programs[block]; p != "" { s.Programs = append(s.Programs, p) } } for _, records := range t.status { for _, state := range records { switch state { case "blocked": s.Waiting = true case "working": s.Working = true } } } return s } // track starts following every session in list. w.mu must be held. func (w *Workspace) track(list []rex.Session) { if w.trackers == nil { w.trackers = make(map[string]*tracker) } for _, s := range list { if w.trackers[s.SessionID] == nil { w.trackers[s.SessionID] = newTracker() w.fetchView(s.SessionID) w.fetchClients(s.SessionID) } } for id := range w.trackers { found := false for _, s := range list { found = found || s.SessionID == id } if !found { delete(w.trackers, id) } } } // shownID is the session shown, or about to be. w.mu must be held. func (w *Workspace) shownID() string { switch { case w.next != nil: return w.next.session.ID() case w.current != nil: return w.current.session.ID() } return "" } // seen clears what happened in a session since it was last shown. w.mu // must be held. func (w *Workspace) seen(sessionID string) { if t := w.trackers[sessionID]; t != nil { t.bell, t.exited, t.failed = false, false, false } } // fetchView fetches a session's view for its summary, and then the // processes of blocks focused in it. Changes that arrive while a fetch runs // share the next one. w.mu must be held. func (w *Workspace) fetchView(id string) { t := w.trackers[id] if t == nil { return } if t.viewing { t.again = true return } t.viewing = true go func() { for { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) view, _, err := w.conn.SessionView(ctx, id) cancel() w.mu.Lock() t := w.trackers[id] if t == nil { w.mu.Unlock() return } if err == nil && view.Revision >= t.view.Revision { t.view = view for _, win := range view.Windows { for _, b := range []string{win.FocusedBlockID, win.ZoomedBlockID} { if b != "" && !t.asked[b] { t.asked[b] = true go w.fetchBlock(id, b) } } } } again := t.again && err == nil t.again = false if !again { t.viewing = false } w.mu.Unlock() w.notify() if !again { return } } }() } // process is a process as com.superlogical.terminal.process and // process_changed describe it. type process struct { Name string `json:"name"` Argv0 string `json:"argv0"` Script string `json:"script"` Cwd string `json:"cwd"` } // processInfo is the part of a terminal's processes a summary uses. type processInfo struct { Foreground *process `json:"foreground"` Ancestors []*process `json:"ancestors"` Home string `json:"home"` } // label names what runs in a terminal: the foreground program, or, for a // shell at its prompt, the last part of its directory. The foreground // process has ancestors in the terminal only when something runs under the // shell. func (p processInfo) label(home string) string { f := p.Foreground if f == nil { return "" } if len(p.Ancestors) == 0 && f.Cwd != "" && shells[f.Name] { if f.Cwd == home && home != "" { return "~" } return path.Base(f.Cwd) } switch { case f.Script != "": return path.Base(f.Script) case f.Argv0 != "": return path.Base(strings.TrimPrefix(f.Argv0, "-")) } return f.Name } // shells are the programs that, at their prompts, a summary names by // their directories. var shells = map[string]bool{ "sh": true, "bash": true, "zsh": true, "fish": true, "dash": true, "ksh": true, "mksh": true, "tcsh": true, "csh": true, "nu": true, "elvish": true, "xonsh": true, "pwsh": true, "login": true, } // fetchBlock asks for what runs in a block, and what its programs say they // are doing. Events that arrive meanwhile are newer, and win. func (w *Workspace) fetchBlock(sessionID, block string) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() var p processInfo perr := w.conn.BlockMethod(ctx, sessionID, block, "com.superlogical.terminal.process", nil, &p) var st struct { Records []struct { ID string `json:"id"` State string `json:"state"` } `json:"records"` } serr := w.conn.BlockMethod(ctx, sessionID, block, "com.superlogical.terminal.program_status", nil, &st) w.mu.Lock() defer w.mu.Unlock() t := w.trackers[sessionID] if t == nil { return } if perr == nil { if p.Home != "" { w.home = p.Home } if _, ok := t.programs[block]; !ok { t.programs[block] = p.label(w.home) } } if serr == nil { if _, ok := t.status[block]; !ok { records := make(map[string]string) for _, r := range st.Records { records[r.ID] = r.State } t.status[block] = records } } w.notify() } // fetchClients asks which clients are attached to a session. w.mu must be // held. func (w *Workspace) fetchClients(id string) { t := w.trackers[id] if t == nil || t.clientsDue { return } t.clientsDue = true go func() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() var list struct { Clients []struct { ClientID string `json:"client_id"` Principal struct { Display string `json:"display"` Node string `json:"node"` } `json:"principal"` Info struct { Kind string `json:"kind"` Name string `json:"name"` Label string `json:"label"` } `json:"info"` ConnectionState string `json:"connection_state"` } `json:"clients"` } _, err := w.conn.Call(ctx, "session.list_clients", map[string]string{"session_id": id}, &list) self := "" if c := w.conn.Welcome().Client; c != nil { self = c.ID } w.mu.Lock() defer w.mu.Unlock() t := w.trackers[id] if t == nil { return } t.clientsDue = false if err != nil { return } t.clients = nil for _, c := range list.Clients { if c.ClientID == self || c.ConnectionState == "lost" || c.Info.Kind == "agent" { continue } name := c.Info.Label for _, n := range []string{c.Info.Name, c.Principal.Node, c.Principal.Display} { if name == "" { name = n } } t.clients = append(t.clients, name) } w.notify() }() } // summarize updates the summaries from a control connection event. func (w *Workspace) summarize(ev rex.Event) { w.mu.Lock() defer w.mu.Unlock() t := w.trackers[ev.SessionID] if t == nil { return } shown := ev.SessionID == w.shownID() switch ev.Name { case "session_view_changed": w.fetchView(ev.SessionID) case "client_connected", "client_disconnected", "client_connection_changed": w.fetchClients(ev.SessionID) case "block_closed": var e struct { BlockID string `json:"block_id"` } if json.Unmarshal(ev.Payload, &e) == nil { delete(t.programs, e.BlockID) delete(t.asked, e.BlockID) delete(t.status, e.BlockID) } case "block_event": var e struct { BlockID string `json:"block_id"` Name string `json:"name"` Payload json.RawMessage `json:"payload"` } if json.Unmarshal(ev.Payload, &e) != nil { return } switch e.Name { case "process_changed": var p processInfo if json.Unmarshal(e.Payload, &p) == nil { t.programs[e.BlockID] = p.label(w.home) } case "bell", "desktop_notification": t.bell = t.bell || !shown case "child_exited": var x struct { ExitCode int `json:"exit_code"` } _ = json.Unmarshal(e.Payload, &x) t.exited = t.exited || !shown t.failed = t.failed || (!shown && x.ExitCode != 0) case "program_status_changed": var x struct { ID string `json:"id"` Record struct { State string `json:"state"` } `json:"record"` } if json.Unmarshal(e.Payload, &x) == nil { if t.status[e.BlockID] == nil { t.status[e.BlockID] = make(map[string]string) } t.status[e.BlockID][x.ID] = x.Record.State } case "program_status_removed": var x struct { IDs []string `json:"ids"` } if json.Unmarshal(e.Payload, &x) == nil { for _, id := range x.IDs { delete(t.status[e.BlockID], id) } } default: return } w.notify() } }