-
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathDaemonStatus.tsx
More file actions
377 lines (353 loc) · 14.8 KB
/
Copy pathDaemonStatus.tsx
File metadata and controls
377 lines (353 loc) · 14.8 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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import { ChevronDown, KeyRound, Power, RefreshCcw, ServerCog, Skull } from "lucide-react";
import { useEffect, useState } from "react";
import type {
DaemonAuditEntry,
DaemonBusyState,
DaemonStatusState,
WebviewMessage,
} from "@perplexity-user-mcp/shared";
import { useDashboardStore, type TunnelProbeState } from "../store";
import { BearerReveal } from "./BearerReveal";
import { DaemonActionButton } from "./DaemonActionButton";
import { RelativeTime } from "./RelativeTime";
import { StatusDot } from "./StatusDot";
import { TunnelManager, type TunnelProvidersState, deriveCfNamedState } from "./TunnelManager";
export { deriveCfNamedState };
type SendFn = (message: WebviewMessage | Omit<Extract<WebviewMessage, { id: string }>, "id">) => void;
/**
* "perplexity_research" → "Research". The daemon reports raw MCP tool names;
* the strip is user-facing.
*/
export function humanizeTool(tool: string): string {
const bare = tool.replace(/^perplexity[_-]?/i, "").replace(/[_-]+/g, " ").trim();
if (!bare) return tool;
return bare.charAt(0).toUpperCase() + bare.slice(1);
}
export function DaemonStatus({ send }: { send: SendFn }) {
const status = useDashboardStore((store) => store.daemonStatus);
const daemonBusy = useDashboardStore((store) => store.daemonBusy);
const auditTail = useDashboardStore((store) => store.daemonAuditTail);
const tokenRotatedAt = useDashboardStore((store) => store.daemonTokenRotatedAt);
const tunnelProviders = useDashboardStore((store) => store.tunnelProviders);
const tunnelProbe = useDashboardStore((store) => store.tunnelProbe);
const revealedBearer = useDashboardStore((store) => store.revealedBearer);
const clearRevealedBearer = useDashboardStore((store) => store.clearRevealedBearer);
// v0.8.5 loopback-default: pull enableTunnels from the live dashboard
// snapshot and pass explicitly so the TunnelManager wrapper decision
// doesn't depend on zustand's SSR/client snapshot divergence. Falls back
// to `false` pre-hydrate — the opt-in card is the right default.
const enableTunnels = useDashboardStore(
(store) => store.state?.settings.enableTunnels ?? false,
);
return (
<DaemonStatusView
status={status}
daemonBusy={daemonBusy}
auditTail={auditTail}
tokenRotatedAt={tokenRotatedAt}
tunnelProviders={tunnelProviders}
tunnelProbe={tunnelProbe}
enableTunnels={enableTunnels}
revealedBearer={revealedBearer}
clearRevealedBearer={clearRevealedBearer}
send={send}
/>
);
}
export function DaemonStatusView({
status,
daemonBusy = null,
auditTail,
tokenRotatedAt,
tunnelProviders,
tunnelProbe,
enableTunnels = true,
revealedBearer,
clearRevealedBearer,
send,
}: {
status: DaemonStatusState | null;
/**
* Live busy/queue state of the shared page. `null` = the daemon has not
* reported yet, so the strip stays silent rather than claiming "Ready".
* Defaults to null so existing callers/tests need no prop change.
*/
daemonBusy?: DaemonBusyState | null;
auditTail: DaemonAuditEntry[];
tokenRotatedAt: string | null;
tunnelProviders?: TunnelProvidersState | null;
tunnelProbe?: TunnelProbeState | null;
/**
* v0.8.5: when false, the TunnelManager slot collapses to a single
* opt-in card. Defaults to `true` so existing callers / tests keep
* seeing the full manager without requiring a prop change — the live
* `DaemonStatus` wrapper reads the real value from the store and
* overrides this default.
*/
enableTunnels?: boolean;
/**
* H0 reveal slice. Non-null only during an active 30s reveal. Raw bearer
* is present here — the slice itself is the enforcement mechanism (TTL +
* auto-clear) the extension host promised when it posted the response.
*/
revealedBearer?: { bearer: string; expiresAt: number; nonce: string } | null;
/** Invoked by the TTL effect when `Date.now() >= expiresAt`. */
clearRevealedBearer?: () => void;
send: SendFn;
}) {
const [bearerFeedback, setBearerFeedback] = useState<string | null>(null);
// H0 — live 1-second tick driving the reveal countdown. Re-runs per
// revealedBearer (nonce change resets). `now` is state so React re-renders
// the countdown label each second; the TTL auto-clear fires via the same
// interval callback once expiresAt is reached.
const [now, setNow] = useState<number>(() => Date.now());
useEffect(() => {
if (!revealedBearer) return;
setNow(Date.now());
const tick = window.setInterval(() => {
const current = Date.now();
setNow(current);
if (current >= revealedBearer.expiresAt) {
window.clearInterval(tick);
clearRevealedBearer?.();
}
}, 1_000);
return () => window.clearInterval(tick);
}, [revealedBearer, clearRevealedBearer]);
const tunnel = status?.tunnel ?? { status: "disabled", url: null, pid: null, error: null };
const bearerAvailable = status?.bearerAvailable ?? false;
const flashBearer = (msg: string) => {
setBearerFeedback(msg);
window.setTimeout(() => setBearerFeedback((prev) => (prev === msg ? null : prev)), 1500);
};
// Bearer copy + reveal are delegated to the extension host so the raw
// token never touches the webview state / postMessage channel. See
// daemon:bearer:copy + daemon:bearer:reveal handlers in DashboardProvider.
const copyBearer = () => {
if (!bearerAvailable) return;
send({ type: "daemon:bearer:copy" });
flashBearer("Copy requested");
};
const revealBearer = () => {
if (!bearerAvailable) return;
send({ type: "daemon:bearer:reveal" });
flashBearer("Reveal requested");
};
// Null-safe health chip — pre-hydrate, avoid flashing "Offline" red before
// the first `daemon:status-updated` arrives. `status === null` is the
// literal signal that the store slice has never been populated.
const healthChip: { label: string; chip: string; dot: "ok" | "warn" | "off" | "info" } =
status === null
? { label: "Loading…", chip: "chip-muted", dot: "info" }
: status.healthy
? { label: "Healthy", chip: "chip-pro", dot: "ok" }
: status.running
? { label: "Starting", chip: "chip-warn", dot: "warn" }
: { label: "Offline", chip: "chip-danger", dot: "off" };
// Busy strip. Three real states plus pre-hydrate:
// null → say nothing (the daemon has never reported)
// idle → calm "Ready", naming the sharing explicitly
// busy → which tool, which client, how many waiting
// Queue depth is a chip inside this strip rather than a 4th DaemonMetric:
// the metric grid is 3-up, so a 4th card would reflow onto a second row and
// jump the layout the moment work starts.
const busyStrip = (() => {
if (!daemonBusy) return null;
if (!daemonBusy.busy || !daemonBusy.active) {
return (
<span className="chip chip-muted" data-testid="daemon-busy-idle">
<StatusDot variant="ok" decorative />
Ready — shared with your other windows & IDEs
</span>
);
}
const { tool, clientId, startedAt } = daemonBusy.active;
return (
<>
<span className="chip chip-accent" data-testid="daemon-busy-active">
<StatusDot variant="info" decorative />
{humanizeTool(tool)} running
{startedAt ? (
<>
{" "}
· <RelativeTime iso={startedAt} />
</>
) : null}
</span>
{clientId ? (
<span className="chip chip-neutral" data-testid="daemon-busy-client">
from {clientId}
</span>
) : null}
{daemonBusy.queued > 0 ? (
<span className="chip chip-warn" data-testid="daemon-busy-queued">
{daemonBusy.queued} queued
</span>
) : null}
</>
);
})();
return (
<div className="glass-panel section-panel" data-testid="daemon-status-card">
<div className="section-header">
<div className="eyebrow">Singleton Daemon</div>
<div className="title">HTTP MCP server</div>
<div className="detail">
One local daemon shared by all VS Code windows and MCP clients — they queue on the
same browser session, so work started anywhere shows up here.
</div>
</div>
{/*
Own live region, deliberately NOT nested inside the bearer-reveal one
below — that region ticks every second during a reveal and would make
busy announcements chatter. Height is reserved so the strip appearing
never shifts the metric grid.
*/}
<div
className="daemon-busy-strip"
role="status"
aria-live="polite"
data-testid="daemon-busy-strip"
>
{busyStrip}
</div>
<div className="daemon-chip-row">
<span className={`chip ${healthChip.chip}`} data-testid="daemon-health-chip">
<StatusDot variant={healthChip.dot} decorative />
{healthChip.label}
</span>
<span className={`chip ${tunnel.status === "enabled" ? "chip-accent" : tunnel.status === "crashed" ? "chip-danger" : "chip-muted"}`}>
Tunnel {tunnel.status === "starting" ? "connecting…" : tunnel.status}
</span>
{tokenRotatedAt ? (
<span className="chip chip-neutral">Token rotated <RelativeTime iso={tokenRotatedAt} /></span>
) : null}
</div>
<div className="daemon-metric-grid">
<DaemonMetric label="PID" value={status?.pid ? String(status.pid) : "not running"} />
<DaemonMetric label="Port" value={status?.port ? String(status.port) : "n/a"} />
<DaemonMetric label="Uptime" value={formatUptime(status?.uptimeMs ?? null)} />
</div>
<TunnelManager
status={status}
tunnelProviders={tunnelProviders}
tunnelProbe={tunnelProbe}
enableTunnels={enableTunnels}
send={send}
/>
<div className="daemon-section-divider" aria-hidden="true" />
<div role="status" aria-live="polite">
<BearerReveal
available={bearerAvailable}
revealed={revealedBearer ?? null}
feedback={bearerFeedback}
onReveal={revealBearer}
onCopy={copyBearer}
now={now}
/>
</div>
<div className="daemon-section-divider" aria-hidden="true" />
<div className="daemon-action-row">
<DaemonActionButton
type="daemon:status"
label="Refresh"
pendingLabel="Refreshing…"
icon={<RefreshCcw size={11} />}
onClick={() => { console.log("[trace] DaemonStatus click", { button: "daemon:status" }); send({ type: "daemon:status" }); }}
/>
<DaemonActionButton
type="daemon:rotate-token"
label="Rotate token"
pendingLabel="Rotating…"
icon={<KeyRound size={11} />}
disabled={!status?.running}
onClick={() => { console.log("[trace] DaemonStatus click", { button: "daemon:rotate-token" }); send({ type: "daemon:rotate-token" }); }}
/>
<DaemonActionButton
type="daemon:restart"
label="Restart daemon"
pendingLabel="Restarting…"
icon={<Power size={11} />}
title="Stop the current daemon and spawn a fresh one. Use after a VSIX upgrade if the daemon is out of sync."
onClick={() => { console.log("[trace] DaemonStatus click", { button: "daemon:restart" }); send({ type: "daemon:restart" }); }}
/>
<DaemonActionButton
type="daemon:kill"
label="Kill daemon"
pendingLabel="Killing…"
icon={<Skull size={11} />}
className="danger-button btn-sm"
title="Force-kill the daemon. Use when tunnels are stuck (ERR_NGROK_334), the daemon isn't responding, or you want a clean-slate reset. Does NOT auto-respawn; click Restart after."
onClick={() => { console.log("[trace] DaemonStatus click", { button: "daemon:kill" }); send({ type: "daemon:kill" }); }}
/>
</div>
{status?.url ? (
<div className="daemon-muted-note">
Loopback {status.url}
</div>
) : null}
{/* Lifecycle honesty: the daemon outlives this window on purpose, and
Restart/Kill above are global, not local to it. */}
<div className="daemon-muted-note" data-testid="daemon-lifecycle-note">
Closing this window won't stop the daemon — it keeps serving your other windows and
IDE clients. Restart and Kill above affect every one of them.
</div>
<details className="daemon-disclosure">
<summary className="daemon-disclosure-summary">
<div className="daemon-disclosure-main">
<div className="eyebrow">Audit Tail</div>
<div className="title">Last tool calls</div>
</div>
{auditTail.length > 0 ? (
<span className="chip chip-neutral daemon-disclosure-count">
{auditTail.length}
</span>
) : null}
<ChevronDown size={14} className="daemon-disclosure-icon text-[var(--text-muted)]" aria-hidden="true" />
</summary>
{auditTail.length === 0 ? (
<div className="empty-state daemon-empty-offset">No daemon tool calls recorded yet.</div>
) : (
<div className="daemon-audit-list">
{[...auditTail].reverse().map((entry, index) => (
<div key={`${entry.timestamp}-${entry.tool}-${index}`} className="list-row">
<div className="daemon-audit-row-main">
<ServerCog size={12} className={entry.ok ? "text-[#86efac]" : "text-[#fca5a5]"} />
<div className="daemon-audit-entry-body">
<div className="daemon-audit-tool">{entry.tool}</div>
<div className="daemon-audit-meta">
{entry.clientId} / {entry.source} / <RelativeTime iso={entry.timestamp} />
</div>
{entry.error ? (
<div className="daemon-audit-error">{entry.error}</div>
) : null}
</div>
</div>
<span className={`chip ${entry.ok ? "chip-pro" : "chip-danger"}`}>{entry.durationMs}ms</span>
</div>
))}
</div>
)}
</details>
</div>
);
}
function DaemonMetric({ label, value }: { label: string; value: string }) {
return (
<div className="metric-card daemon-metric-card">
<div className="metric-label">{label}</div>
<div className="metric-value daemon-metric-value">{value}</div>
</div>
);
}
function formatUptime(ms: number | null): string {
if (typeof ms !== "number" || ms < 0) {
return "n/a";
}
const seconds = Math.floor(ms / 1000);
if (seconds < 60) return `${seconds}s`;
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes}m`;
const hours = Math.floor(minutes / 60);
return `${hours}h ${minutes % 60}m`;
}