-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommands_session.go
More file actions
211 lines (176 loc) · 5.37 KB
/
Copy pathcommands_session.go
File metadata and controls
211 lines (176 loc) · 5.37 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
package main
import (
"encoding/json"
"fmt"
"os"
"strings"
"sync/atomic"
"time"
"github.com/skip2/go-qrcode"
)
// printRaw prints text with \n converted to \r\n for raw terminal mode
func printRaw(format string, args ...interface{}) {
text := fmt.Sprintf(format, args...)
text = strings.ReplaceAll(text, "\n", "\r\n")
fmt.Print(text)
}
// getAIPilotCommand checks if a line is an AIPilot command
func (d *Daemon) getAIPilotCommand(line string) string {
switch line {
case "/qr":
return "qr"
}
return ""
}
// executeAIPilotCommand runs an AIPilot command
func (d *Daemon) executeAIPilotCommand(cmd string) {
switch cmd {
case "qr":
d.showPairingQRInAltScreen()
}
}
// showPairingQRInAltScreen shows QR in alt screen, exits on ESC/Ctrl+C or pairing completion
func (d *Daemon) showPairingQRInAltScreen() {
// Clear agent screen BEFORE switching to alt screen
d.sendToPTY([]byte{0x03}) // Ctrl+C to cancel any input
time.Sleep(20 * time.Millisecond)
d.sendToPTY([]byte{0x0c}) // Ctrl+L to clear/redraw
time.Sleep(50 * time.Millisecond)
// Switch to alternate screen, clear, and hide cursor
fmt.Print(altScreenOn + clearScreen + cursorHome + hideCursor)
// Channel to signal pairing completion
pairingDone := make(chan bool, 1)
// Show QR in raw mode (using \r\n)
d.showPairingQRRaw(func() {
pairingDone <- true
})
// Show exit hint
printRaw("\n%sPress ESC or Ctrl+C to close%s\n", dim, reset)
// Read keys in a goroutine, only exit on ESC or Ctrl+C
// Use atomic flag to signal goroutine to stop
var shouldExit int32
exitRequested := make(chan bool, 1)
go func() {
b := make([]byte, 1)
for {
n, err := os.Stdin.Read(b)
if err != nil || n == 0 {
return
}
// Check if we should exit (pairing completed or screen closed)
if atomic.LoadInt32(&shouldExit) != 0 {
// Forward this key to PTY instead of discarding
d.sendToPTY(b[:n])
return
}
// ESC (0x1b) or Ctrl+C (0x03) to exit
if b[0] == 0x1b || b[0] == 0x03 {
exitRequested <- true
return
}
// Ignore all other keys while in QR screen
}
}()
// Wait for exit key or pairing completion
select {
case <-exitRequested:
// User pressed ESC or Ctrl+C
case <-pairingDone:
// Pairing completed, auto-exit
time.Sleep(500 * time.Millisecond) // Brief pause to show success message
}
// Signal goroutine to stop intercepting keys
atomic.StoreInt32(&shouldExit, 1)
// Restore main screen and show cursor
fmt.Print(showCursor + altScreenOff)
}
// showPairingQRRaw displays pairing QR in raw terminal mode (uses \r\n)
func (d *Daemon) showPairingQRRaw(onComplete func()) {
if d.relayClient == nil || d.pcConfig == nil {
printRaw("%sError: Cannot create pairing QR%s\n", red, reset)
return
}
// Initialize pairing on relay
printRaw("%sCreating pairing code...%s\n", dim, reset)
pairingResp, err := d.relayClient.InitPairing()
if err != nil {
printRaw("%sError: %v%s\n", red, err, reset)
return
}
// Include session info if we have an active session
d.mu.RLock()
sessionID := d.session
workDir := d.workDir
agentType := d.agentType
d.mu.RUnlock()
var sessionInfo *SessionQRInfo
if sessionID != "" {
sessionInfo = &SessionQRInfo{
SessionID: sessionID,
WorkDir: workDir,
AgentType: string(agentType),
}
}
// Create QR data using shared helper
qrData := buildPairingQRData(d.pcConfig, d.relay, pairingResp.Token, sessionInfo)
qrJSON, err := json.Marshal(qrData)
if err != nil {
printRaw("%sError creating QR: %v%s\n", red, err, reset)
return
}
printRaw("\n%sScan to pair a new mobile device:%s\n\n", bold, reset)
// Generate and print QR code with \r\n
qr, err := qrcode.New(string(qrJSON), qrcode.Medium)
if err != nil {
printRaw("%sError generating QR code: %v%s\n", red, err, reset)
return
}
qrStr := qr.ToSmallString(false)
printRaw("%s", qrStr)
printRaw("\n PC: %s\n", d.pcConfig.PCName)
printRaw(" Expires: %s\n", pairingResp.ExpiresAt)
// Start background polling for pairing completion
go d.waitPairingCompletionRaw(pairingResp.Token, onComplete)
}
// waitPairingCompletionRaw waits for pairing completion via WebSocket with raw mode output
func (d *Daemon) waitPairingCompletionRaw(token string, onComplete func()) {
status, err := d.relayClient.WaitPairingViaWebSocket(token, PairingTimeout)
if err != nil {
return // Silently fail
}
switch status.Status {
case "completed":
existingMobile := d.pcConfig.getPairedMobile(status.MobileID)
samePublicKey := existingMobile != nil && existingMobile.PublicKey == status.PublicKey
mobile := PairedMobile{
ID: status.MobileID,
Name: status.MobileName,
PublicKey: status.PublicKey,
PairedAt: time.Now().Format(time.RFC3339),
}
d.pcConfig.addPairedMobile(mobile)
if err := savePCConfig(d.pcConfig); err != nil {
fmt.Printf("%sFailed to save config: %v%s\n", red, err, reset)
}
d.mu.RLock()
oldSessionID := d.session
d.mu.RUnlock()
tokenShared := false
if oldSessionID != "" && !samePublicKey {
tokenShared = d.addTokenForMobile(mobile)
}
// Single line notification
if samePublicKey {
printRaw("\n%s✓ Paired: %s (session unchanged)%s\n", green, mobile.Name, reset)
} else if tokenShared {
printRaw("\n%s✓ Paired: %s (session shared)%s\n", green, mobile.Name, reset)
} else {
printRaw("\n%s✓ Paired: %s%s\n", green, mobile.Name, reset)
}
if onComplete != nil {
onComplete()
}
case "expired":
return
}
}