返回 CodeWhale
chat.ts
根目录 / extensions / vscode / src / chat.ts
1 import * as crypto from "node:crypto";
2 import * as path from "node:path";
3 import * as vscode from "vscode";
4 import {
5 answerUserInput,
6 checkConnection,
7 createThread,
8 getThreadDetail,
9 interruptTurn,
10 listThreadSummaries,
11 openEventStream,
12 resolveApproval,
13 startTurn,
14 steerTurn,
15 ApiConfig,
16 ConnectionInfo,
17 EventStream,
18 ItemRecord,
19 PendingApproval,
20 PendingUserInput,
21 ThreadDetail,
22 ThreadSummary,
23 type RuntimeEvent,
24 } from "./api";
25 import { SseParser } from "./sse";
26 import {
27 assemblePrompt,
28 collectActiveFileContext,
29 collectDiagnosticsContext,
30 collectSelectionContext,
31 type ContextChip,
32 } from "./context";
33 import {
34 isInsideRoot,
35 isRealPathInsideRoot,
36 projectItem,
37 statusForEvent,
38 type ItemView,
39 } from "./transcript";
40
41 /**
42 * Sidebar chat view: one active Codewhale thread at a time, streaming over
43 * the runtime's replayable SSE contract, with inline approvals, clarification
44 * questions, steer, and interrupt. State lives here; the webview only
45 * renders what it is told and posts intent back.
46 */
47
48 interface SyncMessage {
49 type: "sync";
50 connection?: ConnectionInfo;
51 threads: ThreadSummary[];
52 activeThreadId?: string;
53 model?: string;
54 streaming: boolean;
55 /** Interrupt asked for, turn not ended yet: keep Stop/Steer on screen. */
56 interrupting: boolean;
57 chips: ContextChip[];
58 approvals: PendingApproval[];
59 inputs: PendingUserInput[];
60 items: ItemView[];
61 }
62
63 type OutboundMessage =
64 | SyncMessage
65 | { type: "delta"; itemId: string; text: string }
66 | { type: "focusComposer" }
67 /** Tells the composer whether the send was accepted; it only clears on `ok`. */
68 | { type: "composerResult"; ok: boolean };
69
70 export class ChatView implements vscode.WebviewViewProvider {
71 public static readonly viewType = "codewhale.chat";
72 /** The secondary-sidebar twin. The same instance serves both ids. */
73 public static readonly secondaryViewType = "codewhale.chatSecondary";
74
75 /**
76 * Which of the two view ids actually resolved. Only one is ever visible —
77 * the manifest gates them on `codewhale.noSecondarySidebar` — so `reveal()`
78 * must focus the one this host chose, not a hardcoded id.
79 */
80 private resolvedViewType: string = ChatView.viewType;
81
82 private view?: vscode.WebviewView;
83 private webviewReady = false;
84 private queued: OutboundMessage[] = [];
85
86 private connection?: ConnectionInfo;
87 private threads: ThreadSummary[] = [];
88 private activeThreadId?: string;
89 private activeDetail?: ThreadDetail;
90 private items = new Map<string, ItemView>();
91 private itemOrder: string[] = [];
92 private stream?: EventStream;
93 private lastSeq = 0;
94 private streamingTurnId?: string;
95 private interruptRequested = false;
96 /**
97 * The in-flight send. Its `operationKey` is reused when the same prompt is
98 * retried after a timeout so the runtime dedupes instead of starting a
99 * second turn.
100 */
101 private pendingSend?: { threadId: string; prompt: string; operationKey: string };
102 private reconnectAttempt = 0;
103 private reconnectTimer?: ReturnType<typeof setTimeout>;
104 private chips: ContextChip[] = [];
105
106 constructor(
107 private readonly extensionContext: vscode.ExtensionContext,
108 private readonly configProvider: () => Promise<ApiConfig>,
109 private readonly output: vscode.OutputChannel,
110 ) {}
111
112 resolveWebviewView(view: vscode.WebviewView): void {
113 this.view = view;
114 // Remember which id resolved so reveal() focuses the container this host
115 // actually shows. viewType is readonly on WebviewView and is one of the
116 // two ids registered in extension.ts.
117 this.resolvedViewType = view.viewType || ChatView.viewType;
118 view.webview.options = { enableScripts: true };
119 view.onDidDispose(() => {
120 this.closeStream();
121 this.view = undefined;
122 this.webviewReady = false;
123 });
124 view.webview.onDidReceiveMessage((message: { command?: string; [key: string]: unknown }) => {
125 void this.handleWebviewMessage(message);
126 });
127 view.webview.html = this.renderHtml(view);
128 }
129
130 /** Show the chat sidebar and put focus in the composer. */
131 async reveal(): Promise<void> {
132 await vscode.commands.executeCommand(`${this.resolvedViewType}.focus`);
133 }
134
135 /** Connection updates pushed from the extension host. */
136 setConnection(connection: ConnectionInfo): void {
137 this.connection = connection;
138 this.postSync();
139 }
140
141 async refreshThreads(): Promise<void> {
142 try {
143 this.threads = await listThreadSummaries(await this.configProvider());
144 this.postSync();
145 } catch (error) {
146 this.logError("Thread summaries unavailable", error);
147 }
148 }
149
150 /** "Ask Codewhale" entry: attach the current selection and focus the composer. */
151 async askWithSelection(): Promise<void> {
152 const chip = collectSelectionContext() ?? collectActiveFileContext();
153 if (chip && !this.chips.some((existing) => existing.label === chip.label)) {
154 this.chips.push(chip);
155 }
156 await this.reveal();
157 this.post({ type: "focusComposer" });
158 }
159
160 addChip(kind: ContextChip["kind"]): void {
161 const chip =
162 kind === "selection"
163 ? collectSelectionContext()
164 : kind === "file"
165 ? collectActiveFileContext()
166 : collectDiagnosticsContext();
167 if (!chip) {
168 void vscode.window.showInformationMessage("Nothing to attach for that context kind.");
169 return;
170 }
171 this.chips = this.chips.filter((existing) => existing.label !== chip.label);
172 this.chips.push(chip);
173 this.postSync();
174 }
175
176 removeChip(id: string): void {
177 this.chips = this.chips.filter((chip) => chip.id !== id);
178 this.postSync();
179 }
180
181 async newThread(): Promise<void> {
182 try {
183 const workspace = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
184 const thread = await createThread(await this.configProvider(), workspace ? { workspace } : {});
185 this.output.appendLine(`Created thread ${thread.id}`);
186 await this.selectThread(thread.id);
187 await this.refreshThreads();
188 } catch (error) {
189 this.logError("Create thread failed", error);
190 void vscode.window.showErrorMessage(errorMessage(error));
191 }
192 }
193
194 async selectThread(threadId: string): Promise<void> {
195 this.closeStream();
196 this.streamingTurnId = undefined;
197 this.interruptRequested = false;
198 this.items.clear();
199 this.itemOrder = [];
200 this.activeThreadId = threadId;
201 this.postSync();
202 try {
203 const detail = await getThreadDetail(await this.configProvider(), threadId);
204 if (this.activeThreadId !== threadId) {
205 return; // user switched away while loading
206 }
207 this.activeDetail = detail;
208 this.lastSeq = detail.latestSeq;
209 for (const item of detail.items) {
210 this.ingestItem(item);
211 }
212 this.openStream(threadId, detail.latestSeq).catch((error) => this.logError("Stream failed", error));
213 this.postSync();
214 this.scheduleThreadListRefresh();
215 } catch (error) {
216 this.logError("Load thread failed", error);
217 void vscode.window.showErrorMessage(errorMessage(error));
218 }
219 }
220
221 // ---- webview -> extension ----
222
223 private async handleWebviewMessage(message: { command?: string; [key: string]: unknown }): Promise<void> {
224 switch (message.command) {
225 case "ready":
226 this.webviewReady = true;
227 for (const queued of this.queued.splice(0)) {
228 void this.view?.webview.postMessage(queued);
229 }
230 this.postSync();
231 break;
232 case "check":
233 await vscode.commands.executeCommand("codewhale.checkRuntime");
234 break;
235 case "start":
236 await vscode.commands.executeCommand("codewhale.startRuntime");
237 break;
238 case "terminal":
239 await vscode.commands.executeCommand("codewhale.openTerminal");
240 break;
241 case "setToken":
242 await vscode.commands.executeCommand("codewhale.setRuntimeToken");
243 break;
244 case "newThread":
245 await this.newThread();
246 break;
247 case "selectThread":
248 await this.selectThread(String(message.id ?? ""));
249 break;
250 case "refreshThreads":
251 await this.refreshThreads();
252 break;
253 case "sendPrompt":
254 await this.sendPrompt(String(message.text ?? ""));
255 break;
256 case "steer":
257 await this.steer(String(message.text ?? ""));
258 break;
259 case "interrupt":
260 await this.interrupt();
261 break;
262 case "decideApproval":
263 await this.decideApproval(
264 String(message.id ?? ""),
265 message.decision === "allow" ? "allow" : "deny",
266 message.remember === true,
267 );
268 break;
269 case "answerInput":
270 await this.answerInput(message);
271 break;
272 case "addChip":
273 this.addChip(message.kind === "file" ? "file" : message.kind === "diagnostics" ? "diagnostics" : "selection");
274 break;
275 case "removeChip":
276 this.removeChip(String(message.id ?? ""));
277 break;
278 case "copyCode":
279 await vscode.env.clipboard.writeText(String(message.code ?? ""));
280 break;
281 case "insertCode":
282 await this.insertAtCursor(String(message.code ?? ""));
283 break;
284 case "openFile":
285 await this.openFileAtPath(String(message.path ?? ""));
286 break;
287 case "openLink": {
288 const url = String(message.url ?? "");
289 if (/^https?:\/\//.test(url)) {
290 void vscode.env.openExternal(vscode.Uri.parse(url));
291 }
292 break;
293 }
294 }
295 }
296
297 private async sendPrompt(text: string): Promise<void> {
298 const prompt = text.trim();
299 if (!prompt) {
300 this.post({ type: "composerResult", ok: false });
301 return;
302 }
303 if (!this.activeThreadId) {
304 await this.newThread();
305 if (!this.activeThreadId) {
306 this.post({ type: "composerResult", ok: false });
307 return;
308 }
309 }
310 const threadId = this.activeThreadId;
311 const assembled = assemblePrompt(prompt, this.chips);
312 // A resend of the same pending prompt must carry the same operation key,
313 // or a timeout-then-retry lands as two turns.
314 const operationKey =
315 this.pendingSend && this.pendingSend.threadId === threadId && this.pendingSend.prompt === assembled
316 ? this.pendingSend.operationKey
317 : crypto.randomUUID();
318 this.pendingSend = { threadId, prompt: assembled, operationKey };
319 try {
320 const result = await startTurn(await this.configProvider(), threadId, {
321 prompt: assembled,
322 operationKey,
323 });
324 // Accepted: only now is it safe to drop the composer text and chips.
325 this.pendingSend = undefined;
326 this.chips = [];
327 this.streamingTurnId = result.turn.id;
328 this.interruptRequested = false;
329 this.addLocalUserMessage(prompt);
330 this.post({ type: "composerResult", ok: true });
331 void this.openStream(threadId, this.lastSeq);
332 this.postSync();
333 } catch (error) {
334 // Keep `pendingSend` so the retry reuses the key, and give the text back.
335 this.post({ type: "composerResult", ok: false });
336 this.handleError("Send failed", error);
337 }
338 }
339
340 private async steer(text: string): Promise<void> {
341 if (!this.activeThreadId || !this.streamingTurnId) {
342 return;
343 }
344 try {
345 await steerTurn(await this.configProvider(), this.activeThreadId, this.streamingTurnId, text.trim());
346 this.addLocalUserMessage(`[steer] ${text.trim()}`);
347 } catch (error) {
348 this.handleError("Steer failed", error);
349 }
350 }
351
352 private async interrupt(): Promise<void> {
353 if (!this.activeThreadId || !this.streamingTurnId) {
354 return;
355 }
356 try {
357 await interruptTurn(await this.configProvider(), this.activeThreadId, this.streamingTurnId);
358 this.output.appendLine(`Interrupt requested for turn ${this.streamingTurnId}`);
359 } catch (error) {
360 this.handleError("Interrupt failed", error);
361 }
362 }
363
364 private async decideApproval(id: string, decision: "allow" | "deny", remember: boolean): Promise<void> {
365 try {
366 await resolveApproval(await this.configProvider(), id, decision, remember);
367 } catch (error) {
368 this.handleError("Approval failed", error);
369 }
370 }
371
372 private async answerInput(message: { [key: string]: unknown }): Promise<void> {
373 if (!this.activeThreadId) {
374 return;
375 }
376 const raw = Array.isArray(message.answers) ? message.answers : [];
377 const answers = raw.flatMap((entry) => {
378 if (!entry || typeof entry !== "object") {
379 return [];
380 }
381 const record = entry as Record<string, unknown>;
382 const id = typeof record.id === "string" ? record.id : undefined;
383 const label = typeof record.label === "string" ? record.label : undefined;
384 if (!id || !label) {
385 return [];
386 }
387 return [{ id, label, value: typeof record.value === "string" ? record.value : label }];
388 });
389 if (answers.length === 0) {
390 return;
391 }
392 try {
393 await answerUserInput(await this.configProvider(), this.activeThreadId, String(message.inputId ?? ""), answers);
394 } catch (error) {
395 this.handleError("Answer failed", error);
396 }
397 }
398
399 private async insertAtCursor(code: string): Promise<void> {
400 const editor = vscode.window.activeTextEditor;
401 if (!editor) {
402 void vscode.window.showInformationMessage("Open a file to insert code.");
403 return;
404 }
405 await editor.edit((builder) => builder.replace(editor.selection, code));
406 void vscode.window.showTextDocument(editor.document);
407 }
408
409 /**
410 * Open a path that came from an item's tool metadata. That value is
411 * model-influenced, so it is treated as untrusted: workspace-relative
412 * resolution is preferred, `..` escapes are refused outright, and anything
413 * outside the workspace needs an explicit confirmation from the user.
414 */
415 private async openFileAtPath(raw: string): Promise<void> {
416 const candidate = raw.trim();
417 if (!candidate || /[\u0000-\u001f\u007f]/.test(candidate)) {
418 return;
419 }
420 const folders = vscode.workspace.workspaceFolders ?? [];
421 const targets: vscode.Uri[] = [];
422
423 if (path.isAbsolute(candidate)) {
424 const resolved = path.resolve(candidate);
425 const inWorkspace = await insideAnyFolder(folders, resolved);
426 if (!inWorkspace) {
427 const choice = await vscode.window.showWarningMessage(
428 `Open a file outside this workspace?\n\n${resolved}`,
429 { modal: true },
430 "Open File",
431 );
432 if (choice !== "Open File") {
433 return;
434 }
435 }
436 targets.push(vscode.Uri.file(resolved));
437 } else {
438 for (const folder of folders) {
439 // joinPath keeps the folder's scheme (remote/virtual workspaces); the
440 // containment check runs on the resolved filesystem path, with links
441 // followed, so a link inside the workspace cannot lead out of it.
442 if (await isInsideFolder(folder, candidate)) {
443 targets.push(vscode.Uri.joinPath(folder.uri, candidate));
444 }
445 }
446 if (targets.length === 0) {
447 void vscode.window.showWarningMessage(`Refused to open a path outside the workspace: ${candidate}`);
448 return;
449 }
450 }
451
452 for (const uri of targets) {
453 try {
454 await vscode.workspace.fs.stat(uri);
455 await vscode.window.showTextDocument(uri, { preview: true });
456 return;
457 } catch {
458 // try the next candidate
459 }
460 }
461 void vscode.window.showInformationMessage(`File not found: ${candidate}`);
462 }
463
464 // ---- SSE event ingestion ----
465
466 private async openStream(threadId: string, sinceSeq: number): Promise<void> {
467 this.closeStream();
468 this.reconnectAttempt = 0;
469 const config = await this.configProvider();
470 if (this.activeThreadId !== threadId) {
471 return;
472 }
473 const stream = openEventStream(config, threadId, sinceSeq, new SseParser());
474 stream.onEvent = (event) => this.handleStreamEvent(event);
475 stream.onError = (error) => this.handleStreamError(threadId, error);
476 this.stream = stream;
477 }
478
479 private closeStream(): void {
480 if (this.reconnectTimer) {
481 clearTimeout(this.reconnectTimer);
482 this.reconnectTimer = undefined;
483 }
484 this.stream?.close();
485 this.stream = undefined;
486 }
487
488 private handleStreamEvent(event: RuntimeEvent): void {
489 if (event.seq <= this.lastSeq) {
490 return; // duplicate or stale replay
491 }
492 this.lastSeq = event.seq;
493 this.reconnectAttempt = 0;
494
495 switch (event.event) {
496 case "item.started":
497 case "item.completed":
498 case "item.failed":
499 case "item.interrupted":
500 case "item.canceled":
501 case "tool.execution_started": {
502 const payloadItem = readPayloadItem(event.payload);
503 const itemId = event.itemId ?? payloadItem?.id;
504 if (!itemId) {
505 return;
506 }
507 const existing = this.items.get(itemId);
508 const merged: ItemRecord = {
509 id: itemId,
510 turnId: event.turnId ?? existing?.turnId,
511 kind: payloadItem?.kind ?? existing?.kind ?? "status",
512 status: payloadItem?.status ?? statusForEvent(event.event),
513 summary: payloadItem?.summary ?? existing?.summary ?? "",
514 detail: payloadItem?.detail ?? existing?.detail,
515 metadata: payloadItem?.metadata ?? existing?.metadata,
516 };
517 this.ingestItem(merged, event.event);
518 this.postSync();
519 break;
520 }
521 case "item.delta": {
522 const delta = readPayloadDelta(event.payload);
523 if (!delta || !event.itemId) {
524 return;
525 }
526 const view = this.items.get(event.itemId);
527 if (view) {
528 view.streamText = (view.streamText ?? "") + delta;
529 view.rev += 1;
530 } else {
531 this.ingestItem({
532 id: event.itemId,
533 turnId: event.turnId,
534 kind: readPayloadKind(event.payload) ?? "agent_message",
535 summary: delta,
536 });
537 }
538 this.post({ type: "delta", itemId: event.itemId, text: delta });
539 break;
540 }
541 case "approval.required": {
542 const approval = readPayloadApproval(event.payload);
543 if (approval && this.activeDetail) {
544 this.activeDetail.pendingApprovals = [
545 ...this.activeDetail.pendingApprovals.filter((entry) => entry.id !== approval.id),
546 approval,
547 ];
548 this.postSync();
549 }
550 break;
551 }
552 case "approval.decided":
553 case "approval.timeout": {
554 const id = readPayloadId(event.payload) ?? event.itemId;
555 if (id && this.activeDetail) {
556 this.activeDetail.pendingApprovals = this.activeDetail.pendingApprovals.filter(
557 (entry) => entry.id !== id,
558 );
559 this.postSync();
560 }
561 break;
562 }
563 case "user_input.required": {
564 const input = readPayloadUserInput(event.payload);
565 if (input && this.activeDetail) {
566 this.activeDetail.pendingUserInputs = [
567 ...this.activeDetail.pendingUserInputs.filter((entry) => entry.id !== input.id),
568 input,
569 ];
570 this.postSync();
571 }
572 break;
573 }
574 case "user_input.answered":
575 case "user_input.canceled": {
576 const id = readPayloadId(event.payload);
577 if (id && this.activeDetail) {
578 this.activeDetail.pendingUserInputs = this.activeDetail.pendingUserInputs.filter(
579 (entry) => entry.id !== id,
580 );
581 this.postSync();
582 }
583 break;
584 }
585 case "turn.interrupt_requested": {
586 // The turn is still running until it reports an end state; keep the
587 // Stop/Steer controls on screen instead of hiding them here.
588 if (event.turnId && event.turnId === this.streamingTurnId) {
589 this.interruptRequested = true;
590 this.postSync();
591 }
592 break;
593 }
594 case "turn.completed":
595 case "turn.failed":
596 case "turn.interrupted":
597 case "turn.ended": {
598 if (event.turnId && event.turnId === this.streamingTurnId) {
599 this.streamingTurnId = undefined;
600 this.interruptRequested = false;
601 this.postSync();
602 this.scheduleThreadListRefresh();
603 }
604 break;
605 }
606 default:
607 break;
608 }
609 }
610
611 private handleStreamError(threadId: string, error: Error): void {
612 if (this.activeThreadId !== threadId) {
613 return;
614 }
615 if (error instanceof Error && "statusCode" in error && (error as { statusCode?: number }).statusCode === 401) {
616 this.connection = { kind: "auth-required", detail: "Runtime token was rejected." };
617 this.postSync();
618 return;
619 }
620 // The stream is dead; drop it, or the `!this.stream` guard below never
621 // passes and the reconnect silently never happens.
622 this.stream?.close();
623 this.stream = undefined;
624 const attempt = ++this.reconnectAttempt;
625 const delay = Math.min(1000 * attempt, 5000);
626 this.output.appendLine(`Event stream for ${threadId} dropped (${error.message}); retrying in ${delay}ms`);
627 this.reconnectTimer = setTimeout(() => {
628 this.reconnectTimer = undefined;
629 if (this.activeThreadId === threadId && !this.stream) {
630 void this.openStream(threadId, this.lastSeq).catch((error) =>
631 this.logError("Stream reconnect failed", error),
632 );
633 }
634 }, delay);
635 }
636
637 /** Fill the item projection from a thread-detail snapshot or SSE event. */
638 private ingestItem(item: ItemRecord, event?: string): void {
639 const existing = this.items.get(item.id);
640 this.items.set(item.id, projectItem(item, existing, event));
641 if (!existing) {
642 this.itemOrder.push(item.id);
643 }
644 }
645
646 private addLocalUserMessage(text: string): void {
647 const id = `local-${crypto.randomUUID()}`;
648 this.items.set(id, { id, kind: "user_message", summary: text, rev: 1 });
649 this.itemOrder.push(id);
650 this.postSync();
651 }
652
653 private scheduleThreadListRefresh(): void {
654 // Titles/previews settle right after a turn finishes; refresh lazily.
655 setTimeout(() => {
656 void this.refreshThreads();
657 }, 1200);
658 }
659
660 // ---- outbound ----
661
662 private post(message: OutboundMessage): void {
663 if (!this.view) {
664 return;
665 }
666 if (!this.webviewReady) {
667 this.queued.push(message);
668 return;
669 }
670 void this.view.webview.postMessage(message);
671 }
672
673 private postSync(): void {
674 this.post({
675 type: "sync",
676 connection: this.connection,
677 threads: this.threads,
678 activeThreadId: this.activeThreadId,
679 model: this.activeDetail?.thread.model ?? this.threads.find((t) => t.id === this.activeThreadId)?.model,
680 streaming: this.streamingTurnId !== undefined,
681 interrupting: this.interruptRequested,
682 chips: this.chips,
683 approvals: this.activeDetail?.pendingApprovals ?? [],
684 inputs: this.activeDetail?.pendingUserInputs ?? [],
685 items: this.itemOrder.flatMap((id) => {
686 const view = this.items.get(id);
687 return view ? [view] : [];
688 }),
689 });
690 }
691
692 private handleError(where: string, error: unknown): void {
693 this.logError(where, error);
694 if (isAuthError(error)) {
695 this.connection = { kind: "auth-required", detail: "Runtime token was rejected." };
696 this.postSync();
697 }
698 void vscode.window.showErrorMessage(`CodeWhale ${where.toLowerCase()}: ${errorMessage(error)}`);
699 }
700
701 private logError(where: string, error: unknown): void {
702 this.output.appendLine(`${new Date().toISOString()} ${where}: ${errorMessage(error)}`);
703 }
704
705 /** Load the thread list + latest detail for the active thread (used after reconnects). */
706 async resyncAfterConnection(): Promise<void> {
707 await this.refreshThreads();
708 if (this.activeThreadId) {
709 await this.selectThread(this.activeThreadId);
710 }
711 }
712
713 // ---- webview HTML ----
714
715 private renderHtml(view: vscode.WebviewView): string {
716 const nonce = makeNonce();
717 return `<!doctype html>
718 <html lang="en">
719 <head>
720 <meta charset="UTF-8">
721 <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${nonce}';">
722 <meta name="viewport" content="width=device-width, initial-scale=1.0">
723 <style>
724 ${chatStyles()}
725 </style>
726 </head>
727 <body>
728 <header id="conn">
729 <span id="conn-dot" class="dot offline" aria-hidden="true"></span>
730 <span id="conn-label" role="status" aria-live="polite">Checking runtime…</span>
731 <span class="spacer"></span>
732 <button id="btn-new" class="icon" title="New thread" aria-label="New thread">+ New</button>
733 </header>
734 <div id="conn-actions" class="hidden" role="group" aria-label="Runtime connection actions">
735 <button id="btn-start">Start Local Runtime</button>
736 <button id="btn-token">Set Runtime Token</button>
737 <button id="btn-terminal">Open Terminal</button>
738 </div>
739 <details id="threads-box">
740 <summary>Threads <span id="threads-count"></span></summary>
741 <div id="threads" role="group" aria-label="Threads"></div>
742 </details>
743 <main id="transcript" role="log" aria-live="polite" aria-relevant="additions text"
744 aria-label="Conversation transcript" tabindex="0"></main>
745 <div id="attention" role="region" aria-live="assertive" aria-label="Needs your attention"></div>
746 <div id="chips" role="list" aria-label="Attached context"></div>
747 <div id="steer-box" class="hidden" role="group" aria-label="Running turn controls">
748 <label class="sr-only" for="steer-input">Steer the running turn</label>
749 <input id="steer-input" type="text" placeholder="Steer the running turn…"
750 aria-label="Steer the running turn" />
751 <button id="btn-steer">Steer</button>
752 <button id="btn-interrupt" class="danger">Stop</button>
753 </div>
754 <footer id="composer">
755 <div class="attach-row" role="group" aria-label="Attach editor context">
756 <button id="btn-chip-selection" title="Attach current selection" aria-label="Attach current selection">+ Selection</button>
757 <button id="btn-chip-file" title="Attach active file" aria-label="Attach active file">+ File</button>
758 <button id="btn-chip-diagnostics" title="Attach problems" aria-label="Attach problems from the active file">+ Problems</button>
759 <span id="model-label" class="model" role="status" aria-live="polite"></span>
760 </div>
761 <label class="sr-only" for="prompt">Message Codewhale</label>
762 <textarea id="prompt" rows="3" aria-label="Message Codewhale"
763 aria-describedby="prompt-hint"
764 placeholder="Ask Codewhale… (Enter to send, Shift+Enter for newline)"></textarea>
765 <span id="prompt-hint" class="sr-only">Press Enter to send, Shift plus Enter for a new line.</span>
766 </footer>
767 <script nonce="${nonce}">
768 ${chatScript()}
769 </script>
770 </body>
771 </html>`;
772 }
773 }
774
775 /**
776 * Whether `candidate` is inside the workspace folder. Local folders are
777 * checked on their real path (links followed); a folder on a non-file scheme
778 * (virtual workspace) has no local disk to resolve, so it keeps the lexical
779 * check.
780 */
781 async function isInsideFolder(folder: vscode.WorkspaceFolder, candidate: string): Promise<boolean> {
782 return folder.uri.scheme === "file"
783 ? isRealPathInsideRoot(folder.uri.fsPath, candidate)
784 : isInsideRoot(folder.uri.fsPath, candidate);
785 }
786
787 /** Whether `candidate` is inside any of the workspace folders. */
788 async function insideAnyFolder(
789 folders: readonly vscode.WorkspaceFolder[],
790 candidate: string,
791 ): Promise<boolean> {
792 for (const folder of folders) {
793 if (await isInsideFolder(folder, candidate)) {
794 return true;
795 }
796 }
797 return false;
798 }
799
800 function readPayloadItem(payload: unknown): Partial<ItemRecord> | undefined {
801 if (!payload || typeof payload !== "object") {
802 return undefined;
803 }
804 const record = payload as Record<string, unknown>;
805 const source =
806 record.item && typeof record.item === "object" ? (record.item as Record<string, unknown>) : record;
807 const summary = typeof source.summary === "string" ? source.summary : undefined;
808 return {
809 id: typeof source.id === "string" ? source.id : undefined,
810 kind: typeof source.kind === "string" ? source.kind : undefined,
811 status: typeof source.status === "string" ? source.status : undefined,
812 summary,
813 detail: typeof source.detail === "string" ? source.detail : undefined,
814 metadata:
815 source.metadata && typeof source.metadata === "object"
816 ? (source.metadata as Record<string, unknown>)
817 : undefined,
818 };
819 }
820
821 function readPayloadDelta(payload: unknown): string | undefined {
822 if (!payload || typeof payload !== "object") {
823 return undefined;
824 }
825 const delta = (payload as Record<string, unknown>).delta;
826 return typeof delta === "string" ? delta : undefined;
827 }
828
829 function readPayloadKind(payload: unknown): string | undefined {
830 if (!payload || typeof payload !== "object") {
831 return undefined;
832 }
833 const kind = (payload as Record<string, unknown>).kind;
834 return typeof kind === "string" ? kind : undefined;
835 }
836
837 function readPayloadId(payload: unknown): string | undefined {
838 if (!payload || typeof payload !== "object") {
839 return undefined;
840 }
841 const record = payload as Record<string, unknown>;
842 for (const key of ["approval_id", "input_id", "id"]) {
843 const value = record[key];
844 if (typeof value === "string") {
845 return value;
846 }
847 }
848 return undefined;
849 }
850
851 function readPayloadApproval(payload: unknown): PendingApproval | undefined {
852 if (!payload || typeof payload !== "object") {
853 return undefined;
854 }
855 const record = payload as Record<string, unknown>;
856 const id = readPayloadId(record);
857 if (!id) {
858 return undefined;
859 }
860 return {
861 id,
862 turnId: typeof record.turn_id === "string" ? record.turn_id : undefined,
863 toolName: typeof record.tool_name === "string" ? record.tool_name : "tool",
864 description: typeof record.description === "string" ? record.description : "",
865 intentSummary: typeof record.intent_summary === "string" ? record.intent_summary : undefined,
866 };
867 }
868
869 function readPayloadUserInput(payload: unknown): PendingUserInput | undefined {
870 if (!payload || typeof payload !== "object") {
871 return undefined;
872 }
873 const record = payload as Record<string, unknown>;
874 const id = readPayloadId(record);
875 if (!id) {
876 return undefined;
877 }
878 const request =
879 record.request && typeof record.request === "object"
880 ? (record.request as Record<string, unknown>)
881 : record;
882 const questions = Array.isArray(request.questions)
883 ? request.questions.flatMap((raw) => {
884 if (!raw || typeof raw !== "object") {
885 return [];
886 }
887 const question = raw as Record<string, unknown>;
888 const questionId = typeof question.id === "string" ? question.id : undefined;
889 if (!questionId) {
890 return [];
891 }
892 return [
893 {
894 id: questionId,
895 header: typeof question.header === "string" ? question.header : undefined,
896 question: typeof question.question === "string" ? question.question : "",
897 allowFreeText: question.allow_free_text === true,
898 multiSelect: question.multi_select === true,
899 options: Array.isArray(question.options)
900 ? question.options.flatMap((optionRaw) => {
901 if (!optionRaw || typeof optionRaw !== "object") {
902 return [];
903 }
904 const option = optionRaw as Record<string, unknown>;
905 return typeof option.label === "string"
906 ? [
907 {
908 label: option.label,
909 description:
910 typeof option.description === "string" ? option.description : undefined,
911 },
912 ]
913 : [];
914 })
915 : [],
916 },
917 ];
918 })
919 : [];
920 return { id, turnId: typeof record.turn_id === "string" ? record.turn_id : undefined, questions };
921 }
922
923 function isAuthError(error: unknown): boolean {
924 return error instanceof Error && "statusCode" in error && (error as { statusCode?: number }).statusCode === 401;
925 }
926
927 function errorMessage(error: unknown): string {
928 return error instanceof Error ? error.message : String(error);
929 }
930
931 function makeNonce(): string {
932 return crypto.randomBytes(16).toString("hex");
933 }
934
935 function chatStyles(): string {
936 return `
937 body { display: flex; flex-direction: column; height: 100vh; margin: 0; padding: 0;
938 color: var(--vscode-foreground); font-family: var(--vscode-font-family); font-size: var(--vscode-font-size, 13px); }
939 button { font-family: inherit; font-size: 11px; cursor: pointer; color: var(--vscode-button-foreground);
940 background: var(--vscode-button-secondaryBackground); border: none; border-radius: 3px; padding: 3px 8px; }
941 button.primary { background: var(--vscode-button-background); }
942 button.danger { background: var(--vscode-errorForeground); color: var(--vscode-editor-background); }
943 button:hover { filter: brightness(1.1); }
944 button[aria-disabled="true"] { opacity: 0.6; cursor: default; }
945 /* Keyboard focus must be visible everywhere it can land. */
946 :focus-visible { outline: 2px solid var(--vscode-focusBorder, #0078d4); outline-offset: 1px; border-radius: 3px; }
947 button:focus-visible, summary:focus-visible, [tabindex]:focus-visible, .thread:focus-visible, .chip button:focus-visible {
948 outline: 2px solid var(--vscode-focusBorder, #0078d4); outline-offset: 1px; }
949 input[type="text"]:focus-visible, input[type="checkbox"]:focus-visible, textarea:focus-visible {
950 outline: 2px solid var(--vscode-focusBorder, #0078d4); outline-offset: -1px;
951 border-color: var(--vscode-focusBorder, #0078d4); }
952 /* Some hosts still report only :focus for the textarea; keep it obvious. */
953 textarea:focus, input[type="text"]:focus { border-color: var(--vscode-focusBorder, #0078d4); }
954 .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden;
955 clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; border: 0; }
956 input[type="text"], textarea { width: 100%; box-sizing: border-box; color: var(--vscode-input-foreground);
957 background: var(--vscode-input-background); border: 1px solid var(--vscode-input-border, transparent); border-radius: 3px;
958 padding: 6px 8px; font-family: inherit; font-size: inherit; resize: vertical; }
959 header { display: flex; align-items: center; gap: 6px; padding: 8px 10px; }
960 .dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
961 .dot.connected { background: var(--vscode-testing-iconPassed, #2ea043); }
962 .dot.offline { background: var(--vscode-testing-iconFailed, #f14c4c); }
963 .dot.auth-required { background: var(--vscode-editorWarning-foreground, #cca700); }
964 .dot.error { background: var(--vscode-testing-iconFailed, #f14c4c); }
965 .spacer { flex: 1; }
966 .hidden { display: none !important; }
967 #conn-label { color: var(--vscode-descriptionForeground); font-size: 11px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
968 #conn-actions { display: flex; gap: 6px; padding: 0 10px 8px; flex-wrap: wrap; }
969 details { border-top: 1px solid var(--vscode-panel-border, #333); }
970 #threads-box { padding: 0 10px; }
971 #threads-box summary { cursor: pointer; padding: 6px 0; color: var(--vscode-descriptionForeground); font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; }
972 .thread { padding: 5px 6px; border-radius: 4px; cursor: pointer; overflow: hidden; }
973 .thread:hover { background: var(--vscode-list-hoverBackground); }
974 .thread.active { background: var(--vscode-list-activeSelectionBackground); color: var(--vscode-list-activeSelectionForeground); }
975 .thread-title { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
976 .thread-meta { color: var(--vscode-descriptionForeground); font-size: 10px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
977 main { flex: 1; overflow-y: auto; padding: 4px 10px; }
978 .msg { margin: 8px 0; }
979 .msg .who { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em;
980 color: var(--vscode-descriptionForeground); margin-bottom: 2px; }
981 .msg.user .who { color: var(--vscode-textLink-foreground); }
982 .bubble { border-radius: 6px; padding: 6px 9px; line-height: 1.5; overflow-wrap: anywhere; white-space: pre-wrap; }
983 .msg.user .bubble { background: var(--vscode-input-background); border: 1px solid var(--vscode-panel-border, #333); }
984 .msg.agent .bubble { white-space: normal; }
985 .msg.agent .bubble p { margin: 0 0 8px; }
986 .msg.agent .bubble p:last-child { margin-bottom: 0; }
987 .msg.agent .bubble h3, .msg.agent .bubble h4, .msg.agent .bubble h5 { margin: 10px 0 4px; }
988 .msg.agent .bubble ul, .msg.agent .bubble ol { margin: 4px 0; padding-left: 20px; }
989 .msg.agent .bubble hr { border: none; border-top: 1px solid var(--vscode-panel-border, #333); }
990 .msg.agent .bubble a { color: var(--vscode-textLink-foreground); }
991 .streaming::after { content: "▍"; animation: blink 1s steps(2) infinite; color: var(--vscode-descriptionForeground); }
992 @keyframes blink { 50% { opacity: 0; } }
993 .tool { margin: 6px 0; border: 1px solid var(--vscode-panel-border, #333); border-radius: 5px; font-size: 12px; }
994 .tool summary { cursor: pointer; padding: 5px 8px; color: var(--vscode-descriptionForeground); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
995 .tool pre { margin: 0; padding: 6px 8px; overflow-x: auto; font-family: var(--vscode-editor-font-family, monospace); font-size: 11px; white-space: pre-wrap; }
996 .msg.error .bubble { color: var(--vscode-errorForeground); }
997 .msg.status .bubble { color: var(--vscode-descriptionForeground); font-size: 11px; }
998 .codeblock { margin: 8px 0; border: 1px solid var(--vscode-panel-border, #333); border-radius: 5px; overflow: hidden; }
999 .codeblock-bar { display: flex; justify-content: space-between; align-items: center; padding: 2px 4px 2px 8px;
1000 background: var(--vscode-titleBar-activeBackground, #222); }
1001 .codeblock-lang { font-size: 10px; color: var(--vscode-descriptionForeground); text-transform: uppercase; }
1002 .codeblock-actions button { margin-left: 4px; padding: 1px 6px; font-size: 10px; }
1003 .codeblock pre { margin: 0; padding: 8px; overflow-x: auto; font-family: var(--vscode-editor-font-family, monospace); font-size: 11px; }
1004 .card { margin: 8px 0; border: 1px solid var(--vscode-editorWarning-foreground, #cca700); border-radius: 6px; padding: 8px; }
1005 .card .title { font-weight: 700; margin-bottom: 4px; }
1006 .card .desc { color: var(--vscode-descriptionForeground); margin-bottom: 8px; overflow-wrap: anywhere; white-space: pre-wrap; }
1007 .card .row { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; margin-top: 6px; }
1008 .card label { font-size: 11px; color: var(--vscode-descriptionForeground); display: flex; gap: 4px; align-items: center; }
1009 .opt { display: block; width: 100%; text-align: left; margin: 3px 0; padding: 5px 8px; }
1010 .opt .opt-desc { display: block; font-weight: 400; color: var(--vscode-descriptionForeground); font-size: 10px; }
1011 #chips { display: flex; gap: 4px; flex-wrap: wrap; padding: 0 10px 4px; }
1012 .chip { display: inline-flex; gap: 4px; align-items: center; background: var(--vscode-badge-background);
1013 color: var(--vscode-badge-foreground); border-radius: 8px; padding: 1px 8px; font-size: 10px; }
1014 .chip button { background: transparent; color: inherit; padding: 0 2px; font-size: 11px; }
1015 #steer-box { display: flex; gap: 6px; padding: 4px 10px; }
1016 #steer-box input { flex: 1; }
1017 #composer { border-top: 1px solid var(--vscode-panel-border, #333); padding: 6px 10px 10px; }
1018 .attach-row { display: flex; gap: 4px; margin-bottom: 4px; align-items: center; }
1019 .attach-row button { font-size: 10px; padding: 1px 6px; }
1020 .model { margin-left: auto; color: var(--vscode-descriptionForeground); font-size: 10px; }
1021 main:focus-visible { outline: 2px solid var(--vscode-focusBorder, #0078d4); outline-offset: -2px; }
1022 #transcript .empty { color: var(--vscode-descriptionForeground); text-align: center; margin-top: 30px; line-height: 1.6; }
1023 `;
1024 }
1025
1026 /**
1027 * The webview script as a string. Kept here (not in a separate file) so the
1028 * extension stays a no-bundler build; it must never interpolate runtime data.
1029 */
1030 function chatScript(): string {
1031 return `
1032 const vscode = acquireVsCodeApi();
1033 const transcript = document.getElementById("transcript");
1034 const attention = document.getElementById("attention");
1035 const chipsRow = document.getElementById("chips");
1036 const threadsList = document.getElementById("threads");
1037 const itemEls = new Map(); // item id -> element
1038 const codeBlocks = new Map(); // item id -> [raw code]
1039 const streamBufs = new Map(); // item id -> streaming text element
1040 let state = { streaming: false, activeThreadId: undefined };
1041
1042 document.getElementById("btn-new").addEventListener("click", () => vscode.postMessage({ command: "newThread" }));
1043 document.getElementById("btn-start").addEventListener("click", () => vscode.postMessage({ command: "start" }));
1044 document.getElementById("btn-token").addEventListener("click", () => vscode.postMessage({ command: "setToken" }));
1045 document.getElementById("btn-terminal").addEventListener("click", () => vscode.postMessage({ command: "terminal" }));
1046 document.getElementById("btn-chip-selection").addEventListener("click", () => vscode.postMessage({ command: "addChip", kind: "selection" }));
1047 document.getElementById("btn-chip-file").addEventListener("click", () => vscode.postMessage({ command: "addChip", kind: "file" }));
1048 document.getElementById("btn-chip-diagnostics").addEventListener("click", () => vscode.postMessage({ command: "addChip", kind: "diagnostics" }));
1049 document.getElementById("btn-interrupt").addEventListener("click", (e) => {
1050 if (e.currentTarget.getAttribute("aria-disabled") === "true") { return; }
1051 vscode.postMessage({ command: "interrupt" });
1052 });
1053 document.getElementById("btn-steer").addEventListener("click", sendSteer);
1054 document.getElementById("steer-input").addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); sendSteer(); } });
1055
1056 const promptBox = document.getElementById("prompt");
1057 promptBox.addEventListener("keydown", (e) => {
1058 if (e.key === "Enter" && !e.shiftKey) {
1059 e.preventDefault();
1060 sendPrompt();
1061 }
1062 });
1063
1064 let sending = false;
1065 let sentText = "";
1066 function sendPrompt() {
1067 const text = promptBox.value.trim();
1068 if (!text || sending) { return; }
1069 sentText = promptBox.value;
1070 // Do NOT clear here: the turn can still be refused and the text is the
1071 // user's. It is cleared only when the extension confirms acceptance.
1072 sending = true;
1073 promptBox.setAttribute("aria-busy", "true");
1074 vscode.postMessage({ command: "sendPrompt", text });
1075 }
1076
1077 function composerResult(ok) {
1078 sending = false;
1079 promptBox.removeAttribute("aria-busy");
1080 // Only clear what was actually sent: the user may have kept typing.
1081 if (ok && promptBox.value === sentText) { promptBox.value = ""; }
1082 sentText = "";
1083 promptBox.focus();
1084 }
1085 function sendSteer() {
1086 const box = document.getElementById("steer-input");
1087 const text = box.value.trim();
1088 if (!text) { return; }
1089 box.value = "";
1090 vscode.postMessage({ command: "steer", text });
1091 }
1092
1093 window.addEventListener("message", (event) => {
1094 const msg = event.data;
1095 if (msg.type === "sync") { renderSync(msg); }
1096 else if (msg.type === "delta") { appendDelta(msg.itemId, msg.text); }
1097 else if (msg.type === "focusComposer") { promptBox.focus(); }
1098 else if (msg.type === "composerResult") { composerResult(msg.ok === true); }
1099 });
1100 vscode.postMessage({ command: "ready" });
1101
1102 function renderSync(msg) {
1103 state = msg;
1104 renderConnection(msg);
1105 renderThreads(msg);
1106 renderChips(msg.chips || []);
1107 renderAttention(msg);
1108 renderItems(msg.items || []);
1109 const running = !!msg.streaming;
1110 document.getElementById("steer-box").classList.toggle("hidden", !running);
1111 const stop = document.getElementById("btn-interrupt");
1112 stop.classList.toggle("hidden", !running);
1113 stop.textContent = msg.interrupting ? "Stopping…" : "Stop";
1114 stop.setAttribute("aria-label", msg.interrupting ? "Stopping the current turn" : "Stop the current turn");
1115 stop.setAttribute("aria-disabled", msg.interrupting ? "true" : "false");
1116 document.getElementById("model-label").textContent = msg.model ? msg.model : "";
1117 }
1118
1119 function renderConnection(msg) {
1120 const conn = msg.connection;
1121 const dot = document.getElementById("conn-dot");
1122 const label = document.getElementById("conn-label");
1123 const actions = document.getElementById("conn-actions");
1124 if (!conn) { dot.className = "dot offline"; label.textContent = "Checking runtime…"; actions.classList.add("hidden"); return; }
1125 dot.className = "dot " + conn.kind;
1126 label.textContent = conn.detail;
1127 label.title = conn.detail;
1128 const showActions = conn.kind !== "connected";
1129 actions.classList.toggle("hidden", !showActions);
1130 document.getElementById("btn-token").classList.toggle("hidden", conn.kind !== "auth-required");
1131 }
1132
1133 function renderThreads(msg) {
1134 const threads = msg.threads || [];
1135 document.getElementById("threads-count").textContent = "(" + threads.length + ")";
1136 threadsList.textContent = "";
1137 for (const thread of threads) {
1138 const el = document.createElement("div");
1139 el.className = "thread" + (thread.id === msg.activeThreadId ? " active" : "");
1140 el.setAttribute("role", "button");
1141 el.tabIndex = 0;
1142 if (thread.id === msg.activeThreadId) { el.setAttribute("aria-current", "true"); }
1143 const title = document.createElement("div");
1144 title.className = "thread-title";
1145 title.textContent = thread.title || "New Thread";
1146 const meta = document.createElement("div");
1147 meta.className = "thread-meta";
1148 meta.textContent = [thread.model, thread.branch, thread.latestTurnStatus].filter(Boolean).join(" · ");
1149 el.appendChild(title);
1150 el.appendChild(meta);
1151 const open = () => vscode.postMessage({ command: "selectThread", id: thread.id });
1152 el.setAttribute("aria-label", "Thread: " + (thread.title || "New Thread"));
1153 el.addEventListener("click", open);
1154 el.addEventListener("keydown", (e) => {
1155 if (e.key === "Enter" || e.key === " ") { e.preventDefault(); open(); }
1156 });
1157 threadsList.appendChild(el);
1158 }
1159 }
1160
1161 function renderChips(chips) {
1162 chipsRow.textContent = "";
1163 for (const chip of chips) {
1164 const el = document.createElement("span");
1165 el.className = "chip";
1166 el.setAttribute("role", "listitem");
1167 const text = document.createElement("span");
1168 text.textContent = chip.label + (chip.detail ? " (" + chip.detail + ")" : "");
1169 const remove = document.createElement("button");
1170 remove.textContent = "×";
1171 remove.title = "Remove";
1172 remove.setAttribute("aria-label", "Remove context " + chip.label);
1173 remove.addEventListener("click", () => vscode.postMessage({ command: "removeChip", id: chip.id }));
1174 el.appendChild(text);
1175 el.appendChild(remove);
1176 chipsRow.appendChild(el);
1177 }
1178 }
1179
1180 function renderAttention(msg) {
1181 attention.textContent = "";
1182 for (const approval of msg.approvals || []) {
1183 attention.appendChild(approvalCard(approval));
1184 }
1185 for (const input of msg.inputs || []) {
1186 attention.appendChild(userInputCard(msg.activeThreadId, input));
1187 }
1188 }
1189
1190 function approvalCard(approval) {
1191 const card = document.createElement("div");
1192 card.className = "card";
1193 card.setAttribute("role", "group");
1194 card.setAttribute("aria-label", "Approval request for " + approval.toolName);
1195 const title = document.createElement("div");
1196 title.className = "title";
1197 title.textContent = "Approval: " + approval.toolName;
1198 const desc = document.createElement("div");
1199 desc.className = "desc";
1200 desc.textContent = approval.intentSummary ? approval.intentSummary + "\\n" + approval.description : approval.description;
1201 const row = document.createElement("div");
1202 row.className = "row";
1203 const remember = document.createElement("label");
1204 const rememberBox = document.createElement("input");
1205 rememberBox.type = "checkbox";
1206 remember.appendChild(rememberBox);
1207 remember.appendChild(document.createTextNode(" remember"));
1208 const allow = document.createElement("button");
1209 allow.className = "primary";
1210 allow.textContent = "Allow";
1211 allow.setAttribute("aria-label", "Allow " + approval.toolName);
1212 allow.addEventListener("click", () => vscode.postMessage({ command: "decideApproval", id: approval.id, decision: "allow", remember: rememberBox.checked }));
1213 const deny = document.createElement("button");
1214 deny.textContent = "Deny";
1215 deny.setAttribute("aria-label", "Deny " + approval.toolName);
1216 deny.addEventListener("click", () => vscode.postMessage({ command: "decideApproval", id: approval.id, decision: "deny", remember: rememberBox.checked }));
1217 row.appendChild(allow); row.appendChild(deny); row.appendChild(remember);
1218 card.appendChild(title); card.appendChild(desc); card.appendChild(row);
1219 return card;
1220 }
1221
1222 function userInputCard(threadId, input) {
1223 const card = document.createElement("div");
1224 card.className = "card";
1225 card.setAttribute("role", "group");
1226 card.setAttribute("aria-label", "Codewhale needs an answer");
1227 for (const question of input.questions || []) {
1228 const title = document.createElement("div");
1229 title.className = "title";
1230 title.textContent = (question.header ? question.header + ": " : "") + question.question;
1231 card.appendChild(title);
1232 const selected = new Set();
1233 const answer = (label) => vscode.postMessage({
1234 command: "answerInput", inputId: input.id,
1235 answers: [{ id: question.id, label: label, value: label }],
1236 });
1237 for (const option of question.options || []) {
1238 const btn = document.createElement("button");
1239 btn.className = "opt";
1240 btn.textContent = option.label;
1241 if (option.description) {
1242 const desc = document.createElement("span");
1243 desc.className = "opt-desc";
1244 desc.textContent = option.description;
1245 btn.appendChild(desc);
1246 }
1247 if (question.multiSelect) {
1248 btn.setAttribute("role", "checkbox");
1249 btn.setAttribute("aria-checked", "false");
1250 btn.addEventListener("click", () => {
1251 const on = !selected.has(option.label);
1252 if (on) { selected.add(option.label); btn.style.opacity = "0.6"; }
1253 else { selected.delete(option.label); btn.style.opacity = ""; }
1254 btn.setAttribute("aria-checked", on ? "true" : "false");
1255 });
1256 } else {
1257 btn.addEventListener("click", () => answer(option.label));
1258 }
1259 card.appendChild(btn);
1260 }
1261 if (question.multiSelect && (question.options || []).length > 0) {
1262 const confirm = document.createElement("button");
1263 confirm.className = "primary";
1264 confirm.textContent = "Confirm";
1265 confirm.addEventListener("click", () => vscode.postMessage({
1266 command: "answerInput", inputId: input.id,
1267 answers: Array.from(selected).map((label) => ({ id: question.id, label: label, value: label })),
1268 }));
1269 card.appendChild(confirm);
1270 }
1271 if (question.allowFreeText) {
1272 const free = document.createElement("div");
1273 free.className = "row";
1274 const box = document.createElement("input");
1275 box.type = "text";
1276 box.placeholder = "Other…";
1277 box.setAttribute("aria-label", "Other answer for: " + question.question);
1278 const send = document.createElement("button");
1279 send.textContent = "Send";
1280 send.addEventListener("click", () => { if (box.value.trim()) { answer(box.value.trim()); } });
1281 free.appendChild(box); free.appendChild(send);
1282 card.appendChild(free);
1283 }
1284 }
1285 return card;
1286 }
1287
1288 function renderItems(items) {
1289 const seen = new Set();
1290 for (const view of items) {
1291 seen.add(view.id);
1292 const existing = itemEls.get(view.id);
1293 if (!existing) {
1294 itemEls.set(view.id, renderItem(view));
1295 } else if (existing.dataset.rev !== String(view.rev)) {
1296 const fresh = renderItem(view);
1297 existing.replaceWith(fresh);
1298 itemEls.set(view.id, fresh);
1299 }
1300 }
1301 for (const [id, el] of Array.from(itemEls)) {
1302 if (!seen.has(id)) { el.remove(); itemEls.delete(id); streamBufs.delete(id); codeBlocks.delete(id); }
1303 }
1304 orderTranscript(items);
1305 trimEmpty();
1306 scrollToBottom();
1307 }
1308
1309 function orderTranscript(items) {
1310 let cursor = transcript.firstChild;
1311 for (const view of items) {
1312 const el = itemEls.get(view.id);
1313 if (!el) { continue; }
1314 if (cursor === el) { cursor = el.nextSibling; continue; }
1315 transcript.insertBefore(el, cursor);
1316 }
1317 }
1318
1319 function renderItem(view) {
1320 if (view.kind === "user_message") {
1321 return wrap("user", "You", plainBubble(view.summary));
1322 }
1323 if (view.kind === "agent_message") {
1324 if (view.html !== undefined) {
1325 streamBufs.delete(view.id);
1326 const bubble = document.createElement("div");
1327 bubble.className = "bubble";
1328 bubble.innerHTML = view.html;
1329 if (view.codeBlocks) { codeBlocks.set(view.id, view.codeBlocks); wireCodeButtons(bubble, view.id); }
1330 return wrap("agent", "Codewhale", bubble, view);
1331 }
1332 const bubble = document.createElement("div");
1333 bubble.className = "bubble streaming";
1334 bubble.setAttribute("aria-busy", "true");
1335 bubble.textContent = view.streamText || "";
1336 streamBufs.set(view.id, bubble);
1337 return wrap("agent", "Codewhale", bubble, view);
1338 }
1339 if (view.kind === "tool_call" || view.kind === "command_execution" || view.kind === "file_change") {
1340 return wrap(view.kind, "", toolDetails(view), view);
1341 }
1342 if (view.kind === "error") {
1343 return wrap("error", "Error", plainBubble(view.summary + (view.detail ? "\\n" + view.detail : "")), view);
1344 }
1345 return wrap("status", "", plainBubble(view.summary), view);
1346 }
1347
1348 function wrap(kind, who, body, view) {
1349 const msg = document.createElement("div");
1350 msg.className = "msg " + kind;
1351 msg.setAttribute("role", "group");
1352 msg.setAttribute("aria-label", who || kind.replace(/_/g, " "));
1353 if (view) { msg.dataset.rev = String(view.rev); }
1354 if (who) {
1355 const whoEl = document.createElement("div");
1356 whoEl.className = "who";
1357 whoEl.textContent = who;
1358 msg.appendChild(whoEl);
1359 }
1360 msg.appendChild(body);
1361 return msg;
1362 }
1363
1364 function plainBubble(text) {
1365 const bubble = document.createElement("div");
1366 bubble.className = "bubble";
1367 bubble.textContent = text;
1368 return bubble;
1369 }
1370
1371 function toolDetails(view) {
1372 const details = document.createElement("details");
1373 details.className = "tool";
1374 const summary = document.createElement("summary");
1375 summary.textContent = toolLabel(view);
1376 details.appendChild(summary);
1377 const body = document.createElement("pre");
1378 body.textContent = view.detail || view.summary || "";
1379 details.appendChild(body);
1380 // view.filePath is parsed extension-side (metadata.tool_input included)
1381 // and validated again before anything is opened.
1382 if (view.filePath) {
1383 const open = document.createElement("button");
1384 open.textContent = "Open file";
1385 open.setAttribute("aria-label", "Open file " + view.filePath);
1386 open.title = view.filePath;
1387 open.style.margin = "4px 8px";
1388 open.addEventListener("click", () => vscode.postMessage({ command: "openFile", path: view.filePath }));
1389 details.appendChild(open);
1390 }
1391 return details;
1392 }
1393
1394 function toolLabel(view) {
1395 const icon = view.kind === "file_change" ? "✎ " : view.kind === "command_execution" ? "▶ " : "🔧 ";
1396 return icon + (view.summary || view.kind);
1397 }
1398
1399 function wireCodeButtons(scope, itemId) {
1400 for (const btn of scope.querySelectorAll("button.cb-copy, button.cb-insert")) {
1401 const slot = Number(btn.dataset.cb);
1402 btn.addEventListener("click", () => {
1403 const blocks = codeBlocks.get(itemId) || [];
1404 const code = blocks[slot] || "";
1405 vscode.postMessage({ command: btn.classList.contains("cb-copy") ? "copyCode" : "insertCode", code: code });
1406 });
1407 }
1408 for (const link of scope.querySelectorAll("a[href]")) {
1409 link.addEventListener("click", (e) => {
1410 e.preventDefault();
1411 vscode.postMessage({ command: "openLink", url: link.getAttribute("href") });
1412 });
1413 }
1414 }
1415
1416 function appendDelta(itemId, text) {
1417 let bubble = streamBufs.get(itemId);
1418 if (!bubble) { return; }
1419 bubble.textContent += text;
1420 scrollToBottom();
1421 }
1422
1423 function trimEmpty() {
1424 const empty = transcript.querySelector(".empty");
1425 if (empty && transcript.children.length > 1) { empty.remove(); }
1426 }
1427
1428 function scrollToBottom() {
1429 transcript.scrollTop = transcript.scrollHeight;
1430 }
1431
1432 function ensureEmpty() {
1433 if (transcript.children.length === 0) {
1434 const empty = document.createElement("div");
1435 empty.className = "empty";
1436 empty.textContent = "Start a task: attach context below and ask Codewhale. The same thread stays available in the terminal.";
1437 transcript.appendChild(empty);
1438 }
1439 }
1440 ensureEmpty();
1441 `;
1442 }
1443
1443 lines TYPESCRIPT