diff --git a/src/features/debugger/state.ts b/src/features/debugger/state.ts index 0a8a1a50f1..77c8ebddf3 100644 --- a/src/features/debugger/state.ts +++ b/src/features/debugger/state.ts @@ -35,7 +35,7 @@ import { toolWindowService, useDebugRunSessions, } from "@/workbench/contributions"; -import { startedPort } from "@/platform/serverPort"; +import { startedServer, type StartedServer } from "@/platform/serverPort"; import { breakpointsOf, consumeTemporary, flushBreakpoints, refreshStates, resetStatuses } from "./breakpoints/store"; import { interpolateLog, logParts, suspends } from "./breakpoints/model"; import { syncSpecial, useSpecialBreakpoints } from "./breakpoints/special"; @@ -523,6 +523,7 @@ export function publishContext() { status: paused ? ("paused" as const) : session.status, processId: session.process, httpPort: sessionHttpPort(session.id), + httpPath: sessionHttpPath(session.id), rerun: session.runConfig || session.launch ? () => void rerunSession(session.id) : null, rerunInPlace: session.runConfig || session.launch ? () => void rerunSession(session.id, { show: false }) : null, @@ -586,26 +587,37 @@ export function publishContext() { /** * The HTTP port the session's application announced on its console ("Tomcat started on - * port 8080"), the same embedded web server line the Run console is parsed for. Kept per - * session, so the Services node keeps the port after the line scrolls out of the buffer. + * port 8080 with context path '/api'"), the same embedded web server line the Run console + * is parsed for. Kept per session, so the Services node keeps it after the line scrolls out + * of the buffer. */ -const announcedPorts = new Map(); +const announcedServers = new Map(); -export function sessionHttpPort(id: DebugSessionId): number | undefined { - let port: number | undefined; +function sessionServer(id: DebugSessionId): StartedServer | undefined { + let found: StartedServer | undefined; for (const line of useDebug.getState().console[id] ?? []) { - const found = startedPort(line.text); - if (found !== null) port = found; + const started = startedServer(line.text); + if (started !== null) found = started; } - if (port !== undefined) announcedPorts.set(id, port); - else port = announcedPorts.get(id); - return port; + if (found) announcedServers.set(id, found); + else found = announcedServers.get(id); + return found; } -/** Republishes Services metadata only when a console announced a port it had not shown yet. */ +export function sessionHttpPort(id: DebugSessionId): number | undefined { + return sessionServer(id)?.port; +} + +/** The servlet context path the same line reported, "" when it reported none. */ +export function sessionHttpPath(id: DebugSessionId): string { + return sessionServer(id)?.path ?? ""; +} + +/** Republishes Services metadata only when a console announced an address it had not shown yet. */ function republishForPorts() { const published = useDebugRunSessions.getState().serviceSessions; - if (published.some((d) => d.httpPort !== sessionHttpPort(d.id))) publishContext(); + if (published.some((d) => d.httpPort !== sessionHttpPort(d.id) || (d.httpPath ?? "") !== sessionHttpPath(d.id))) + publishContext(); } /** Sessions attached to a process Run started: their Console follows its output. */ @@ -1787,7 +1799,7 @@ export function resetSessions() { pendingOutput.length = 0; cancelOutputFlush(); ansiStreams.clear(); - announcedPorts.clear(); + announcedServers.clear(); serverPages.clear(); pendingDropped.clear(); useDebug.setState({ sessions: {}, active: null, console: {}, consoleDropped: {}, stopSeq: 0, variablesEpoch: 0 }); diff --git a/src/features/run/services.test.ts b/src/features/run/services.test.ts index 7b39a270cc..2ef33b6319 100644 --- a/src/features/run/services.test.ts +++ b/src/features/run/services.test.ts @@ -26,7 +26,7 @@ import { sessionStatus, } from "./services"; import { KIND_OPTIONS, categoryOf } from "./configs"; -import { startedPort } from "@/platform/serverPort"; +import { startedServer } from "@/platform/serverPort"; import { registerRunConfigType, registerRunExecutor, @@ -320,16 +320,29 @@ describe("sessions of types not added", () => { }); describe("embedded web server port", () => { + const port = (line: string) => startedServer(line)?.port ?? null; + it("reads the port from the started line", () => { - expect(startedPort("TomcatWebServer : Tomcat started on port 8080 (http) with context path '/'")).toBe(8080); - expect(startedPort("Tomcat started on port(s): 8081 (http) with context path ''")).toBe(8081); - expect(startedPort("o.s.b.web.embedded.netty.NettyWebServer : Netty started on port 9090")).toBe(9090); - expect(startedPort("Netty started on port(s): 9091")).toBe(9091); - expect(startedPort("Undertow started on port(s) 8082 (http)")).toBe(8082); - expect(startedPort("Jetty started on port 9083 (http/1.1) with context path '/'")).toBe(9083); - expect(startedPort("Tomcat initialized with port 8080 (http)")).toBeNull(); - expect(startedPort("Started DemoApplication in 1.2 seconds")).toBeNull(); - expect(startedPort("Tomcat started on port 99999")).toBeNull(); + expect(port("TomcatWebServer : Tomcat started on port 8080 (http) with context path '/'")).toBe(8080); + expect(port("Tomcat started on port(s): 8081 (http) with context path ''")).toBe(8081); + expect(port("o.s.b.web.embedded.netty.NettyWebServer : Netty started on port 9090")).toBe(9090); + expect(port("Netty started on port(s): 9091")).toBe(9091); + expect(port("Undertow started on port(s) 8082 (http)")).toBe(8082); + expect(port("Jetty started on port 9083 (http/1.1) with context path '/'")).toBe(9083); + expect(port("Tomcat initialized with port 8080 (http)")).toBeNull(); + expect(port("Started DemoApplication in 1.2 seconds")).toBeNull(); + expect(port("Tomcat started on port 99999")).toBeNull(); + }); + + it("reads the context path the same line reports", () => { + const started = (line: string) => startedServer(line)?.path; + expect(started("Tomcat started on port 8080 (http) with context path '/api'")).toBe("/api"); + expect(started("Tomcat started on port 8080 (http) with context path '/api/'")).toBe("/api"); + expect(started("Tomcat started on port 8080 (http) with context path 'api'")).toBe("/api"); + expect(started("Tomcat started on port 8080 (http) with context path '/'")).toBe(""); + expect(started("Tomcat started on port(s): 8081 (http) with context path ''")).toBe(""); + expect(started("Netty started on port 9090")).toBe(""); + expect(startedServer("Tomcat started on port 99999")).toBeNull(); }); }); @@ -561,12 +574,33 @@ describe("add service categories", () => { describe("open in browser", () => { const item = () => ({ key: "run:config:a", label: "a", icon: "" }); const hasBrowser = () => !runServiceProvider.actions!(item()).find((a) => a.id === "open-browser")?.disabled; + const browser = () => runServiceProvider.actions!(item()).find((a) => a.id === "open-browser")!; beforeEach(() => { useProject.setState({ project: null }); useRun.setState({ configs: [], sessions: [] }); }); + it("opens the context path the embedded web server announced (#7383)", async () => { + const running = config("a", "spring-boot"); + useRun.setState({ + configs: [running], + sessions: [session("s1", running, "running", 1, { httpPort: 8080, httpPath: "/api" })], + }); + await browser().run(); + expect(openUrl).toHaveBeenCalledWith("http://localhost:8080/api/"); + }); + + it("opens the root URL when the server reports no context path", async () => { + const running = config("a", "spring-boot"); + useRun.setState({ + configs: [running], + sessions: [session("s1", running, "running", 1, { httpPort: 8080 })], + }); + await browser().run(); + expect(openUrl).toHaveBeenCalledWith("http://localhost:8080"); + }); + it("offers Open in Browser while a session runs with an HTTP port", () => { useRun.setState({ configs: [config("a", "spring-boot")], @@ -718,6 +752,7 @@ describe("group batch actions", () => { processId: null, startedAt: 2, httpPort: 8456, + httpPath: "/b", stop: async () => {}, rerun: null, show: () => {}, @@ -729,10 +764,10 @@ describe("group batch actions", () => { const choices = showContextMenu.mock.calls[0]![1]; expect(choices.map((c: { label: string }) => c.label)).toEqual([ "a — http://localhost:8123", - "b — http://localhost:8456", + "b — http://localhost:8456/b/", ]); choices[1].run(); - expect(openUrl).toHaveBeenCalledWith("http://localhost:8456"); + expect(openUrl).toHaveBeenCalledWith("http://localhost:8456/b/"); }); }); diff --git a/src/features/run/services.tsx b/src/features/run/services.tsx index 34fdb3319e..fd8ed227a7 100644 --- a/src/features/run/services.tsx +++ b/src/features/run/services.tsx @@ -563,7 +563,10 @@ function browserActions(sessions: readonly ServiceSession[]): ServiceItemAction[ for (const s of sessions) { if (!liveServiceSession(s)) continue; const port = (s.run && isLive(s.run) ? s.run.httpPort : undefined) ?? serviceDebugger(s)?.httpPort; - if (port && Number.isInteger(port) && port > 0 && port < 65536) urls.set(`http://localhost:${port}`, s.config.name); + if (!port || !Number.isInteger(port) || port <= 0 || port >= 65536) continue; + // The context path the embedded server announced: "/api" → http://localhost:8080/api/. + const path = (s.run && isLive(s.run) ? s.run.httpPath : undefined) ?? serviceDebugger(s)?.httpPath ?? ""; + urls.set(`http://localhost:${port}${path ? `${path}/` : ""}`, s.config.name); } return [ { diff --git a/src/features/run/store.ts b/src/features/run/store.ts index 3328c9f1a7..42e8df847a 100644 --- a/src/features/run/store.ts +++ b/src/features/run/store.ts @@ -77,7 +77,7 @@ import { TerminalOutput } from "./terminalOutput"; import { typeFor } from "./types"; import { agentName } from "./agentConfig"; import { loadRunTemplates } from "./runTemplates"; -import { startedPort } from "@/platform/serverPort"; +import { startedServer } from "@/platform/serverPort"; import { tomcatBrowserUrl } from "./tomcat"; import { gradleBootLaunch, gradleDelegation, gradleTestLaunch } from "./gradleRun"; import { openUrl } from "./navigate"; @@ -112,6 +112,8 @@ export interface RunSession { terminal?: boolean; /** The HTTP port the application's embedded web server reported it started on. */ httpPort?: number; + /** Its servlet context path on that port, when the server reported one. */ + httpPath?: string; /** Pinned tab: once finished, a later run opens a new tab instead of taking its place. */ pinned?: boolean; /** Commit checks own these tabs so their output stays available for review. */ @@ -335,15 +337,7 @@ async function reattachRemoteRuns(root: string, knownConfigs: readonly RunConfig const rt = newRuntime(config); generation = rt.generation; if (attached.info.pty) rt.terminal = new TerminalOutput(); - rt.lineListeners.push((line) => { - const port = startedPort(line); - if ( - port !== null && - runtimes.get(sessionId)?.generation === generation && - getSession(sessionId)?.httpPort !== port - ) - patchSession(sessionId, { httpPort: port }); - }); + rt.lineListeners.push((line) => noteStartedServer(sessionId, generation, line)); runtimes.set(sessionId, rt); const session: RunSession = { id: sessionId, @@ -699,6 +693,15 @@ function getSession(id: string): RunSession | undefined { return useRun.getState().sessions.find((s) => s.id === id); } +/** Keeps the port and context path a console line announced, for Open in Browser. */ +function noteStartedServer(sessionId: string, generation: number, line: string) { + const started = startedServer(line); + if (!started || runtimes.get(sessionId)?.generation !== generation) return; + const session = getSession(sessionId); + if (session?.httpPort === started.port && session.httpPath === started.path) return; + patchSession(sessionId, { httpPort: started.port, httpPath: started.path }); +} + function flush(sessionId: string) { const rt = runtimes.get(sessionId); if (!rt) return; @@ -1075,6 +1078,7 @@ async function startRunIn( stdinClosed: false, stopped: false, httpPort: undefined, + httpPath: undefined, backgroundCheck: undefined, watching: undefined, }; @@ -1121,9 +1125,7 @@ async function startRunIn( void openUrl(tomcatBrowserUrl(config)); } } - const port = startedPort(line); - if (port !== null && runtimes.get(sessionId)?.generation === generation && getSession(sessionId)?.httpPort !== port) - patchSession(sessionId, { httpPort: port }); + noteStartedServer(sessionId, generation, line); }); rt.onExit = options.onExit; rt.beforeStop = options.beforeStop; diff --git a/src/platform/serverPort.ts b/src/platform/serverPort.ts index 8ed67ebabb..1f63cfc664 100644 --- a/src/platform/serverPort.ts +++ b/src/platform/serverPort.ts @@ -1,15 +1,31 @@ /** - * The HTTP port of a running Spring Boot application, from the embedded web - * server's startup line: "Tomcat started on port 8080 (http) with context path '/'", + * The embedded web server of a running Spring Boot application, from its startup + * line: "Tomcat started on port 8080 (http) with context path '/'", * "Netty started on port 8080", "Undertow started on port(s) 8080 (http)", - * "Jetty started on port(s) 8080 (http/1.1)". + * "Jetty started on port(s) 8080 (http/1.1)". Tomcat and Jetty report the servlet + * context path on the same line; Netty and Undertow never do. */ const STARTED = /\b(?:Tomcat|Netty|Undertow|Jetty)\b.*?\bstarted on port(?:\(s\))?:?\s*(\d{1,5})/i; +const CONTEXT = /\bwith context path\s+['"]([^'"]*)['"]/i; -export function startedPort(line: string): number | null { +export interface StartedServer { + port: number; + /** The servlet context path, "" for the root one. */ + path: string; +} + +export function startedServer(line: string): StartedServer | null { if (!line.includes("tarted on port")) return null; const m = STARTED.exec(line); if (!m) return null; const port = Number(m[1]); - return port > 0 && port < 65536 ? port : null; + if (!(port > 0 && port < 65536)) return null; + return { port, path: contextPath(line) }; +} + +/** `with context path '/api'` → `/api`; `'/'` and `''` are the root one. */ +function contextPath(line: string): string { + const path = CONTEXT.exec(line)?.[1]?.trim() ?? ""; + if (!path || path === "/") return ""; + return `${path.startsWith("/") ? "" : "/"}${path.replace(/\/+$/, "")}`; } diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.ts index 51adf565f1..307baf127f 100644 --- a/src/workbench/contributions.ts +++ b/src/workbench/contributions.ts @@ -2334,6 +2334,8 @@ export interface DebugServiceSession { processId: number | null; /** The debuggee's HTTP port announced on its console (not the JDWP attach port), if known. */ httpPort?: number; + /** Its servlet context path on that port, when the console reported one. */ + httpPath?: string; rerun: (() => void) | null; /** Rerun without opening the Debug tool window (the Services panel debugs in place). */ rerunInPlace?: (() => void) | null;