This repository was archived by the owner on Apr 14, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.go
More file actions
330 lines (282 loc) · 8.09 KB
/
app.go
File metadata and controls
330 lines (282 loc) · 8.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
)
// Service labels
const (
KernelLabel = "com.cogos.kernel"
DefaultPort = 5200 // fallback only — prefer reading from workspace config
)
// ServiceStatus represents the status of a managed service
type ServiceStatus struct {
Name string `json:"name"`
Label string `json:"label"`
Port int `json:"port"`
Running bool `json:"running"`
Healthy bool `json:"healthy"`
Launchd bool `json:"launchd"`
PID *int `json:"pid"`
ExitCode *int `json:"exitCode"`
}
// App struct - the main application
type App struct {
ctx context.Context
workspaceRoot string
kernelPort int
terminal *TerminalManager
}
// NewApp creates a new App application struct
func NewApp() *App {
app := &App{}
app.terminal = NewTerminalManager(app)
return app
}
// startup is called when the app starts
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
a.workspaceRoot = a.findWorkspaceRoot()
a.kernelPort = a.resolveKernelPort()
}
// resolveKernelPort reads the port from workspace config, falling back to default.
func (a *App) resolveKernelPort() int {
if a.workspaceRoot == "" {
return DefaultPort
}
// Read from .cog/config/kernel.yaml
configPath := filepath.Join(a.workspaceRoot, ".cog", "config", "kernel.yaml")
data, err := os.ReadFile(configPath)
if err != nil {
return DefaultPort
}
// Simple YAML parsing for port field — avoids yaml dependency
for _, line := range strings.Split(string(data), "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "port:") {
val := strings.TrimSpace(strings.TrimPrefix(line, "port:"))
if p, err := strconv.Atoi(val); err == nil && p > 0 {
return p
}
}
}
return DefaultPort
}
// shutdown is called when the app is closing
func (a *App) shutdown(ctx context.Context) {
if a.terminal != nil {
a.terminal.CloseAll()
}
}
// === TERMINAL METHODS ===
// StartTerminal starts a new terminal session
func (a *App) StartTerminal(id string) error {
return a.terminal.StartSession(id, "", "")
}
// WriteTerminal writes to a terminal session
func (a *App) WriteTerminal(id string, data string) error {
return a.terminal.WriteToSession(id, data)
}
// ResizeTerminal resizes a terminal session
func (a *App) ResizeTerminal(id string, cols int, rows int) error {
return a.terminal.ResizeSession(id, uint16(cols), uint16(rows))
}
// CloseTerminal closes a terminal session
func (a *App) CloseTerminal(id string) error {
return a.terminal.CloseSession(id)
}
// findWorkspaceRoot locates the CogOS workspace
func (a *App) findWorkspaceRoot() string {
// Check common locations
home, _ := os.UserHomeDir()
candidates := []string{
filepath.Join(home, "workspace"),
filepath.Join(home, "cog-workspace"),
}
for _, path := range candidates {
if _, err := os.Stat(filepath.Join(path, ".cog")); err == nil {
return path
}
}
// Try current directory
cwd, _ := os.Getwd()
if _, err := os.Stat(filepath.Join(cwd, ".cog")); err == nil {
return cwd
}
return ""
}
// GetWorkspaceRoot returns the workspace root path
func (a *App) GetWorkspaceRoot() string {
return a.workspaceRoot
}
// GetServices returns the status of all managed services
// Now only returns kernel status (cog-chat service retired)
func (a *App) GetServices() []ServiceStatus {
services := []struct {
name string
label string
port int
health string
}{
{"kernel", KernelLabel, a.kernelPort, fmt.Sprintf("http://localhost:%d/health", a.kernelPort)},
}
result := make([]ServiceStatus, 0)
for _, svc := range services {
status := ServiceStatus{
Name: svc.name,
Label: svc.label,
Port: svc.port,
Running: false,
Healthy: false,
Launchd: false,
}
// Check launchd status
cmd := exec.Command("launchctl", "list", svc.label)
output, err := cmd.Output()
if err == nil {
status.Launchd = true
// Parse output: "PID\tStatus\tLabel"
lines := strings.Split(string(output), "\n")
if len(lines) > 0 {
fields := strings.Fields(lines[0])
if len(fields) >= 2 {
if pid, err := strconv.Atoi(fields[0]); err == nil && pid > 0 {
status.PID = &pid
status.Running = true
}
if exitCode, err := strconv.Atoi(fields[1]); err == nil {
status.ExitCode = &exitCode
}
}
}
}
// Check health endpoint
client := &http.Client{Timeout: 2 * time.Second}
resp, err := client.Get(svc.health)
if err == nil {
status.Healthy = resp.StatusCode == http.StatusOK
resp.Body.Close()
status.Running = true
}
result = append(result, status)
}
return result
}
// RestartService restarts a service via launchctl
func (a *App) RestartService(serviceName string) (bool, string) {
labels := map[string]string{
"kernel": KernelLabel,
}
label, ok := labels[serviceName]
if !ok {
return false, "Unknown service: " + serviceName
}
uid := os.Getuid()
cmd := exec.Command("launchctl", "kickstart", "-k", fmt.Sprintf("gui/%d/%s", uid, label))
output, err := cmd.CombinedOutput()
if err != nil {
return false, fmt.Sprintf("Failed to restart: %s - %s", err.Error(), string(output))
}
return true, "Service restarted"
}
// StartService starts a service via launchctl
func (a *App) StartService(serviceName string) (bool, string) {
labels := map[string]string{
"kernel": KernelLabel,
}
label, ok := labels[serviceName]
if !ok {
return false, "Unknown service: " + serviceName
}
uid := os.Getuid()
cmd := exec.Command("launchctl", "kickstart", fmt.Sprintf("gui/%d/%s", uid, label))
output, err := cmd.CombinedOutput()
if err != nil {
return false, fmt.Sprintf("Failed to start: %s - %s", err.Error(), string(output))
}
return true, "Service started"
}
// StopService stops a service via launchctl
func (a *App) StopService(serviceName string) (bool, string) {
labels := map[string]string{
"kernel": KernelLabel,
}
label, ok := labels[serviceName]
if !ok {
return false, "Unknown service: " + serviceName
}
uid := os.Getuid()
cmd := exec.Command("launchctl", "kill", "SIGTERM", fmt.Sprintf("gui/%d/%s", uid, label))
output, err := cmd.CombinedOutput()
if err != nil {
return false, fmt.Sprintf("Failed to stop: %s - %s", err.Error(), string(output))
}
return true, "Service stopped"
}
// EnableService registers a service with launchd
func (a *App) EnableService(serviceName string) (bool, string) {
if a.workspaceRoot == "" {
return false, "Workspace not found"
}
switch serviceName {
case "kernel":
// Use the kernel's built-in enable command
cmd := exec.Command(filepath.Join(a.workspaceRoot, ".cog", "cog"), "serve", "enable")
cmd.Dir = a.workspaceRoot
output, err := cmd.CombinedOutput()
if err != nil {
return false, fmt.Sprintf("Failed to enable: %s - %s", err.Error(), string(output))
}
return true, "Kernel enabled for auto-start"
default:
return false, "Unknown service: " + serviceName
}
}
// GetKernelHealth fetches health info from the kernel
func (a *App) GetKernelHealth() map[string]interface{} {
client := &http.Client{Timeout: 2 * time.Second}
resp, err := client.Get(fmt.Sprintf("http://localhost:%d/health", a.kernelPort))
if err != nil {
return map[string]interface{}{
"status": "unreachable",
"error": err.Error(),
}
}
defer resp.Body.Close()
var health map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&health); err != nil {
return map[string]interface{}{
"status": "error",
"error": err.Error(),
}
}
return health
}
// GetKernelStatus fetches raw status JSON from the kernel health endpoint.
func (a *App) GetKernelStatus() (string, error) {
client := &http.Client{Timeout: 2 * time.Second}
resp, err := client.Get(fmt.Sprintf("http://localhost:%d/health", a.kernelPort))
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("kernel health request failed with status %d", resp.StatusCode)
}
if !json.Valid(body) {
return "", fmt.Errorf("kernel health response is not valid JSON")
}
return string(body), nil
}