fix: vscode (#279)

This commit is contained in:
Carlos Florêncio
2026-02-24 23:01:41 +00:00
committed by GitHub
parent edf1f6faa5
commit 3a95a43990
8 changed files with 200 additions and 140 deletions
@@ -33,7 +33,7 @@ func (s *Server) handleVscodeProxy(c *gin.Context) {
return
}
proxy := httputil.NewSingleHostReverseProxy(target)
proxy := &httputil.ReverseProxy{}
proxy.Rewrite = func(r *httputil.ProxyRequest) {
r.SetURL(target)
// Strip /api/v1/vscode/proxy prefix and forward remaining path.
@@ -46,6 +46,8 @@ func (s *Server) handleVscodeProxy(c *gin.Context) {
zap.String("forwarded_path", path))
r.Out.URL.Path = path
r.Out.URL.RawPath = ""
// Rewrite Origin to match code-server's host so ensureOrigin check passes.
r.Out.Header.Set("Origin", target.String())
if r.Out.Header.Get("Upgrade") != "" {
r.Out.Header.Set("Connection", "Upgrade")
}
@@ -0,0 +1,153 @@
package api
import (
"io"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"sync"
"testing"
"github.com/kandev/kandev/internal/agentctl/server/process"
)
func TestHandleVscodeProxy_ProxiesRequest(t *testing.T) {
var mu sync.Mutex
var receivedPath, receivedMethod string
mock := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
receivedPath = r.URL.Path
receivedMethod = r.Method
mu.Unlock()
w.WriteHeader(http.StatusOK)
}))
defer mock.Close()
port := mustParsePort(t, mock.URL)
s := newTestServer(t)
s.procMgr.SetVscodeForTest(process.VscodeStatusRunning, port)
// Use a real HTTP server so Gin's responseWriter gets a real http.ResponseWriter
ts := httptest.NewServer(s.router)
defer ts.Close()
resp, err := http.Get(ts.URL + "/api/v1/vscode/proxy/some/path")
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer resp.Body.Close() //nolint:errcheck
_, _ = io.Copy(io.Discard, resp.Body)
if resp.StatusCode != http.StatusOK {
t.Errorf("expected 200, got %d", resp.StatusCode)
}
mu.Lock()
defer mu.Unlock()
if receivedPath != "/some/path" {
t.Errorf("expected path /some/path, got %q", receivedPath)
}
if receivedMethod != http.MethodGet {
t.Errorf("expected GET, got %q", receivedMethod)
}
}
func TestHandleVscodeProxy_RootPath(t *testing.T) {
var mu sync.Mutex
var receivedPath string
mock := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
receivedPath = r.URL.Path
mu.Unlock()
w.WriteHeader(http.StatusOK)
}))
defer mock.Close()
port := mustParsePort(t, mock.URL)
s := newTestServer(t)
s.procMgr.SetVscodeForTest(process.VscodeStatusRunning, port)
ts := httptest.NewServer(s.router)
defer ts.Close()
resp, err := http.Get(ts.URL + "/api/v1/vscode/proxy")
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer resp.Body.Close() //nolint:errcheck
_, _ = io.Copy(io.Discard, resp.Body)
if resp.StatusCode != http.StatusOK {
t.Errorf("expected 200, got %d", resp.StatusCode)
}
mu.Lock()
defer mu.Unlock()
if receivedPath != "/" {
t.Errorf("expected root path /, got %q", receivedPath)
}
}
func TestHandleVscodeProxy_OriginHeader(t *testing.T) {
var mu sync.Mutex
var receivedOrigin string
mock := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
receivedOrigin = r.Header.Get("Origin")
mu.Unlock()
w.WriteHeader(http.StatusOK)
}))
defer mock.Close()
port := mustParsePort(t, mock.URL)
s := newTestServer(t)
s.procMgr.SetVscodeForTest(process.VscodeStatusRunning, port)
ts := httptest.NewServer(s.router)
defer ts.Close()
req, _ := http.NewRequest(http.MethodGet, ts.URL+"/api/v1/vscode/proxy/test", nil)
req.Header.Set("Origin", "http://different-host:9999")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer resp.Body.Close() //nolint:errcheck
_, _ = io.Copy(io.Discard, resp.Body)
mu.Lock()
defer mu.Unlock()
expected := "http://127.0.0.1:" + strconv.Itoa(port)
if receivedOrigin != expected {
t.Errorf("expected Origin %q, got %q", expected, receivedOrigin)
}
}
func TestHandleVscodeProxy_NotRunning(t *testing.T) {
s := newTestServer(t)
req := httptest.NewRequest(http.MethodGet, "/api/v1/vscode/proxy/foo", nil)
w := httptest.NewRecorder()
s.router.ServeHTTP(w, req)
if w.Code != http.StatusServiceUnavailable {
t.Errorf("expected 503, got %d", w.Code)
}
}
func mustParsePort(t *testing.T, rawURL string) int {
t.Helper()
u, err := url.Parse(rawURL)
if err != nil {
t.Fatalf("failed to parse URL: %v", err)
}
port, err := strconv.Atoi(u.Port())
if err != nil {
t.Fatalf("failed to parse port: %v", err)
}
return port
}
@@ -0,0 +1,12 @@
package process
// SetVscodeForTest injects a VscodeManager with the given status and port.
// Intended for use in tests where starting a real code-server is not feasible.
func (m *Manager) SetVscodeForTest(status VscodeStatus, port int) {
m.vscodeMu.Lock()
defer m.vscodeMu.Unlock()
m.vscode = &VscodeManager{
status: status,
port: port,
}
}
+2 -1
View File
@@ -28,7 +28,8 @@ export async function runDev({ repoRoot, backendPort, webPort }: DevOptions): Pr
extra: { KANDEV_MOCK_AGENT: "true", KANDEV_DATABASE_PATH: dbPath },
});
const webEnv = buildWebEnv({ ports, includeMcp: true, debug: true });
const logLevel = process.env.KANDEV_LOGGING_LEVEL?.trim() || process.env.KANDEV_LOG_LEVEL?.trim() || "info";
const logLevel =
process.env.KANDEV_LOGGING_LEVEL?.trim() || process.env.KANDEV_LOG_LEVEL?.trim() || "info";
logStartupInfo({
header: "dev mode: using local repo",
+14 -2
View File
@@ -19,7 +19,13 @@ import { DATA_DIR, HEALTH_TIMEOUT_MS_RELEASE } from "./constants";
import { resolveHealthTimeoutMs, waitForHealth } from "./health";
import { getBinaryName } from "./platform";
import { createProcessSupervisor } from "./process";
import { attachBackendExitHandler, buildBackendEnv, buildWebEnv, logStartupInfo, pickPorts } from "./shared";
import {
attachBackendExitHandler,
buildBackendEnv,
buildWebEnv,
logStartupInfo,
pickPorts,
} from "./shared";
import { launchWebApp } from "./web";
export type StartOptions = {
@@ -116,7 +122,13 @@ export async function runStart({
});
const webEnv = buildWebEnv({ ports, includeMcp: true, production: true, debug });
logStartupInfo({ header: "start mode: using local build", ports, dbPath, includeMcp: true, logLevel });
logStartupInfo({
header: "start mode: using local build",
ports,
dbPath,
includeMcp: true,
logLevel,
});
const supervisor = createProcessSupervisor();
supervisor.attachSignalHandlers();
@@ -42,6 +42,7 @@ import { PreviewController } from "./preview/preview-controller";
import { ReviewDialog } from "@/components/review/review-dialog";
import { useCumulativeDiff } from "@/hooks/domains/session/use-cumulative-diff";
import { formatReviewCommentsAsMarkdown } from "@/components/task/chat/messages/review-comments-attachment";
import { stopVscode } from "@/lib/api/domains/vscode-api";
import { getWebSocketClient } from "@/lib/ws/connection";
import { useToast } from "@/components/toast-provider";
import type { DiffComment } from "@/lib/diff/types";
@@ -512,6 +513,11 @@ function setupLayoutPersistence(
function setupPortalCleanup(api: DockviewReadyEvent["api"]) {
api.onDidRemovePanel((panel) => {
if (useDockviewStore.getState().isRestoringLayout) return;
// Stop code-server when the user explicitly closes the vscode tab
const entry = panelPortalManager.get(panel.id);
if (entry?.component === "vscode" && entry.sessionId) {
stopVscode(entry.sessionId);
}
panelPortalManager.release(panel.id);
});
}
+1 -1
View File
@@ -66,7 +66,7 @@ export function EditorsMenu({ activeSessionId }: EditorsMenuProps) {
</Button>
</TooltipTrigger>
<TooltipContent>
{activeSessionId ? "Open in editor" : "Select a session to open its worktree"}
{activeSessionId ? "Open editor" : "Select a session to open its worktree"}
</TooltipContent>
</Tooltip>
<DropdownMenu>
+9 -135
View File
@@ -1,25 +1,12 @@
"use client";
import { memo, useState, useCallback, useEffect, useRef } from "react";
import {
IconRefresh,
IconExternalLink,
IconPlayerStop,
IconBrandVscode,
IconLoader2,
IconAlertCircle,
} from "@tabler/icons-react";
import { IconBrandVscode, IconLoader2, IconAlertCircle } from "@tabler/icons-react";
import { useTheme } from "next-themes";
import { Button } from "@kandev/ui/button";
import { PanelRoot, PanelBody, PanelFooterBar } from "./panel-primitives";
import { PanelRoot, PanelBody } from "./panel-primitives";
import { useAppStore } from "@/components/state-provider";
import { useDockviewStore } from "@/lib/state/dockview-store";
import {
startVscode,
stopVscode,
getVscodeStatus,
type VscodeStatus,
} from "@/lib/api/domains/vscode-api";
import { startVscode, getVscodeStatus, type VscodeStatus } from "@/lib/api/domains/vscode-api";
import { getBackendConfig } from "@/lib/config";
function VscodeProgress({
@@ -49,9 +36,7 @@ function VscodeProgress({
return (
<div className="h-full w-full flex flex-col items-center justify-center text-muted-foreground gap-4">
<IconLoader2 className="h-10 w-10 text-blue-500 animate-spin" />
<p className="text-sm font-medium">
{status === "installing" ? "Installing VS Code Server" : "Starting VS Code Server"}
</p>
<p className="text-sm font-medium">Starting VS Code Server</p>
{message && <p className="text-xs text-center max-w-xs opacity-70">{message}</p>}
</div>
);
@@ -60,25 +45,16 @@ function VscodeProgress({
function VscodeIframe({ url }: { url: string }) {
const [loaded, setLoaded] = useState(false);
const handleLoad = useCallback(() => {
setTimeout(() => setLoaded(true), 300);
}, []);
return (
<div className="relative h-full w-full bg-card">
{!loaded && (
<div className="absolute inset-0 flex items-center justify-center">
<IconLoader2 className="h-8 w-8 text-muted-foreground animate-spin" />
</div>
)}
<div className="h-full w-full bg-card">
<iframe
src={url}
title="VS Code"
className={`h-full w-full border-0 ${loaded ? "opacity-100" : "opacity-0"}`}
className={`h-full w-full border-0 transition-opacity duration-200 ${loaded ? "opacity-100" : "opacity-0"}`}
sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-downloads"
allow="clipboard-read; clipboard-write"
referrerPolicy="no-referrer"
onLoad={handleLoad}
onLoad={() => setTimeout(() => setLoaded(true), 100)}
/>
</div>
);
@@ -99,18 +75,16 @@ function VscodePanelBody({
isRunning,
isProgress,
iframeUrl,
refreshKey,
onRetry,
}: {
status: VscodeStatus;
isRunning: boolean;
isProgress: boolean;
iframeUrl: string;
refreshKey: number;
onRetry: () => void;
}) {
if (isRunning) {
return <VscodeIframe key={refreshKey} url={iframeUrl} />;
return <VscodeIframe url={iframeUrl} />;
}
if (isProgress) {
return (
@@ -136,7 +110,6 @@ function useVscodeLifecycle() {
const activeSessionId = useAppStore((state) => state.tasks.activeSessionId);
const { resolvedTheme } = useTheme();
const [status, setStatus] = useState<VscodeStatus>({ status: "stopped" });
const [refreshKey, setRefreshKey] = useState(0);
const startedRef = useRef(false);
// Auto-start on mount or session change
@@ -183,23 +156,6 @@ function useVscodeLifecycle() {
return () => clearInterval(interval);
}, [activeSessionId, status.status]);
const handleStop = useCallback(async () => {
if (!activeSessionId) return;
await stopVscode(activeSessionId);
setStatus({ status: "stopped" });
startedRef.current = false;
// Remove the vscode panel from the current layout instead of switching layouts
const dockApi = useDockviewStore.getState().api;
const vscodePanel = dockApi?.getPanel("vscode");
if (vscodePanel) {
try {
dockApi!.removePanel(vscodePanel);
} catch {
/* already removed */
}
}
}, [activeSessionId]);
const handleRetry = useCallback(() => {
if (!activeSessionId) return;
startedRef.current = true;
@@ -212,26 +168,12 @@ function useVscodeLifecycle() {
});
}, [activeSessionId, resolvedTheme]);
const handleRefresh = useCallback(() => {
setRefreshKey((k) => k + 1);
}, []);
const handleOpenInTab = useCallback(() => {
if (status.url) {
window.open(buildBaseUrl(status.url), "_blank", "noopener,noreferrer");
}
}, [status.url]);
const iframeUrl = status.status === "running" && status.url ? buildBaseUrl(status.url) : null;
return {
status,
iframeUrl,
refreshKey,
handleStop,
handleRetry,
handleRefresh,
handleOpenInTab,
};
}
@@ -241,8 +183,7 @@ type VscodePanelProps = {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export const VscodePanel = memo(function VscodePanel({ panelId }: VscodePanelProps) {
const { status, iframeUrl, refreshKey, handleStop, handleRetry, handleRefresh, handleOpenInTab } =
useVscodeLifecycle();
const { status, iframeUrl, handleRetry } = useVscodeLifecycle();
const isRunning = status.status === "running" && iframeUrl;
const isProgress =
@@ -256,76 +197,9 @@ export const VscodePanel = memo(function VscodePanel({ panelId }: VscodePanelPro
isRunning={!!isRunning}
isProgress={isProgress}
iframeUrl={iframeUrl ?? ""}
refreshKey={refreshKey}
onRetry={handleRetry}
/>
</PanelBody>
<VscodePanelFooter
status={status.status}
isRunning={!!isRunning}
onOpenInTab={handleOpenInTab}
onRefresh={handleRefresh}
onStop={handleStop}
/>
</PanelRoot>
);
});
function VscodePanelFooter({
status,
isRunning,
onOpenInTab,
onRefresh,
onStop,
}: {
status: VscodeStatus["status"];
isRunning: boolean;
onOpenInTab: () => void;
onRefresh: () => void;
onStop: () => void;
}) {
return (
<PanelFooterBar>
<div className="flex items-center gap-1 text-xs text-muted-foreground px-1">
<IconBrandVscode className="h-3.5 w-3.5" />
<span>VS Code</span>
{isRunning && <span className="ml-1 h-1.5 w-1.5 rounded-full bg-green-500" />}
{(status === "installing" || status === "starting") && (
<IconLoader2 className="ml-1 h-3 w-3 animate-spin text-blue-500" />
)}
</div>
<div className="flex-1" />
{isRunning && (
<>
<Button
size="sm"
variant="outline"
onClick={onOpenInTab}
className="cursor-pointer"
title="Open in browser tab"
>
<IconExternalLink className="h-4 w-4" />
</Button>
<Button
size="sm"
variant="outline"
onClick={onRefresh}
className="cursor-pointer"
title="Refresh"
>
<IconRefresh className="h-4 w-4" />
</Button>
<Button
size="sm"
variant="outline"
onClick={onStop}
className="cursor-pointer"
title="Stop VS Code"
>
<IconPlayerStop className="h-4 w-4" />
</Button>
</>
)}
</PanelFooterBar>
);
}