-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathchatPanelProvider.ts
More file actions
258 lines (234 loc) · 7.82 KB
/
chatPanelProvider.ts
File metadata and controls
258 lines (234 loc) · 7.82 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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import { randomBytes } from "node:crypto";
import { type CoderApi } from "../../api/coderApi";
import { type Logger } from "../../logging/logger";
import type * as vscode from "vscode";
/**
* Provides a webview that embeds the Coder agent chat UI.
* Authentication flows through postMessage:
*
* 1. The iframe loads /agents/{id}/embed on the Coder server.
* 2. The embed page detects the user is signed out and sends
* { type: "coder:vscode-ready" } to window.parent.
* 3. Our webview relays this to the extension host.
* 4. The extension host replies with the session token.
* 5. The webview forwards { type: "coder:vscode-auth-bootstrap" }
* with the token back into the iframe.
* 6. The embed page calls API.setSessionToken(token), re-fetches
* the authenticated user, and renders the chat UI.
*/
export class ChatPanelProvider
implements vscode.WebviewViewProvider, vscode.Disposable
{
public static readonly viewType = "coder.chatPanel";
private view?: vscode.WebviewView;
private disposables: vscode.Disposable[] = [];
private chatId: string | undefined;
private authRetryTimer: ReturnType<typeof setTimeout> | undefined;
constructor(
private readonly client: CoderApi,
private readonly logger: Logger,
) {}
/**
* Opens the chat panel for the given chat ID.
* Called after a deep link reload via the persisted
* pendingChatId, or directly for testing.
*/
public openChat(chatId: string): void {
this.chatId = chatId;
this.refresh();
this.view?.show(true);
}
resolveWebviewView(
webviewView: vscode.WebviewView,
_context: vscode.WebviewViewResolveContext,
_token: vscode.CancellationToken,
): void {
this.view = webviewView;
webviewView.webview.options = { enableScripts: true };
this.disposables.push(
webviewView.webview.onDidReceiveMessage((msg: unknown) => {
this.handleMessage(msg);
}),
);
this.renderView();
webviewView.onDidDispose(() => this.dispose());
}
public refresh(): void {
if (!this.view) {
return;
}
this.renderView();
}
private renderView(): void {
if (!this.view) {
throw new Error("renderView called before resolveWebviewView");
}
const webview = this.view.webview;
if (!this.chatId) {
webview.html = this.getNoAgentHtml();
return;
}
const coderUrl = this.client.getHost();
if (!coderUrl) {
webview.html = this.getNoAgentHtml();
return;
}
const embedUrl = `${coderUrl}/agents/${this.chatId}/embed`;
webview.html = this.getIframeHtml(embedUrl, coderUrl);
}
private handleMessage(message: unknown): void {
if (typeof message !== "object" || message === null) {
return;
}
const msg = message as { type?: string };
if (msg.type === "coder:vscode-ready") {
this.sendAuthToken();
}
}
/**
* Attempt to forward the session token to the chat iframe.
* The token may not be available immediately after a reload
* (e.g. deployment setup is still in progress), so we retry
* with exponential backoff before giving up.
*/
private static readonly MAX_AUTH_RETRIES = 5;
private static readonly AUTH_RETRY_BASE_MS = 500;
private sendAuthToken(attempt = 0): void {
clearTimeout(this.authRetryTimer);
const token = this.client.getSessionToken();
if (!token) {
if (attempt < ChatPanelProvider.MAX_AUTH_RETRIES) {
const delay = ChatPanelProvider.AUTH_RETRY_BASE_MS * 2 ** attempt;
this.logger.info(
`Chat: no session token yet, retrying in ${delay}ms ` +
`(attempt ${attempt + 1}/${ChatPanelProvider.MAX_AUTH_RETRIES})`,
);
this.authRetryTimer = setTimeout(
() => this.sendAuthToken(attempt + 1),
delay,
);
return;
}
this.logger.warn(
"Chat iframe requested auth but no session token available " +
"after all retries",
);
this.view?.webview.postMessage({
type: "coder:auth-error",
error: "No session token available. Please sign in and retry.",
});
return;
}
this.logger.info("Chat: forwarding token to iframe");
this.view?.webview.postMessage({
type: "coder:auth-bootstrap-token",
token,
});
}
private getIframeHtml(embedUrl: string, allowedOrigin: string): string {
const nonce = randomBytes(16).toString("base64");
return /* html */ `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy"
content="default-src 'none';
frame-src ${allowedOrigin};
script-src 'nonce-${nonce}';
style-src 'unsafe-inline';">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Coder Chat</title>
<style>
html, body {
margin: 0; padding: 0;
width: 100%; height: 100%;
overflow: hidden;
background: var(--vscode-editor-background, #1e1e1e);
}
iframe { border: none; width: 100%; height: 100%; }
#status {
color: var(--vscode-foreground, #ccc);
font-family: var(--vscode-font-family, sans-serif);
font-size: 13px; padding: 16px; text-align: center;
}
#retry-btn {
margin-top: 12px; padding: 6px 16px;
background: var(--vscode-button-background, #0e639c);
color: var(--vscode-button-foreground, #fff);
border: none; border-radius: 2px; cursor: pointer;
font-family: var(--vscode-font-family, sans-serif);
font-size: 13px;
}
#retry-btn:hover {
background: var(--vscode-button-hoverBackground, #1177bb);
}
</style>
</head>
<body>
<div id="status">Loading chat…</div>
<iframe id="chat-frame" src="${embedUrl}" allow="clipboard-write"
style="display:none;"></iframe>
<script nonce="${nonce}">
(function () {
const vscode = acquireVsCodeApi();
const iframe = document.getElementById('chat-frame');
const status = document.getElementById('status');
iframe.addEventListener('load', () => {
iframe.style.display = 'block';
status.style.display = 'none';
});
window.addEventListener('message', (event) => {
const data = event.data;
if (!data || typeof data !== 'object') return;
if (event.source === iframe.contentWindow) {
if (data.type === 'coder:vscode-ready') {
status.textContent = 'Authenticating…';
vscode.postMessage({ type: 'coder:vscode-ready' });
}
return;
}
if (data.type === 'coder:auth-bootstrap-token') {
status.textContent = 'Signing in…';
iframe.contentWindow.postMessage({
type: 'coder:vscode-auth-bootstrap',
payload: { token: data.token },
}, '${allowedOrigin}');
}
if (data.type === 'coder:auth-error') {
status.textContent = '';
status.appendChild(document.createTextNode(data.error || 'Authentication failed.'));
const btn = document.createElement('button');
btn.id = 'retry-btn';
btn.textContent = 'Retry';
btn.addEventListener('click', () => {
status.textContent = 'Authenticating…';
vscode.postMessage({ type: 'coder:vscode-ready' });
});
status.appendChild(document.createElement('br'));
status.appendChild(btn);
status.style.display = 'block';
iframe.style.display = 'none';
}
});
})();
</script>
</body>
</html>`;
}
private getNoAgentHtml(): string {
return /* html */ `<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8">
<style>body{display:flex;align-items:center;justify-content:center;
height:100vh;margin:0;padding:16px;box-sizing:border-box;
font-family:var(--vscode-font-family);color:var(--vscode-foreground);
text-align:center;}</style></head>
<body><p>No active chat session. Open a chat from the Agents tab on your Coder deployment.</p></body></html>`;
}
dispose(): void {
clearTimeout(this.authRetryTimer);
for (const d of this.disposables) {
d.dispose();
}
this.disposables = [];
}
}