Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 21 additions & 7 deletions desktop/src-tauri/src/sidecar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
//! spawns `jcode web --headless` on it, waits until /api/health answers, stores
//! the port in the managed `SidecarPort` state (so the frontend can resolve an
//! absolute `http://127.0.0.1:<port>` API base via the `get_sidecar_port` IPC
//! command), then reveals the window.
//! command), then keeps health-polling so startup failures can be surfaced.

use std::collections::VecDeque;
use std::io::Write as _;
Expand Down Expand Up @@ -159,6 +159,15 @@ pub fn start(app: &AppHandle) -> Result<(), Box<dyn std::error::Error>> {
}
}

// Show the frontend shell as soon as the sidecar has been spawned. The page
// itself waits for /api/health before issuing API calls, but keeping the
// native window hidden until then makes slow sidecar boot look like a blank
// or stuck app.
if let Some(w) = app.get_webview_window("main") {
let _ = w.show();
let _ = w.set_focus();
}

// `ready` flips true once the sidecar's /api/health answers. Until then, the
// sidecar exiting is a fatal *startup* failure that we surface to the user —
// previously such a crash left the splash spinning forever, which is exactly
Expand Down Expand Up @@ -218,7 +227,7 @@ pub fn start(app: &AppHandle) -> Result<(), Box<dyn std::error::Error>> {
}
});

// Health-poll the port on a background thread, then reveal the window. We
// Health-poll the port on a background thread. We
// verify the /api/health response (not just a bare TCP connect) so that if
// another process grabbed the port in the moment between pick_free_port and
// the sidecar binding it, the frontend won't be pointed at a foreign server.
Expand All @@ -237,7 +246,6 @@ pub fn start(app: &AppHandle) -> Result<(), Box<dyn std::error::Error>> {
if health_ok(&addr, port) {
poll_ready.store(true, Ordering::SeqCst);
if let Some(w) = app.get_webview_window("main") {
let _ = w.show();
let _ = w.set_focus();
}
return;
Expand Down Expand Up @@ -305,9 +313,8 @@ fn health_ok(addr: &SocketAddr, port: u16) -> bool {
let _ = stream.set_read_timeout(Some(Duration::from_millis(600)));
let _ = stream.set_write_timeout(Some(Duration::from_millis(600)));

let req = format!(
"GET /api/health HTTP/1.0\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n"
);
let req =
format!("GET /api/health HTTP/1.0\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n");
if stream.write_all(req.as_bytes()).is_err() {
return false;
}
Expand All @@ -328,5 +335,12 @@ fn health_ok(addr: &SocketAddr, port: u16) -> bool {
}

let resp = String::from_utf8_lossy(&buf);
resp.starts_with("HTTP/1.") && resp.contains(" 200 ") && resp.contains("\"status\"")
let status_ok = resp
.lines()
.next()
.and_then(|line| line.split_whitespace().nth(1))
.map(|code| code == "200")
.unwrap_or(false);

status_ok && resp.contains("\"status\"")
}
19 changes: 9 additions & 10 deletions internal/command/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,16 +255,12 @@ func runWebServer(port int, host string, openBrowser bool, authToken string) err

registry := internalmodel.NewModelRegistryWithConfig(cfg)

// Load MCP tools. mcpToolsPtr is swapped atomically by reloadMCPTools so a new
// task (built concurrently by buildWebTask) always reads a consistent slice
// header without a data race on hot-reload.
// MCP tools are loaded asynchronously after the web server starts listening.
// A slow remote MCP server must not block /api/health and make desktop launch
// look hung. mcpToolsPtr is swapped atomically by reloadMCPTools so a new task
// (built concurrently by buildWebTask) always reads a consistent slice header
// without a data race on hot-reload.
var mcpToolsPtr atomic.Pointer[[]tool.BaseTool]
var initialMCPStatuses []tools.MCPStatus
if len(cfg.MCPServers) > 0 {
mt, statuses := tools.LoadMCPTools(ctx, cfg.MCPServers)
mcpToolsPtr.Store(&mt)
initialMCPStatuses = statuses
}
reloadMCPTools := func(servers map[string]*config.MCPServer) ([]tools.MCPStatus, error) {
nt, statuses := tools.LoadMCPTools(ctx, servers)
mcpToolsPtr.Store(&nt)
Expand Down Expand Up @@ -780,7 +776,6 @@ func runWebServer(port int, host string, openBrowser bool, authToken string) err
SkillLoader: skillLoader,
FlowLoader: flowLoader,
ReloadMCP: reloadMCPTools,
InitialMCPStatuses: initialMCPStatuses,
WechatClient: wechatClient,
WebHandler: bootEC.Handler,
EventHandler: bootEC.EventHandler,
Expand All @@ -803,6 +798,10 @@ func runWebServer(port int, host string, openBrowser bool, authToken string) err
go sched.Run(ctx)
}

if len(cfg.MCPServers) > 0 {
srv.ReloadMCPInBackground()
}

// Set up inbound WeChat message handler now that srv exists. Always register
// regardless of WebEnabled — the user can enable via the UI. Inbound messages
// target the active task (no task_id channel).
Expand Down
49 changes: 48 additions & 1 deletion internal/web/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2009,12 +2009,59 @@ func serverFromReq(req *mcpServerReq) (*config.MCPServer, error) {
return srv, nil
}

func cloneMCPServers(in map[string]*config.MCPServer) map[string]*config.MCPServer {
if len(in) == 0 {
return nil
}
out := make(map[string]*config.MCPServer, len(in))
for name, srv := range in {
if srv == nil {
out[name] = nil
continue
}
cp := *srv
cp.Args = append([]string(nil), srv.Args...)
cp.Env = append([]string(nil), srv.Env...)
if srv.Headers != nil {
cp.Headers = make(map[string]string, len(srv.Headers))
for k, v := range srv.Headers {
cp.Headers[k] = v
}
}
if srv.OAuth != nil {
oa := *srv.OAuth
oa.Scopes = append([]string(nil), srv.OAuth.Scopes...)
cp.OAuth = &oa
}
out[name] = &cp
}
return out
}

// ReloadMCPInBackground connects configured MCP servers without blocking web
// startup. Slow or unreachable MCP servers should update settings/tool state
// when they finish, never delay /api/health or the desktop window.
func (s *Server) ReloadMCPInBackground() {
if s.reloadMCP == nil {
return
}
go func() {
config.Logger().Printf("[web] loading MCP tools in background")
if err := s.reloadMCPAndRebuild(); err != nil {
config.Logger().Printf("[web] background MCP reload failed: %v", err)
} else {
config.Logger().Printf("[web] background MCP reload finished")
}
s.wsBroker.Broadcast(WSEvent{Type: "mcp_changed", Data: map[string]string{"source": "startup"}})
}()
}

// reloadMCPAndRebuild reconnects MCP servers from the current config and
// rebuilds the live agent so new tools take effect without a restart.
func (s *Server) reloadMCPAndRebuild() error {
if s.reloadMCP != nil {
s.mu.RLock()
servers := s.cfg.MCPServers
servers := cloneMCPServers(s.cfg.MCPServers)
s.mu.RUnlock()
statuses, err := s.reloadMCP(servers)
if err != nil {
Expand Down
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pnpm-workspace.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ packages:
- 'packages/*'
- 'web-react'
allowBuilds:
'@parcel/watcher': true
esbuild: true
# Native build scripts to allow. esbuild (Vite's bundler) and @parcel/watcher
# (dev-server file watching) are trusted toolchain deps — whitelisting them
Expand Down
71 changes: 70 additions & 1 deletion web-react/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,67 @@
<link rel="icon" type="image/svg+xml" href="/icon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>jcode</title>
<style>
.boot-screen {
position: fixed;
inset: 0;
display: grid;
place-items: center;
background: var(--color-background, #f7f7f4);
color: var(--color-foreground, #171717);
font-family: Geist, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
.boot-card {
display: flex;
flex-direction: column;
align-items: center;
gap: 14px;
}
.boot-logo {
font-family: "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 26px;
font-weight: 800;
letter-spacing: 0;
}
.boot-logo span:first-child,
.boot-logo span:last-child {
color: var(--color-muted-foreground, #8a8a84);
}
.boot-logo b {
color: var(--color-primary, #ff7a00);
}
.boot-copy {
color: var(--color-muted-foreground, #73736d);
font-size: 14px;
}
.boot-dots {
display: flex;
gap: 5px;
}
.boot-dots span {
width: 5px;
height: 5px;
border-radius: 999px;
background: var(--color-primary, #ff7a00);
animation: boot-pulse 1.1s ease-in-out infinite;
}
.boot-dots span:nth-child(2) {
animation-delay: 140ms;
}
.boot-dots span:nth-child(3) {
animation-delay: 280ms;
}
@keyframes boot-pulse {
0%, 80%, 100% { opacity: .32; transform: translateY(0); }
40% { opacity: 1; transform: translateY(-3px); }
}
@media (prefers-color-scheme: dark) {
.boot-screen {
background: var(--color-background, #111111);
color: var(--color-foreground, #f6f6f2);
}
}
</style>
<!-- Pre-mount theme resolution: apply the saved theme BEFORE the bundle loads
so there's no flash of the wrong theme. Mirrors web/index.html. -->
<script>
Expand All @@ -27,7 +88,15 @@
</script>
</head>
<body>
<div id="root"></div>
<div id="root">
<div class="boot-screen" role="status" aria-live="polite">
<div class="boot-card">
<div class="boot-logo"><span>[</span><b>J</b>CODE<span>]</span></div>
<div class="boot-copy">Starting local server...</div>
<div class="boot-dots" aria-hidden="true"><span></span><span></span><span></span></div>
</div>
</div>
</div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
1 change: 1 addition & 0 deletions web-react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
},
"dependencies": {
"@heroicons/react": "^2.2.0",
"@lobehub/icons-static-svg": "^1.91.0",
"@reduxjs/toolkit": "^2.8.2",
"@tauri-apps/api": "^2.9.0",
"@tauri-apps/plugin-dialog": "^2.0.0",
Expand Down
Loading
Loading