-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathDashboardProvider.ts
More file actions
2629 lines (2538 loc) · 112 KB
/
Copy pathDashboardProvider.ts
File metadata and controls
2629 lines (2538 loc) · 112 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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as crypto from "node:crypto";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import * as vscode from "vscode";
import {
EXTENSION_ID,
IDE_METADATA,
type DaemonAuditEntry,
type DaemonStatusState,
type DaemonTunnelState,
type DashboardState,
type ExtensionMessage,
type McpTransportId,
type TunnelPerformanceSnapshot,
type TunnelProbeResult,
type TunnelProbeTarget,
type TunnelProviderIdShared,
type WebviewMessage
} from "@perplexity-user-mcp/shared";
import type { AuthManager, AuthState } from "../mcp/auth-manager.js";
import {
getIdeStatuses,
removeTarget,
syncRulesForIde,
removeRulesForIde,
getRulesStatuses
} from "../auto-config/index.js";
import type { IdeTarget } from "@perplexity-user-mcp/shared";
import { mergePrompts, readPromptsConfig, writePromptsConfig } from "perplexity-user-mcp/prompts-config";
import { deletePromptHandler, resetPromptHandler, savePromptHandler } from "./prompts-handler.js";
import { getAccountSnapshot, setLastRefreshTier } from "../auth/session.js";
import { ensureVaultPassphrase, peekStoredVaultPassphrase } from "../auth/vault-passphrase.js";
import { withScopedVaultPassphrase } from "../auth/scoped-env.js";
import { createExtensionAwareRunDoctor } from "../diagnostics/doctor-runner.js";
import { log, debug, getOutputRingBuffer } from "../extension.js";
import { captureDiagnostics } from "../diagnostics/capture.js";
import { handleDiagnosticsCapture } from "../diagnostics/flow.js";
import { redactMessage, redactObject } from "../redact.js";
import { REVEAL_CONFIRM_LABEL, runBearerRevealGate } from "./bearer-reveal-gate.js";
import { detectStaleConfigs } from "./staleness-detector.js";
import {
regenerateStaleIdes,
type RegenerateStaleIdesDeps,
} from "./staleness-auto-regen.js";
import { handleTransportSelect } from "./transport-select-handler.js";
import { TunnelEnableRecorder } from "./tunnel-enable-recorder.js";
import { parseTunnelPerformance } from "./tunnel-performance.js";
import { confirmTunnelSwitch } from "./tunnel-switch-confirm.js";
import {
handleCfNamedCreate,
handleCfNamedDeleteRemote,
handleCfNamedList,
handleCfNamedLogin,
handleCfNamedUnbindLocal,
type CfNamedDeps,
} from "./cf-named-handlers.js";
import {
listProfiles,
getActiveName,
getProfilePaths,
setActive,
createProfile,
deleteProfile,
} from "perplexity-user-mcp/profiles";
import { refreshAccountInfo } from "../browser/runtime.js";
import { installImpit, uninstallImpit } from "../native-deps.js";
import { getSettingsSnapshot, updateSettings } from "../settings.js";
import { renderWebviewHtml } from "./html.js";
import { LAUNCHER_PATH } from "../launcher/write-launcher.js";
import {
configureExternalViewer,
countHistoryEntries,
deleteHistoryEntry,
listExternalViewers,
listHistoryEntries,
openExternalViewer,
openPreview,
openRichView,
pinHistoryEntry,
rebuildHistoryEntries,
runCloudSync,
hydrateCloudEntry,
runExport,
tagHistoryEntry,
} from "../history/open-handlers.js";
import {
clearBundledNgrokSettings,
clearCfNamedConfig,
createCfNamedTunnel,
deleteCfNamedTunnel,
disableBundledDaemonTunnel,
enableBundledDaemonTunnel,
ensureBundledDaemon,
getBundledActiveTunnelProvider,
getBundledCfNamedState,
getBundledDaemonStatus,
getBundledNgrokSettings,
installBundledCloudflared,
isCloudflaredInstalled,
killBundledDaemon,
listBundledOAuthClients,
listBundledOAuthConsents,
listBundledTunnelProviders,
listCfNamedTunnels,
readBundledDaemonAuditTail,
readCfNamedConfig,
restartBundledDaemon,
revokeAllBundledOAuthClients,
revokeAllBundledOAuthConsents,
revokeBundledOAuthClient,
revokeBundledOAuthConsent,
rotateBundledDaemonToken,
runCfNamedLogin,
setBundledActiveTunnelProvider,
setBundledNgrokAuthtoken,
setBundledNgrokDomain,
} from "../daemon/runtime.js";
export class DashboardProvider implements vscode.WebviewViewProvider {
private view: vscode.WebviewView | undefined;
private authManager?: AuthManager;
private otpResolvers = new Map<string, (s: string | null) => void>();
private onMcpServerDefinitionsChanged?: () => void;
private daemonEventsAbort: AbortController | null = null;
private daemonStatusWatcher: fs.FSWatcher | null = null;
private daemonStatusWatchedProfile: string | null = null;
// v0.8.5: deps factory injected from extension.ts so the auto-regen hook
// on `postStaleness` can reuse the live ApplyIdeConfigDeps without pulling
// the daemon runtime singletons into the webview module.
private autoRegenDepsFactory: RegenerateStaleIdesDeps | null = null;
// Cache the most-recent doctor report so "Report issue" can reuse it instead
// of re-running all 10 checks. Cleared when the user clicks Run again.
private lastDoctorReport: unknown = null;
// v0.8.5: session-local ring buffer of tunnel enable timings. Populated by
// the `daemon:enable-tunnel` handler (click-time timestamp) and finalised
// in `postDaemonState` when we observe tunnel.status === "enabled" for the
// first time after a click. Read back out via `postTunnelPerformance`.
private readonly enableRecorder = new TunnelEnableRecorder();
// Click-time metadata for an in-flight tunnel enable. `null` when no
// enable is pending. Set synchronously in the `daemon:enable-tunnel`
// handler before any await so the recorder sees a monotonic wall-clock.
private pendingTunnelEnable:
| { provider: TunnelProviderIdShared; startedAt: string; startPerf: number }
| null = null;
constructor(private readonly context: vscode.ExtensionContext) {}
setAuthManager(m: AuthManager): void {
this.authManager = m;
}
setOnMcpServerDefinitionsChanged(fn: () => void): void {
this.onMcpServerDefinitionsChanged = fn;
}
/**
* v0.8.5: inject the deps factory the staleness auto-regen hook uses. This
* stays in extension.ts because buildApplyIdeConfigDepsLive closes over the
* extension context (workspaceState, daemon runtime, vscode.window prompts).
* DashboardProvider must not grow an import on those.
*/
setAutoRegenDeps(factory: RegenerateStaleIdesDeps): void {
this.autoRegenDepsFactory = factory;
}
async postAuthState(s: AuthState): Promise<void> {
if (!this.view) return;
await this.view.webview.postMessage({ type: "auth:state", payload: s });
}
async postProfileList(): Promise<void> {
if (!this.view) return;
await this.view.webview.postMessage({ type: "profile:list", payload: { active: getActiveName(), profiles: listProfiles() } });
}
async postHistoryList(limit = 200): Promise<void> {
// Default cap aligned across all call sites (search, hydrate, rebuild,
// sync, profile-switch). Keeping these in sync prevents the "stats
// change between actions" UX where a 100-cap rebuild and a 200-cap
// sync rendered different visible totals on stores larger than 100.
if (!this.view) return;
await this.view.webview.postMessage({ type: "history:list", payload: { items: listHistoryEntries(limit), totalCount: countHistoryEntries() } });
}
async postViewersList(): Promise<void> {
if (!this.view) return;
await this.view.webview.postMessage({ type: "viewers:list", payload: { viewers: await listExternalViewers() } });
}
async postHistoryEntry(historyId: string): Promise<void> {
if (!this.view) return;
await openRichView(historyId, (message) => this.view?.webview.postMessage(message));
}
async postDoctorRun(probe: boolean): Promise<void> {
if (!this.view) return;
await this.view.webview.postMessage({
type: probe ? "doctor:probe" : "doctor:run",
id: crypto.randomBytes(6).toString("hex"),
payload: {},
});
}
async postDoctorReportIssue(): Promise<void> {
if (!this.view) return;
await this.view.webview.postMessage({
type: "doctor:report-issue",
id: crypto.randomBytes(6).toString("hex"),
payload: { category: "runtime", check: "run" },
});
}
async resolveWebviewView(webviewView: vscode.WebviewView): Promise<void> {
log("resolveWebviewView called");
this.view = webviewView;
webviewView.webview.options = {
enableScripts: true,
localResourceRoots: [vscode.Uri.joinPath(this.context.extensionUri, "media", "webview")]
};
try {
const state = this.buildState();
log(`buildState succeeded: loggedIn=${state.snapshot.loggedIn}, historyLen=${state.history.length}`);
const html = renderWebviewHtml(
webviewView.webview,
this.context.extensionUri,
state
);
log(`renderWebviewHtml succeeded: ${html.length} chars`);
webviewView.webview.html = html;
} catch (err) {
const msg = err instanceof Error ? err.stack ?? err.message : String(err);
log(`resolveWebviewView ERROR: ${msg}`);
webviewView.webview.html = `<!DOCTYPE html><html><body style="padding:16px;font-family:sans-serif;color:#f8fafc;background:#0f172a"><h2>Perplexity Dashboard Error</h2><pre style="white-space:pre-wrap;color:#fca5a5">${msg.replace(/</g, "<")}</pre><p>Check Output > Perplexity MCP for details.</p></body></html>`;
}
const disposeHook = (webviewView as vscode.WebviewView & { onDidDispose?: (listener: () => void) => vscode.Disposable }).onDidDispose?.(() => {
this.stopDaemonEventStream();
this.stopDaemonStatusWatch();
});
if (disposeHook) {
this.context.subscriptions.push(disposeHook);
}
void this.postDaemonState({ ensure: true, restartEvents: true });
webviewView.webview.onDidReceiveMessage(async (message: WebviewMessage) => {
if (message.type === "log:webview") {
const { level, args, ts } = message.payload;
const safeArgs = redactObject(args);
const serialized = safeArgs.map((a) => typeof a === "string" ? a : (() => { try { return JSON.stringify(a); } catch { return String(a); } })()).join(" ");
debug(`[webview/${level}] ${ts} ${serialized}`);
return;
}
debug(`Webview message received: ${redactMessage(JSON.stringify(message))}`);
try {
switch (message.type) {
case "ready":
debug("Handling ready");
await this.refresh();
break;
case "dashboard:refresh":
debug("Handling refresh");
// If the daemon is reporting anonymous but the profile has stored
// credentials, touch .reinit so the daemon re-runs init() and
// re-checks auth. The daemon-status.json watcher picks up the
// result and calls refresh() automatically when it completes.
this.triggerDaemonReinitIfStale();
await this.refresh();
break;
case "auth:login":
debug("Handling auth:login");
try {
const ok = await vscode.commands.executeCommand<boolean>("Perplexity.login");
await this.postActionResult(message.id, ok !== false, ok === false ? "login_not_completed" : undefined);
} catch (err) {
await this.postActionResult(message.id, false, String(err));
}
break;
case "configs:generate": {
try {
const settings = getSettingsSnapshot();
debug(`configs:generate target=${message.payload.target} launcherPath=${LAUNCHER_PATH}`);
// DashboardProvider doesn't own the deps factory (that lives in
// extension.ts with workspaceState access). For the webview-driven
// regenerate we defer to the command so the same deps apply.
// v0.8.4 — the command itself now posts success / failure notices
// (including the "N failures" error modal). Don't emit a blanket
// "MCP config written" notice here; it would overwrite the
// actionable failure notice the command just emitted.
await vscode.commands.executeCommand(
"Perplexity.generateConfigs",
message.payload.target
);
void settings;
await this.refresh();
await this.postActionResult(message.id, true);
} catch (err) {
await this.postActionResult(message.id, false, String(err));
}
break;
}
case "configs:remove": {
try {
debug(`configs:remove target=${message.payload.target}`);
const wsRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
removeTarget(message.payload.target, { workspaceRoot: wsRoot });
await this.postNotice("info", `MCP config removed from ${message.payload.target}.`);
await this.refresh();
await this.postActionResult(message.id, true);
} catch (err) {
await this.postActionResult(message.id, false, String(err));
}
break;
}
case "rules:sync": {
try {
const wsRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
debug(`rules:sync target=${message.payload.target} wsRoot=${wsRoot ?? "(none)"}`);
if (!wsRoot) {
await this.postNotice("warning", "No workspace folder open. Open a project first.");
await this.postActionResult(message.id, false, "No workspace folder open");
break;
}
if (message.payload.target === "all") {
const { IDE_METADATA } = await import("@perplexity-user-mcp/shared");
for (const key of Object.keys(IDE_METADATA)) {
syncRulesForIde(key as IdeTarget, wsRoot);
}
await this.postNotice("info", "Perplexity rules synced to all IDE formats.");
} else {
syncRulesForIde(message.payload.target, wsRoot);
await this.postNotice("info", `Perplexity rules synced for ${message.payload.target}.`);
}
await this.refresh();
await this.postActionResult(message.id, true);
} catch (err) {
await this.postActionResult(message.id, false, String(err));
}
break;
}
case "rules:remove": {
try {
const wsRoot2 = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
debug(`rules:remove target=${message.payload.target} wsRoot=${wsRoot2 ?? "(none)"}`);
if (wsRoot2) {
removeRulesForIde(message.payload.target, wsRoot2);
await this.postNotice("info", `Perplexity rules removed from ${message.payload.target}.`);
}
await this.refresh();
await this.postActionResult(message.id, true);
} catch (err) {
await this.postActionResult(message.id, false, String(err));
}
break;
}
case "settings:update":
debug(`settings:update payload=${JSON.stringify(message.payload)}`);
// v0.8.5: enableTunnels=false triggers a confirm modal + atomic
// tunnel shutdown before the setting flip. The check happens here
// (not on the webview) so the modal + daemon call run as a single
// host-side transaction. Other keys in the same payload are still
// applied even when the user cancels the tunnel opt-out.
if (message.payload.enableTunnels === false) {
const status = await getBundledDaemonStatus().catch(() => null);
const tunnelActive =
status?.health?.tunnel?.status === "enabled" ||
status?.health?.tunnel?.status === "starting";
const choice = await vscode.window.showWarningMessage(
"Disable tunnel options?",
{
modal: true,
detail: tunnelActive
? "The active tunnel will shut down. http-loopback and stdio configs remain working."
: "The dashboard will hide tunnel controls. http-loopback and stdio configs remain working.",
},
"Disable",
);
if (choice !== "Disable") {
// Strip the enableTunnels toggle from the partial so any
// co-sent keys still apply, then refresh so the UI stays
// consistent with the unchanged value.
const rest = { ...message.payload };
delete rest.enableTunnels;
if (Object.keys(rest).length > 0) {
await updateSettings(rest);
}
await this.refresh();
break;
}
if (tunnelActive) {
try {
await disableBundledDaemonTunnel();
} catch (err) {
// Log + surface but continue flipping the setting — the
// user asked to hide tunnel UI and we shouldn't trap them
// with a stuck tunnel if shutdown races a crashed process.
debug(
`disable-tunnel during enableTunnels=false failed: ${(err as Error).message}`,
);
await this.postNotice(
"warning",
`Tunnel shutdown reported: ${(err as Error).message}`,
);
}
}
}
await updateSettings(message.payload);
await this.refresh();
break;
case "models:refresh":
debug("Handling models:refresh");
await this.handleModelsRefresh(message.id);
break;
case "speed-boost:install":
debug("Handling speed-boost:install");
await this.handleSpeedBoostInstall(message.id);
break;
case "speed-boost:uninstall":
debug("Handling speed-boost:uninstall");
await this.handleSpeedBoostUninstall(message.id);
break;
case "auth:login-start": {
if (!this.authManager) break;
const { profile, mode, email } = message.payload;
// Reject any stale resolver for this profile so a retried login doesn't leak.
this.otpResolvers.get(profile)?.(null);
this.otpResolvers.delete(profile);
try {
const runLogin = (loginMode: "auto" | "manual") => this.authManager!.login({
profile,
mode: loginMode,
...(loginMode === "auto" ? { email } : {}),
onOtpPrompt: () => new Promise<string | null>((resolve) => {
void this.view?.webview.postMessage({ type: "auth:otp-prompt", payload: { profile, attempt: 0, email: email ?? "" } });
this.otpResolvers.set(profile, resolve);
}),
onProgress: (phase) => {
if (phase !== "awaiting_user" || loginMode !== "manual") return;
const message = "Manual login opened in Chrome. Finish sign-in there; if it is behind other windows, bring Chrome to the front.";
void vscode.window.showInformationMessage(message);
void this.postNotice("info", message);
},
// v0.8.6: Linux-viable unseal. Keytar-happy machines short-circuit
// inside the provider; headless Linux prompts once via SecretStorage.
passphraseProvider: () => ensureVaultPassphrase(this.context),
});
const result = await runLogin(mode);
// v0.8.6: post a user-facing notice that includes the runner's real
// error message (not just the `reason` enum). Truncation happens in
// the auth manager so the detail fits a toast.
const loginFailedNotice = (reason: string, error?: string, detail?: string) => {
const text = error && error !== reason
? `Login failed for '${profile}' (${reason}): ${error}`
: `Login failed for '${profile}': ${reason}`;
void this.postNotice("error", text);
if (detail && detail !== error) {
debug(`[login:${profile}] detail: ${detail}`);
}
};
if (!result.ok && result.reason === "auto_unsupported" && mode === "auto") {
await this.postNotice("info", "Auto login could not continue with the current site response — opening manual login instead.");
const fallback = await runLogin("manual");
if (!fallback.ok) {
loginFailedNotice(fallback.reason ?? "manual-fallback-failed", fallback.error, fallback.detail);
await this.postActionResult(message.id, false, fallback.reason ?? "manual-fallback-failed");
} else {
this.onMcpServerDefinitionsChanged?.();
await this.postActionResult(message.id, true);
}
} else if (!result.ok) {
loginFailedNotice(result.reason ?? "login_failed", result.error, result.detail);
await this.postActionResult(message.id, false, result.reason ?? "login_failed");
} else {
this.onMcpServerDefinitionsChanged?.();
await this.postActionResult(message.id, true);
}
} catch (err) {
await this.postActionResult(message.id, false, (err as Error).message);
} finally {
// Drop any un-resolved resolver for this profile (e.g. user cancelled modal)
this.otpResolvers.delete(profile);
}
await this.refresh();
break;
}
case "auth:otp-submit": {
const { profile, otp } = message.payload;
const resolver = this.otpResolvers.get(profile);
if (resolver) {
resolver(otp);
this.otpResolvers.delete(profile);
}
break;
}
case "auth:cancel": {
// Break out of a hung login: tells AuthManager to abort the
// spawned runner and clear the inflight lock so the next
// login click doesn't bounce with "already in progress".
const cancelled = this.authManager
? await this.authManager.cancelLogin(message.payload.profile)
: false;
await this.postActionResult(message.id, cancelled);
await this.refresh();
break;
}
case "auth:logout": {
if (!this.authManager) break;
await this.authManager.logout(message.payload);
this.onMcpServerDefinitionsChanged?.();
await this.postActionResult(message.id, true);
await this.refresh();
break;
}
case "auth:dismiss-expired":
break;
case "profile:switch": {
setActive(message.payload.name);
this.onMcpServerDefinitionsChanged?.();
// The active profile changed → re-supply its vault passphrase to
// the running daemon so it can unlock the new profile (otherwise it
// stays anonymous with the previous profile's passphrase).
void this.reinitDaemonWithPassphrase();
await this.postActionResult(message.id, true);
await this.postProfileList();
await this.refresh();
break;
}
case "profile:add-prompt": {
try {
await vscode.commands.executeCommand("Perplexity.addAccount");
} catch (err) {
await this.postNotice("error", `Could not add profile: ${(err as Error).message}`);
}
break;
}
case "profile:add": {
try {
createProfile(message.payload.name, { loginMode: message.payload.loginMode });
setActive(message.payload.name);
this.onMcpServerDefinitionsChanged?.();
await this.postActionResult(message.id, true);
} catch (err) {
await this.postActionResult(message.id, false, (err as Error).message);
}
await this.postProfileList();
await this.refresh();
break;
}
case "profile:delete": {
const name = message.payload.name;
const confirm = await vscode.window.showWarningMessage(
`Delete profile '${name}' and remove its stored cookies, browser data, cache, history, attachments, and local profile files?`,
{
modal: true,
detail: "This permanently removes the local Perplexity MCP profile from this machine.",
},
"Delete profile",
);
if (confirm !== "Delete profile") {
await this.postActionResult(message.id, false, "cancelled");
break;
}
const wasActive = getActiveName() === name;
deleteProfile(name);
if (wasActive) this.onMcpServerDefinitionsChanged?.();
await this.postNotice("info", `Deleted profile '${name}'.`);
await this.postActionResult(message.id, true);
await this.postProfileList();
await this.refresh();
break;
}
case "doctor:run":
case "doctor:probe": {
await this.view?.webview.postMessage({ type: "doctor:running", payload: { probeRan: message.type === "doctor:probe" } });
try {
const runDoctorBound = this.buildRunDoctor();
const report = await runDoctorBound({
probe: message.type === "doctor:probe",
});
this.lastDoctorReport = report;
await this.view?.webview.postMessage({ type: "doctor:report", payload: report });
await this.postActionResult(message.id, true);
} catch (err) {
await this.postActionResult(message.id, false, (err as Error).message);
}
break;
}
case "doctor:export": {
try {
const uri = await vscode.window.showSaveDialog({
defaultUri: vscode.Uri.file(`doctor-report-${Date.now()}.json`),
filters: { JSON: ["json"] },
});
if (uri) {
const runDoctorBound = this.buildRunDoctor();
const report = await runDoctorBound();
await vscode.workspace.fs.writeFile(uri, Buffer.from(JSON.stringify(report, null, 2)));
await this.postNotice("info", `Doctor report written to ${uri.fsPath}.`);
}
await this.postActionResult(message.id, true);
} catch (err) {
await this.postActionResult(message.id, false, (err as Error).message);
}
break;
}
case "doctor:report-issue": {
try {
let report = this.lastDoctorReport;
if (!report) {
const runDoctorBound = this.buildRunDoctor();
report = await runDoctorBound();
this.lastDoctorReport = report;
}
const { collectDiagnostics, renderPreview, openIssue, buildIssueUrl } = await import("./doctor-report-handler.js");
const diag = collectDiagnostics({
report: report as import("@perplexity-user-mcp/shared").DoctorReport,
stderrTail: "(extension output channel tail not yet wired)",
extVersion: this.context.extension.packageJSON.version as string,
nodeVersion: process.version,
os: `${process.platform} ${process.arch}`,
activeTier: getAccountSnapshot().tier ?? null,
});
const choice = await renderPreview({
markdown: diag.markdown,
showInformationMessage: vscode.window.showInformationMessage,
});
if (choice === "Copy to clipboard") {
await vscode.env.clipboard.writeText(diag.markdown);
await this.postNotice("info", "Redacted report copied to clipboard.");
} else if (choice === "Open GitHub issue") {
const url = (buildIssueUrl as Function)({
owner: "nskha",
repo: "perplexity-user-mcp",
category: message.payload.category,
check: message.payload.check,
body: diag.markdown,
});
await openIssue({ url, optOut: false, openExternal: (u: unknown) => vscode.env.openExternal(vscode.Uri.parse(String(u))) });
}
await this.postActionResult(message.id, true);
} catch (err) {
await this.postActionResult(message.id, false, (err as Error).message);
}
break;
}
case "doctor:action": {
try {
const { commandId, args } = message.payload;
// Whitelist of commands the webview may trigger through doctor actions.
// Keeps the `doctor:action` channel safe from arbitrary command execution
// if the webview is ever compromised.
const allowed = new Set([
"Perplexity.installSpeedBoost",
"Perplexity.uninstallSpeedBoost",
"Perplexity.generateConfigs",
"Perplexity.addAccount",
"Perplexity.switchAccount",
"Perplexity.refreshDashboard",
]);
if (!allowed.has(commandId)) {
throw new Error(`Command '${commandId}' is not allowed from a doctor action.`);
}
await vscode.commands.executeCommand(commandId, ...(args ?? []));
// Invalidate cached report so the next Run picks up the now-fixed state.
this.lastDoctorReport = null;
await this.postActionResult(message.id, true);
} catch (err) {
await this.postActionResult(message.id, false, (err as Error).message);
}
break;
}
case "daemon:status": {
try {
await this.postDaemonState({ ensure: true, restartEvents: true });
await this.postActionResult(message.id, true);
} catch (err) {
await this.postActionResult(message.id, false, (err as Error).message);
}
break;
}
case "daemon:list-tunnel-providers": {
try {
await this.postTunnelProviders();
await this.postActionResult(message.id, true);
} catch (err) {
await this.postActionResult(message.id, false, (err as Error).message);
}
break;
}
case "daemon:set-tunnel-provider": {
try {
const { providerId } = message.payload;
// v0.8.5: confirm gate. Read pre-switch state so the modal can
// tell the user what will be disrupted. We inspect the live
// daemon status for the "tunnel actually enabled right now"
// signal (matches the existing hasTunnel check in
// daemon:clear-ngrok-settings) and use the settings file for the
// currently-selected provider.
const beforeStatus = await getBundledDaemonStatus();
const currentTunnelEnabled = Boolean(
beforeStatus.health?.tunnel?.url ?? beforeStatus.record?.tunnelUrl,
);
const currentProvider = getBundledActiveTunnelProvider();
const confirmed = await confirmTunnelSwitch({
nextProvider: providerId,
deps: {
showWarningMessage: vscode.window.showWarningMessage,
currentProvider,
currentTunnelEnabled,
},
});
if (!confirmed) {
// User cancelled — not a failure. Clear the spinner and bail.
await this.postActionResult(message.id, true);
break;
}
const wasRunning = beforeStatus.record?.tunnelUrl != null;
if (wasRunning) {
await disableBundledDaemonTunnel();
}
setBundledActiveTunnelProvider(providerId);
await this.postTunnelProviders();
const providerLabel =
providerId === "ngrok"
? "ngrok"
: providerId === "cf-named"
? "Cloudflare Named Tunnel"
: "Cloudflare Quick";
await this.postNotice("info", `Active tunnel provider set to ${providerLabel}. Click Enable to start it.`);
// v0.8.5: re-run staleness so the banner reflects the new
// provider immediately. The tunnel URL is gone at this point (we
// disabled it above), so any http-tunnel IDE should now flag as
// stale until the user re-enables + regenerates.
await this.postStaleness(await getBundledDaemonStatus());
await this.postActionResult(message.id, true);
} catch (err) {
await this.postActionResult(message.id, false, (err as Error).message);
}
break;
}
case "daemon:set-ngrok-authtoken": {
try {
const token = (message.payload.authtoken ?? "").trim();
if (token.length < 10) {
throw new Error("Authtoken looks invalid (too short). Paste the full token from dashboard.ngrok.com/get-started/your-authtoken.");
}
setBundledNgrokAuthtoken(token);
await this.postTunnelProviders();
await this.maybeWarnNgrokChangeRequiresReEnable("authtoken");
await this.postNotice("info", "ngrok authtoken saved.");
await this.postActionResult(message.id, true);
} catch (err) {
await this.postActionResult(message.id, false, (err as Error).message);
}
break;
}
case "daemon:set-ngrok-domain": {
try {
const domain = (message.payload.domain ?? "").trim();
setBundledNgrokDomain(domain.length > 0 ? domain : null);
await this.postTunnelProviders();
await this.maybeWarnNgrokChangeRequiresReEnable("reserved domain");
await this.postNotice("info", domain ? `ngrok reserved domain set to ${domain}.` : "ngrok reserved domain cleared.");
await this.postActionResult(message.id, true);
} catch (err) {
await this.postActionResult(message.id, false, (err as Error).message);
}
break;
}
case "daemon:clear-ngrok-settings": {
try {
const activeProvider = getBundledActiveTunnelProvider();
const status = await getBundledDaemonStatus();
const hasTunnel = Boolean(status.health?.tunnel?.url ?? status.record?.tunnelUrl);
if (activeProvider === "ngrok" && hasTunnel) {
await disableBundledDaemonTunnel();
}
clearBundledNgrokSettings();
await this.postTunnelProviders();
await this.postDaemonState({ restartEvents: true });
await this.postNotice("info", "ngrok local settings deleted. Remote ngrok endpoints/domains remain in the ngrok dashboard.");
await this.postActionResult(message.id, true);
} catch (err) {
await this.postActionResult(message.id, false, (err as Error).message);
}
break;
}
case "daemon:install-cloudflared": {
// Simple passthrough — the cf-named widget uses this when the
// user clicks "Install cloudflared" in the missing-binary state.
// The enable-tunnel path has its own inline install prompt; this
// message lets the cf-named widget trigger the same install
// without also enabling a tunnel.
try {
await vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: "Downloading cloudflared…",
cancellable: false,
},
async () => {
await installBundledCloudflared();
},
);
await this.postTunnelProviders();
await this.postNotice("info", "cloudflared installed.");
await this.postActionResult(message.id, true);
} catch (err) {
await this.postActionResult(message.id, false, (err as Error).message);
}
break;
}
case "daemon:cf-named-login": {
// Delegate to the pure helper so tests can exercise the modal +
// runtime wiring without a webview host. The helper posts the
// result message in every branch (cancel / ok / error).
const deps = this.makeCfNamedDeps();
const outcome = await handleCfNamedLogin(message.id, deps);
debug(`[cf-named] post-login: handler returned outcome=${outcome}`);
if (outcome === "ok") {
await this.postTunnelProviders();
debug(`[cf-named] post-login: postTunnelProviders done`);
await this.postNotice("info", "cloudflared login complete.");
debug(`[cf-named] post-login: postNotice done`);
await this.postActionResult(message.id, true);
debug(`[cf-named] post-login: postActionResult done`);
} else {
await this.postActionResult(message.id, false, outcome);
}
break;
}
case "daemon:cf-named-create": {
const deps = this.makeCfNamedDeps();
const outcome = await handleCfNamedCreate(message.id, message.payload, deps);
if (outcome === "ok") {
await this.postTunnelProviders();
await this.postNotice(
"info",
message.payload.mode === "create"
? `Created tunnel "${message.payload.name}" → ${message.payload.hostname}.`
: `Bound existing tunnel → ${message.payload.hostname}.`,
);
await this.postActionResult(message.id, true);
} else {
await this.postActionResult(message.id, false, outcome);
}
break;
}
case "daemon:cf-named-list": {
const deps = this.makeCfNamedDeps();
const outcome = await handleCfNamedList(message.id, deps);
await this.postActionResult(message.id, outcome === "ok");
break;
}
case "daemon:cf-named-unbind-local": {
const deps = this.makeCfNamedDeps();
const outcome = await handleCfNamedUnbindLocal(message.id, message.payload, deps);
if (outcome === "ok") {
await this.postTunnelProviders();
await this.postDaemonState({ restartEvents: true });
await this.postNotice("info", "Cloudflare named tunnel local config unbound.");
await this.postActionResult(message.id, true);
} else {
await this.postActionResult(message.id, false, outcome);
}
break;
}
case "daemon:cf-named-delete-remote": {
const deps = this.makeCfNamedDeps();
const outcome = await handleCfNamedDeleteRemote(message.id, message.payload, deps);
if (outcome === "ok") {
await this.postTunnelProviders();
await this.postDaemonState({ restartEvents: true });
await this.postNotice("warning", `Deleted remote Cloudflare tunnel "${message.payload.name}". Remove the DNS CNAME for ${message.payload.hostname ?? "the hostname"} in Cloudflare DNS if it still exists.`);
await this.postActionResult(message.id, true);
} else {
await this.postTunnelProviders();
await this.postDaemonState({ restartEvents: true });
await this.postActionResult(message.id, false, outcome);
}
break;
}
case "daemon:tunnel-probe": {
await this.handleTunnelProbe(message);
break;
}
case "daemon:kill": {
const confirm = await vscode.window.showWarningMessage(
"Force-kill the daemon?\n\nThis sends SIGTERM+SIGKILL to the daemon process, closes the tunnel, and releases the lockfile. Existing MCP clients will disconnect. The extension will NOT auto-spawn a fresh daemon — click Restart to bring it back.",
{ modal: true },
"Kill daemon",
);
if (confirm !== "Kill daemon") {
await this.postActionResult(message.id, false, "cancelled");
break;
}
try {
this.stopDaemonEventStream();
const result = await killBundledDaemon();
await this.postDaemonState();
this.onMcpServerDefinitionsChanged?.();
await this.postNotice(
"info",
result.forced
? `Daemon force-killed (pid=${result.pid ?? "?"}). Lockfile released.`
: result.stopped
? `Daemon stopped cleanly (pid=${result.pid ?? "?"}).`
: "Daemon was not running.",
);
await this.postActionResult(message.id, true);
} catch (err) {
const detail = err instanceof Error ? (err.stack ?? err.message) : String(err);
await this.postNotice("error", `Kill daemon failed: ${(err as Error).message}`);
debug(`[trace] daemon:kill FAILED: ${detail}`);
await this.postActionResult(message.id, false, (err as Error).message);
}
break;
}
case "daemon:restart": {
try {
await this.postNotice("info", "Restarting daemon — this will drop any open tunnel for a few seconds.");
this.stopDaemonEventStream();
await restartBundledDaemon();
await this.postDaemonState({ ensure: false, restartEvents: true });
this.onMcpServerDefinitionsChanged?.();
await this.postNotice("info", "Daemon restarted.");
await this.postActionResult(message.id, true);
} catch (err) {
const detail = err instanceof Error ? (err.stack ?? err.message) : String(err);
await this.postNotice("error", `Daemon restart failed: ${(err as Error).message}`);
debug(`[trace] daemon:restart FAILED: ${detail}`);
await this.postActionResult(message.id, false, (err as Error).message);
}
break;
}
case "daemon:rotate-token": {
const confirm = await vscode.window.showWarningMessage(
"Rotate the daemon bearer token? Existing MCP clients must reconnect before they can use the daemon again.",
{
modal: true,
detail: "This updates the token file and daemon lockfile, then broadcasts a token-rotation event.",
},
"Rotate token",
);
if (confirm !== "Rotate token") {
await this.postActionResult(message.id, false, "cancelled");
break;
}
try {
await rotateBundledDaemonToken();
await this.view?.webview.postMessage({
type: "daemon:token-rotated",
payload: { rotatedAt: new Date().toISOString() },
} satisfies ExtensionMessage);
this.onMcpServerDefinitionsChanged?.();
await this.postDaemonState({ ensure: true, restartEvents: true });
await this.postNotice("info", "Daemon token rotated. MCP clients will reconnect with the new bearer token.");
await this.postActionResult(message.id, true);
} catch (err) {
await this.postActionResult(message.id, false, (err as Error).message);
}
break;
}
case "daemon:enable-tunnel": {
const confirm = await vscode.window.showWarningMessage(
"Your Perplexity Pro/Max session will be accessible over the public internet. Anyone with the tunnel URL and bearer token can use your account. Continue?",
{ modal: true },
"Enable tunnel",
);
if (confirm !== "Enable tunnel") {
await this.postActionResult(message.id, false, "cancelled");
break;
}
// v0.8.5: start the perf timer only AFTER the user confirms. The
// modal open time is not a tunnel metric — it's UX time. We use
// performance.now() for duration (monotonic, immune to clock
// changes) and Date for the display timestamp.
const provider = getBundledActiveTunnelProvider();
const startPerf = performance.now();
const startedAt = new Date().toISOString();
try {
if (!isCloudflaredInstalled()) {
const installChoice = await vscode.window.showInformationMessage(
"Cloudflare Tunnel requires the cloudflared binary (~25 MB). Download it now from github.com/cloudflare/cloudflared?",
{ modal: true },
"Download and enable",
);
if (installChoice !== "Download and enable") {
await this.postActionResult(message.id, false, "cancelled");
break;
}
await vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,