返回 CodeWhale
status.ts
根目录 / extensions / vscode / src / status.ts
1 import * as crypto from "node:crypto";
2 import * as vscode from "vscode";
3 import type { RuntimeState, SnapshotEntry, ThreadSummary } from "./runtime";
4
5 export class RuntimeStatusView implements vscode.WebviewViewProvider {
6 public static readonly viewType = "codewhale.runtimeStatus";
7
8 private view?: vscode.WebviewView;
9 private state: RuntimeState = {
10 kind: "offline",
11 baseUrl: "http://127.0.0.1:7878",
12 detail: "Runtime has not been checked yet.",
13 };
14 private threads: ThreadSummary[] = [];
15 private threadsDetail = "Connect to the runtime to load recent threads.";
16 private snapshots: SnapshotEntry[] = [];
17 private snapshotsDetail = "Connect to the runtime to load restore points.";
18
19 resolveWebviewView(view: vscode.WebviewView): void {
20 this.view = view;
21 view.webview.options = { enableScripts: true };
22 view.webview.onDidReceiveMessage((message: { command?: string }) => {
23 if (message.command === "check") {
24 void vscode.commands.executeCommand("codewhale.checkRuntime");
25 } else if (message.command === "start") {
26 void vscode.commands.executeCommand("codewhale.startRuntime");
27 } else if (message.command === "terminal") {
28 void vscode.commands.executeCommand("codewhale.openTerminal");
29 } else if (message.command === "threads") {
30 void vscode.commands.executeCommand("codewhale.refreshAgentView");
31 } else if (message.command === "snapshots") {
32 void vscode.commands.executeCommand("codewhale.refreshSnapshots");
33 }
34 });
35 this.render();
36 }
37
38 update(state: RuntimeState): void {
39 this.state = state;
40 this.render();
41 }
42
43 updateThreads(threads: ThreadSummary[], detail: string): void {
44 this.threads = threads;
45 this.threadsDetail = detail;
46 this.render();
47 }
48
49 updateSnapshots(snapshots: SnapshotEntry[], detail: string): void {
50 this.snapshots = snapshots;
51 this.snapshotsDetail = detail;
52 this.render();
53 }
54
55 private render(): void {
56 if (!this.view) {
57 return;
58 }
59
60 const badge = labelFor(this.state.kind);
61 const nonce = makeNonce();
62 const threadsHtml =
63 this.threads.length > 0
64 ? this.threads.map((thread) => renderThread(thread)).join("")
65 : `<p class="detail">${escapeHtml(this.threadsDetail)}</p>`;
66 const snapshotsHtml =
67 this.snapshots.length > 0
68 ? this.snapshots.map((snapshot) => renderSnapshot(snapshot)).join("")
69 : `<p class="detail">${escapeHtml(this.snapshotsDetail)}</p>`;
70 this.view.webview.html = `<!doctype html>
71 <html lang="en">
72 <head>
73 <meta charset="UTF-8">
74 <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${nonce}';">
75 <meta name="viewport" content="width=device-width, initial-scale=1.0">
76 <style>
77 body { padding: 14px; color: var(--vscode-foreground); font-family: var(--vscode-font-family); }
78 .status { margin-bottom: 12px; font-weight: 600; }
79 .detail { margin: 0 0 14px; color: var(--vscode-descriptionForeground); line-height: 1.45; }
80 .section-title { margin: 18px 0 8px; font-size: 11px; font-weight: 700; letter-spacing: 0; text-transform: uppercase; color: var(--vscode-descriptionForeground); }
81 .thread { padding: 8px 0; border-top: 1px solid var(--vscode-sideBarSectionHeader-border, var(--vscode-panel-border)); }
82 .snapshot { padding: 8px 0; border-top: 1px solid var(--vscode-sideBarSectionHeader-border, var(--vscode-panel-border)); }
83 .thread-title, .snapshot-title { margin-bottom: 4px; font-weight: 600; overflow-wrap: anywhere; }
84 .thread-preview { margin-bottom: 5px; color: var(--vscode-descriptionForeground); line-height: 1.35; overflow-wrap: anywhere; }
85 .thread-meta { color: var(--vscode-descriptionForeground); font-size: 11px; overflow-wrap: anywhere; }
86 code { color: var(--vscode-textLink-foreground); }
87 button { width: 100%; margin: 4px 0; }
88 </style>
89 </head>
90 <body>
91 <div class="status">${escapeHtml(badge)}</div>
92 <p class="detail">${escapeHtml(this.state.detail)}</p>
93 <p class="detail"><code>${escapeHtml(this.state.baseUrl)}</code></p>
94 <button data-command="check">Check Runtime</button>
95 <button data-command="threads">Refresh Threads</button>
96 <button data-command="snapshots">Refresh Restore Points</button>
97 <button data-command="start">Start Local Runtime</button>
98 <button data-command="terminal">Open CodeWhale Terminal</button>
99 <div class="section-title">Agent View</div>
100 ${threadsHtml}
101 <div class="section-title">Restore Points</div>
102 ${snapshotsHtml}
103 <script nonce="${nonce}">
104 const vscode = acquireVsCodeApi();
105 for (const button of document.querySelectorAll("button[data-command]")) {
106 button.addEventListener("click", () => vscode.postMessage({ command: button.dataset.command }));
107 }
108 </script>
109 </body>
110 </html>`;
111 }
112 }
113
114 function renderSnapshot(snapshot: SnapshotEntry): string {
115 return `<div class="snapshot">
116 <div class="snapshot-title">${escapeHtml(snapshot.label)}</div>
117 <div class="thread-meta">${escapeHtml(`${snapshot.id} · ${formatUnixTimestamp(snapshot.timestamp)}`)}</div>
118 </div>`;
119 }
120
121 function renderThread(thread: ThreadSummary): string {
122 const status = thread.latestTurnStatus ? ` · ${thread.latestTurnStatus}` : "";
123 const archived = thread.archived ? " · archived" : "";
124 const git = renderGitMetadata(thread);
125 const workspace = thread.workspace ? ` · ${thread.workspace}` : "";
126 const updated = thread.updatedAt ? ` · ${formatTimestamp(thread.updatedAt)}` : "";
127 return `<div class="thread">
128 <div class="thread-title">${escapeHtml(thread.title)}</div>
129 <div class="thread-preview">${escapeHtml(thread.preview || "No recent message.")}</div>
130 <div class="thread-meta">${escapeHtml(`${thread.mode} · ${thread.model}${status}${git}${archived}${updated}${workspace}`)}</div>
131 </div>`;
132 }
133
134 function renderGitMetadata(thread: ThreadSummary): string {
135 if (!thread.branch && !thread.head && !thread.dirty) {
136 return "";
137 }
138
139 const parts: string[] = [];
140 if (thread.branch) {
141 parts.push(`branch ${thread.branch}`);
142 }
143 if (thread.head) {
144 parts.push(`@ ${thread.head}`);
145 }
146 if (thread.dirty) {
147 parts.push("dirty");
148 }
149 return ` · ${parts.join(" ")}`;
150 }
151
152 function labelFor(kind: RuntimeState["kind"]): string {
153 switch (kind) {
154 case "connected":
155 return "Connected";
156 case "auth-required":
157 return "Token Required";
158 case "error":
159 return "Runtime Error";
160 case "offline":
161 return "Offline";
162 }
163 }
164
165 function formatTimestamp(value: string): string {
166 const date = new Date(value);
167 if (Number.isNaN(date.getTime())) {
168 return value;
169 }
170 return date.toLocaleString();
171 }
172
173 function formatUnixTimestamp(value: number): string {
174 const date = new Date(value * 1000);
175 if (Number.isNaN(date.getTime())) {
176 return String(value);
177 }
178 return date.toLocaleString();
179 }
180
181 function escapeHtml(value: string): string {
182 return value
183 .replace(/&/g, "&amp;")
184 .replace(/</g, "&lt;")
185 .replace(/>/g, "&gt;")
186 .replace(/"/g, "&quot;");
187 }
188
189 /** CSP nonces must be unguessable; `Math.random()` is not. Matches `chat.ts`. */
190 function makeNonce(): string {
191 return crypto.randomBytes(16).toString("hex");
192 }
193
193 lines TYPESCRIPT