-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathstart.go
More file actions
237 lines (204 loc) · 6.7 KB
/
start.go
File metadata and controls
237 lines (204 loc) · 6.7 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
package app
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"sync"
twctx "github.com/tinywasm/context"
"github.com/tinywasm/devflow"
"github.com/tinywasm/mcp"
"github.com/tinywasm/sse"
)
// TestMode disables browser auto-start when running tests
var TestMode bool
// Start is called from main.go with UI, Browser and DB passed as parameters
// CRITICAL: UI, Browser and DB instances created in main.go, passed here as interfaces
// mcpToolHandlers: optional external Handlers that implement Tools() for MCP tool discovery
// onProjectReady: optional callback called after handler initialization (for daemon mode to set up proxy)
func Start(startDir string, logger func(messages ...any), ui TuiInterface, browser BrowserInterface, db DB, ExitChan chan bool, serverFactory ServerFactory, githubAuth any, gitHandler devflow.GitClient, goModHandler devflow.GoModInterface, headless bool, clientMode bool, onProjectReady func(*Handler), mcpToolHandlers ...mcp.ToolProvider) bool {
// Initialize Go Handler
GoHandler, _ := devflow.NewGo(gitHandler)
GoHandler.SetRootDir(startDir)
h := &Handler{
FrameworkName: "TINYWASM",
RootDir: startDir,
Tui: ui, // UI passed from main.go
ExitChan: ExitChan,
Logger: logger,
DB: db,
serverFactory: serverFactory,
GitHandler: gitHandler,
GoHandler: GoHandler,
Browser: browser,
GitHubAuth: githubAuth,
GoModHandler: goModHandler,
}
// Noop initial logger to avoid nil check issues
h.Logger = logger
// Check if we are in dev mode
h.CheckDevMode()
// Wire gitignore notification
if !TestMode {
gitHandler.SetShouldWrite(h.IsInitializedProject)
}
// Validate directory
homeDir, _ := os.UserHomeDir()
if startDir == homeDir || startDir == "/" {
logger("Cannot run tinywasm in user root directory. Please run in a Go project directory")
return false
}
var wg sync.WaitGroup
wg.Add(1) // UI goroutine; MCP added below only in standalone (non-headless) mode
// ADD SECTIONS using the passed UI interface
// CRITICAL: Initialize sections BEFORE starting lifecycle
h.SectionBuild = h.AddSectionBUILD()
h.AddSectionDEPLOY()
// Register GitHubAuth in TUI FIRST (so it gets the TUI logger)
// This must happen BEFORE starting the auth Future
if h.GitHubAuth != nil {
h.Tui.AddHandler(h.GitHubAuth, "#6e40c9", h.SectionBuild) // Purple for GitHub
}
// Early return for clientMode: we just needed to construct the TUI sections.
// We don't want to run Github auth, GoNew, watchers, or the local MCP server in the client.
if clientMode {
var clientWg sync.WaitGroup
clientWg.Add(1)
go h.Tui.Start(&clientWg)
clientWg.Wait()
return false
}
// NOW start GitHub auth in background (after TUI registration)
// This ensures the TUI logger is set before auth messages are sent
githubFuture := devflow.NewFuture(func() (any, error) {
if githubAuth != nil {
if auth, ok := githubAuth.(devflow.GitHubAuthenticator); ok {
return devflow.NewGitHub(logger, auth)
}
}
return devflow.NewGitHub(logger)
})
// Initialize GoNew orchestrator with the future
GoNew := devflow.NewGoNew(gitHandler, githubFuture, GoHandler)
GoNew.SetLog(logger)
h.GoNew = GoNew
// Prevents goroutine leak: drain future when app exits so the
// internal goroutine can proceed to close(f.done) and exit.
go func() {
select {
case <-ExitChan:
<-githubFuture.Ready() // unblock the future's sender goroutine
case <-githubFuture.Ready():
// already resolved, nothing to do
}
}()
// Call onProjectReady callback (used by daemon to set up tool proxy)
if onProjectReady != nil {
onProjectReady(h)
}
if !h.IsPartOfProject() {
sectionWizard := h.AddSectionWIZARD(func() {
h.OnProjectReady(&wg)
})
h.Tui.SetActiveTab(sectionWizard)
} else {
h.OnProjectReady(&wg)
}
if !headless {
// Standalone mode: create and serve the project-level HTTP server on port 3030.
// In headless/daemon-sub-project mode this is skipped to avoid a port conflict
// with the already-running global daemon MCP.
mcpPort := "3030"
if p := os.Getenv("TINYWASM_MCP_PORT"); p != "" {
mcpPort = p
}
// Create SSE server for log transport
tinySSE := sse.New(&sse.Config{})
sseServer := tinySSE.Server(&sse.ServerConfig{
ChannelProvider: &logChannelProvider{},
ClientChannelBuffer: 256,
HistoryReplayBuffer: 100,
ReplayAllOnConnect: true,
})
ssePub := NewSSEPublisher(sseServer)
h.Logger = func(messages ...any) {
logger(messages...)
ssePub.PublishLog(fmt.Sprint(messages...))
}
appVersion := "1.0.0"
// Try to get version from DB if available, or just use 1.0.0
if val, err := h.DB.Get("TINYWASM_VERSION"); err == nil && val != "" {
appVersion = val
}
mcpConfig := mcp.Config{
Name: "TinyWasm - Full-stack Go+WASM Dev Environment",
Version: appVersion,
Auth: mcp.OpenAuthorizer(),
SSE: sseServer,
}
// Use buildProjectProviders for single source of truth
toolHandlers := buildProjectProviders(h)
toolHandlers = append(toolHandlers, mcpToolHandlers...)
var err error
h.MCP, err = mcp.NewServer(mcpConfig, toolHandlers)
if err != nil {
logger("Failed to initialize MCP Server:", err)
return false
}
// Configure IDEs (standalone mode)
if err := ConfigureIDEs("tinywasm", appVersion, mcpPort, ""); err != nil {
logger("Warning: Failed to configure IDEs:", err)
}
h.Tui.AddHandler(h.MCP, colorOrangeLight, h.SectionBuild)
SetActiveHandler(h)
mux := http.NewServeMux()
mux.Handle("/logs", sseServer)
mux.HandleFunc("POST /mcp", func(w http.ResponseWriter, r *http.Request) {
var msg []byte
if r.Body != nil {
msg, _ = io.ReadAll(r.Body)
}
ctx := twctx.Background()
resp := h.MCP.HandleMessage(ctx, msg)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
})
mux.HandleFunc("GET /tinywasm/state", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write(h.Tui.GetHandlerStates())
})
mux.HandleFunc("GET /version", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(appVersion))
})
server := &http.Server{
Addr: ":" + mcpPort,
Handler: mux,
}
// Start HTTP server
wg.Add(1)
go func() {
defer wg.Done()
go func() {
<-ExitChan
server.Close()
}()
logger("Standalone listener on", server.Addr)
if err := server.ListenAndServe(); err != http.ErrServerClosed {
logger("Standalone server error:", err)
}
}()
// Start the UI
go h.Tui.Start(&wg)
} else {
// Headless mode: no HTTP, no UI. Keep alive until ExitChan is closed.
wg.Add(1)
go func() {
defer wg.Done()
<-ExitChan
}()
wg.Done() // satisfy the initial wg.Add(1) for UI
}
wg.Wait()
return h.RestartRequested
}