]> git.giacomolli.uk - onechat/blob - terminal.go
Move shared test helpers into helper files
[onechat] / terminal.go
1 package main
2
3 import (
4 "bufio"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "net"
11 "path/filepath"
12 "strings"
13 )
14
15 // terminalResultLines is the most lines of a tool result that the client shows.
16 const terminalResultLines = 10
17
18 // errTerminalDaemonClosed tells that the daemon closed the connection.
19 var errTerminalDaemonClosed = errors.New("the daemon closed the connection")
20
21 // terminal runs "onechat chat": the terminal client of the daemon. Each line of
22 // input is a user message, and the line /stop interrupts the running turn. The
23 // client shows the replies, the tool calls, and their results as they happen.
24 // It ends at the end of the input or when the daemon closes the connection.
25 func terminal(ctx context.Context, in io.Reader, out io.Writer) error {
26 dir, err := dataDir()
27 if err != nil {
28 return err
29 }
30
31 path := filepath.Join(dir, socketFileName)
32 err = checkSocketPath(path)
33 if err != nil {
34 return err
35 }
36
37 var dialer net.Dialer
38 conn, err := dialer.DialContext(ctx, "unix", path)
39 if err != nil {
40 return fmt.Errorf(`connect to the daemon (start it with "onechat daemon"): %w`, err)
41 }
42
43 return terminalSession(ctx, conn, in, out)
44 }
45
46 // terminalSession runs the client on conn until the input ends, the daemon
47 // closes the connection, or ctx ends, and closes conn. A read of the input that
48 // waits for a line can stay behind when the daemon closes the connection.
49 func terminalSession(ctx context.Context, conn net.Conn, in io.Reader, out io.Writer) error {
50 sent := make(chan error, 1)
51 go func() {
52 sent <- terminalSendLines(ctx, conn, in)
53 }()
54
55 shown := make(chan error, 1)
56 go func() {
57 shown <- terminalShowEvents(conn, out)
58 }()
59
60 var err error
61 select {
62 case err = <-sent:
63 err = errors.Join(err, conn.Close())
64 <-shown
65 case err = <-shown:
66 err = errors.Join(terminalCmpError(err, errTerminalDaemonClosed), conn.Close())
67 case <-ctx.Done():
68 err = conn.Close()
69 <-shown
70 }
71
72 return err
73 }
74
75 // terminalSendLines sends each line of in as a request until the input ends.
76 func terminalSendLines(ctx context.Context, conn net.Conn, in io.Reader) error {
77 encoder := json.NewEncoder(conn)
78 scanner := bufio.NewScanner(in)
79 scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
80 for ctx.Err() == nil && scanner.Scan() {
81 line := scanner.Text()
82 request := SocketRequest{
83 Type: "send",
84 Text: line,
85 }
86
87 switch strings.TrimSpace(line) {
88 case "":
89 continue
90 case stopCommand:
91 request = SocketRequest{
92 Type: "interrupt",
93 }
94 }
95
96 err := encoder.Encode(request)
97 if err != nil {
98 return fmt.Errorf("send to the daemon: %w", err)
99 }
100 }
101
102 return scanner.Err()
103 }
104
105 // terminalShowEvents writes each event from the daemon to out until the
106 // connection closes.
107 func terminalShowEvents(conn net.Conn, out io.Writer) error {
108 scanner := bufio.NewScanner(conn)
109 scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
110 for scanner.Scan() {
111 var event Event
112 err := json.Unmarshal(scanner.Bytes(), &event)
113 if err != nil {
114 return fmt.Errorf("decode event: %w", err)
115 }
116
117 text := terminalEventText(event)
118 if text == "" {
119 continue
120 }
121
122 _, err = io.WriteString(out, text+"\n")
123 if err != nil {
124 return err
125 }
126 }
127
128 return scanner.Err()
129 }
130
131 // terminalCmpError returns err, or fallback when err is nil.
132 func terminalCmpError(err, fallback error) error {
133 if err == nil {
134 return fallback
135 }
136
137 return err
138 }
139
140 // terminalEventText returns the text that the client shows for event, or "" for
141 // none. The client shows a user message only from another source, such as
142 // telegram, because the user typed the others. A tool result shows its first
143 // terminalResultLines lines.
144 func terminalEventText(event Event) string {
145 switch event.Kind {
146 case "ready":
147 return "[connected to " + event.Text + "]"
148 case "user":
149 if event.Source == terminalSource {
150 return ""
151 }
152
153 return "[" + event.Source + "] " + event.Text
154 case "reply":
155 return event.Text
156 case "tool":
157 return "[tool] " + event.Text
158 case "echo":
159 return "[result] " + terminalFirstLines(event.Text, terminalResultLines)
160 case "busy":
161 return "[working]"
162 case "idle":
163 return "[done]"
164 case "error":
165 return "[error] " + event.Text
166 default:
167 return ""
168 }
169 }
170
171 // terminalFirstLines returns the first count lines of text, with the number of
172 // the lines left out.
173 func terminalFirstLines(text string, count int) string {
174 text = strings.TrimRight(text, "\n")
175 lines := strings.Split(text, "\n")
176 if len(lines) <= count {
177 return text
178 }
179
180 return strings.Join(lines[:count], "\n") + fmt.Sprintf("\n[%d more lines]", len(lines)-count)
181 }