Skip to content

Commit 8d961c5

Browse files
authored
Merge pull request #583 from github/rentziass/debugger-connect-command
Add 'Connect to Actions Job Debugger' command
2 parents 53f7bbe + c7d9be3 commit 8d961c5

File tree

10 files changed

+864
-2
lines changed

10 files changed

+864
-2
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
# GitHub Actions for VS Code
22

33
> **🐛 Actions Job Debugger (Preview):** To try the latest debugger build, download the `.vsix` artifact from the most recent [Build Debugger Extension](https://github.com/github/vscode-github-actions/actions/workflows/debugger-build.yml) workflow run. On the workflow run page, scroll to **Artifacts** and download **vscode-github-actions-debugger**. Then install it in VS Code by running `code --install-extension <path-to-downloaded.vsix>` or via the Extensions view → `` menu → **Install from VSIX…**.
4+
>
5+
> Once installed, open the Command Palette (`Ctrl+Shift+P` / `Cmd+Shift+P`) and run **GitHub Actions: Connect to Actions Job Debugger…**. Paste the `wss://` tunnel URL from a debug-mode job and the extension will open a full debug session using your current GitHub credentials.
46
57
The GitHub Actions extension lets you manage your workflows, view the workflow run history, and helps with authoring workflows.
68

package-lock.json

Lines changed: 49 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525
"activationEvents": [
2626
"onView:workflows",
2727
"onView:settings",
28+
"onDebugResolve:github-actions-job",
29+
"onCommand:github-actions.debugger.connect",
2830
"workspaceContains:**/.github/workflows/**",
2931
"workspaceContains:**/action.yml",
3032
"workspaceContains:**/action.yaml"
@@ -97,7 +99,19 @@
9799
}
98100
}
99101
},
102+
"debuggers": [
103+
{
104+
"type": "github-actions-job",
105+
"label": "GitHub Actions Job Debugger",
106+
"languages": []
107+
}
108+
],
100109
"commands": [
110+
{
111+
"command": "github-actions.debugger.connect",
112+
"category": "GitHub Actions",
113+
"title": "Debug Running Job…"
114+
},
101115
{
102116
"command": "github-actions.explorer.refresh",
103117
"category": "GitHub Actions",
@@ -544,6 +558,7 @@
544558
"@types/libsodium-wrappers": "^0.7.10",
545559
"@types/uuid": "^3.4.6",
546560
"@types/vscode": "^1.72.0",
561+
"@types/ws": "^8.18.1",
547562
"@typescript-eslint/eslint-plugin": "^5.40.0",
548563
"@typescript-eslint/parser": "^5.40.0",
549564
"@vscode/test-web": "^0.0.69",
@@ -579,7 +594,8 @@
579594
"tunnel": "0.0.6",
580595
"util": "^0.12.1",
581596
"uuid": "^3.3.3",
582-
"vscode-languageclient": "^8.0.2"
597+
"vscode-languageclient": "^8.0.2",
598+
"ws": "^8.20.0"
583599
},
584600
"overrides": {
585601
"browserify-sign": {

src/debugger/debugger.ts

Lines changed: 206 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,206 @@
1+
import * as crypto from "crypto";
2+
import * as vscode from "vscode";
3+
import {getClient} from "../api/api";
4+
import {getSession, newSession} from "../auth/auth";
5+
import {getGitHubApiUri} from "../configuration/configuration";
6+
import {log, logDebug, logError} from "../log";
7+
import {parseJobUrl} from "./jobUrl";
8+
import {validateTunnelUrl} from "./tunnelUrl";
9+
import {WebSocketDapAdapter} from "./webSocketDapAdapter";
10+
11+
export const DEBUG_TYPE = "github-actions-job";
12+
13+
/**
14+
* Extension-private token store keyed by one-time nonce. Tokens are never
15+
* placed in DebugConfiguration (readable by other extensions).
16+
*/
17+
const pendingTokens = new Map<string, string>();
18+
19+
export function registerDebugger(context: vscode.ExtensionContext): void {
20+
context.subscriptions.push(
21+
vscode.debug.registerDebugAdapterDescriptorFactory(DEBUG_TYPE, new ActionsDebugAdapterFactory())
22+
);
23+
24+
context.subscriptions.push(
25+
vscode.debug.registerDebugAdapterTrackerFactory(DEBUG_TYPE, new ActionsDebugTrackerFactory())
26+
);
27+
28+
context.subscriptions.push(
29+
vscode.commands.registerCommand("github-actions.debugger.connect", () => connectToDebugger())
30+
);
31+
}
32+
33+
async function connectToDebugger(): Promise<void> {
34+
const rawUrl = await vscode.window.showInputBox({
35+
title: "Connect to Actions Job Debugger",
36+
prompt: "Paste the URL of the Actions job to debug",
37+
placeHolder: "https://github.com/owner/repo/actions/runs/123/job/456",
38+
ignoreFocusOut: true,
39+
validateInput: input => {
40+
if (!input) {
41+
return "A job URL is required";
42+
}
43+
const result = parseJobUrl(input, getGitHubApiUri());
44+
return result.valid ? null : result.reason;
45+
}
46+
});
47+
48+
if (!rawUrl) {
49+
return;
50+
}
51+
52+
const parsed = parseJobUrl(rawUrl, getGitHubApiUri());
53+
if (!parsed.valid) {
54+
void vscode.window.showErrorMessage(`Invalid job URL: ${parsed.reason}`);
55+
return;
56+
}
57+
58+
// Try silently first; fall back to prompting for sign-in if needed.
59+
let session = await getSession();
60+
if (!session) {
61+
try {
62+
session = await newSession("Sign in to GitHub to connect to the Actions job debugger.");
63+
} catch {
64+
void vscode.window.showErrorMessage(
65+
"GitHub authentication is required to connect to the Actions job debugger. Please sign in and try again."
66+
);
67+
return;
68+
}
69+
}
70+
71+
const token = session.accessToken;
72+
let debuggerUrl: string;
73+
try {
74+
debuggerUrl = await vscode.window.withProgress(
75+
{location: vscode.ProgressLocation.Notification, title: "Connecting to Actions job debugger…"},
76+
async () => {
77+
const octokit = getClient(token);
78+
const response = await octokit.request("GET /repos/{owner}/{repo}/actions/jobs/{job_id}/debugger", {
79+
owner: parsed.owner,
80+
repo: parsed.repo,
81+
job_id: parsed.jobId
82+
});
83+
return (response.data as {debugger_url: string}).debugger_url;
84+
}
85+
);
86+
} catch (e) {
87+
const status = (e as {status?: number}).status;
88+
if (status === 404) {
89+
void vscode.window.showErrorMessage(
90+
"Debugger is not available for this job. Make sure the job is running with debugging enabled."
91+
);
92+
} else if (status === 403) {
93+
void vscode.window.showErrorMessage(
94+
"Permission denied. You may need to re-authenticate or check your access to this repository."
95+
);
96+
} else {
97+
const msg = (e as Error).message || "Unknown error";
98+
void vscode.window.showErrorMessage(`Failed to fetch debugger URL: ${msg}`);
99+
}
100+
return;
101+
}
102+
103+
const validation = validateTunnelUrl(debuggerUrl);
104+
if (!validation.valid) {
105+
void vscode.window.showErrorMessage(`Invalid debugger URL returned by API: ${validation.reason}`);
106+
return;
107+
}
108+
109+
// Store token in extension-private memory (not in the config) to avoid
110+
// exposing it to other extensions.
111+
const nonce = crypto.randomBytes(16).toString("hex");
112+
pendingTokens.set(nonce, token);
113+
114+
const config: vscode.DebugConfiguration = {
115+
type: DEBUG_TYPE,
116+
name: "Actions Job Debugger",
117+
request: "attach",
118+
tunnelUrl: validation.url,
119+
__tokenNonce: nonce
120+
};
121+
122+
log(`Starting debug session for ${validation.url}`);
123+
124+
try {
125+
const started = await vscode.debug.startDebugging(undefined, config);
126+
if (!started) {
127+
void vscode.window.showErrorMessage(
128+
"Failed to start the debug session. Check the GitHub Actions output for details."
129+
);
130+
}
131+
} finally {
132+
// Clean up if the factory hasn't consumed the token yet
133+
pendingTokens.delete(nonce);
134+
}
135+
}
136+
137+
class ActionsDebugAdapterFactory implements vscode.DebugAdapterDescriptorFactory {
138+
async createDebugAdapterDescriptor(session: vscode.DebugSession): Promise<vscode.DebugAdapterDescriptor> {
139+
const tunnelUrl = session.configuration.tunnelUrl as string | undefined;
140+
const nonce = session.configuration.__tokenNonce as string | undefined;
141+
const token = nonce ? pendingTokens.get(nonce) : undefined;
142+
143+
// Consume immediately so it cannot be replayed.
144+
if (nonce) {
145+
pendingTokens.delete(nonce);
146+
}
147+
148+
if (!tunnelUrl || !token) {
149+
throw new Error(
150+
"Missing tunnel URL or authentication token. Use the 'Connect to Actions Job Debugger' command to start a session."
151+
);
152+
}
153+
154+
const revalidation = validateTunnelUrl(tunnelUrl);
155+
if (!revalidation.valid) {
156+
throw new Error(`Invalid debugger tunnel URL: ${revalidation.reason}`);
157+
}
158+
159+
const adapter = new WebSocketDapAdapter(tunnelUrl, token);
160+
161+
try {
162+
await adapter.connect();
163+
} catch (e) {
164+
adapter.dispose();
165+
const msg = (e as Error).message;
166+
logError(e as Error, "Failed to connect debugger adapter");
167+
throw new Error(`Could not connect to the debugger tunnel: ${msg}`);
168+
}
169+
170+
return new vscode.DebugAdapterInlineImplementation(adapter);
171+
}
172+
}
173+
174+
class ActionsDebugTrackerFactory implements vscode.DebugAdapterTrackerFactory {
175+
createDebugAdapterTracker(): vscode.DebugAdapterTracker {
176+
return {
177+
onWillReceiveMessage(message: unknown) {
178+
const m = message as Record<string, unknown>;
179+
logDebug(
180+
`[tracker] VS Code → DA: ${String(m.type)}${m.command ? `:${String(m.command)}` : ""} (seq ${String(m.seq)})`
181+
);
182+
},
183+
onDidSendMessage(message: unknown) {
184+
const m = message as Record<string, unknown>;
185+
const body = m.body as Record<string, unknown> | undefined;
186+
let detail = String(m.type);
187+
if (m.command) {
188+
detail += `:${String(m.command)}`;
189+
}
190+
if (m.event) {
191+
detail += `:${String(m.event)}`;
192+
}
193+
if (m.event === "stopped" && body) {
194+
detail += ` threadId=${String(body.threadId)} allThreadsStopped=${String(body.allThreadsStopped)}`;
195+
}
196+
logDebug(`[tracker] DA → VS Code: ${detail} (seq ${String(m.seq)})`);
197+
},
198+
onError(error: Error) {
199+
logError(error, "[tracker] DAP error");
200+
},
201+
onExit(code: number | undefined, signal: string | undefined) {
202+
log(`[tracker] DAP session exited: code=${String(code)} signal=${String(signal)}`);
203+
}
204+
};
205+
}
206+
}

0 commit comments

Comments
 (0)