-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathApp.tsx
More file actions
303 lines (279 loc) · 12.3 KB
/
Copy pathApp.tsx
File metadata and controls
303 lines (279 loc) · 12.3 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
import { BookOpen, Bot, Clock3, Compass, Layers3, RefreshCcw, Settings2, ShieldCheck, Sparkles, SquareSlash, Stethoscope } from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { startTransition, useCallback, useDeferredValue, useEffect, useRef, useState } from "react";
import type { ExtensionMessage, HistoryItem, WebviewMessage } from "@perplexity-user-mcp/shared";
import { postMessage } from "./lib/vscode";
import { ACTION_TYPES } from "./action-types";
import { type AppTab, useDashboardStore } from "./store";
import {
DashboardView,
HistoryView,
ModelsView,
RulesView,
SettingsView,
buildModelGroups,
prettifyMode,
tierClass,
} from "./views";
import { ProfileSwitcher } from "./components/ProfileSwitcher";
import { OtpModal } from "./components/OtpModal";
import { ExpiredBanner } from "./components/ExpiredBanner";
import { DoctorTab } from "./components/DoctorTab";
import { PromptsTab } from "./components/PromptsTab";
import { RichView } from "./components/RichView";
const tabs: Array<{ id: AppTab; label: string; icon: typeof Compass }> = [
{ id: "dashboard", label: "Home", icon: Compass },
{ id: "settings", label: "IDEs", icon: Settings2 },
{ id: "rules", label: "Rules", icon: BookOpen },
{ id: "prompts", label: "Prompts", icon: SquareSlash },
{ id: "models", label: "Models", icon: Layers3 },
{ id: "doctor", label: "Doctor", icon: Stethoscope },
{ id: "history", label: "History", icon: Clock3 },
];
const initialDashboardState = window.__PERPLEXITY_INITIAL_STATE__;
let actionSeq = 0;
function nextActionId(prefix: string): string {
return `${prefix}-${++actionSeq}-${Date.now().toString(36)}`;
}
/**
* Send a webview message. For action-type messages the `id` field is
* auto-generated and the action is registered as pending in the store.
*/
function send(message: WebviewMessage | Omit<Extract<WebviewMessage, { id: string }>, "id">): void {
// Profile switch + "Refresh state" both re-supply the vault passphrase and
// hot-reload the daemon (a headed reinit that takes ~30s). Flag it so the
// daemon badge shows a "Reconnecting…" spinner instead of looking stuck.
if (message.type === "profile:switch" || message.type === "dashboard:refresh") {
useDashboardStore.getState().startReconnecting();
}
if (ACTION_TYPES.has(message.type) && !("id" in message && message.id)) {
const id = nextActionId(message.type);
const full = { ...message, id } as WebviewMessage;
useDashboardStore.getState().markActionPending(id);
postMessage(full);
return;
}
postMessage(message as WebviewMessage);
}
function filterHistory(items: HistoryItem[], filter: string): HistoryItem[] {
if (!filter.trim()) {
return items;
}
const needle = filter.toLowerCase();
return items.filter(
(item) =>
item.query.toLowerCase().includes(needle) ||
item.tool.toLowerCase().includes(needle) ||
item.answerPreview.toLowerCase().includes(needle) ||
(item.model ?? "").toLowerCase().includes(needle) ||
(item.status ?? "").toLowerCase().includes(needle) ||
(item.tags ?? []).some((tag) => tag.toLowerCase().includes(needle)),
);
}
function DoctorTabWrapper({ send }: { send: (m: WebviewMessage | Omit<Extract<WebviewMessage, { id: string }>, "id">) => void }) {
const report = useDashboardStore((s) => s.doctor.report);
const phase = useDashboardStore((s) => s.doctor.phase);
const reportingOptOut = useDashboardStore((s) => s.doctor.reportingOptOut);
return <DoctorTab report={report} phase={phase} reportingOptOut={reportingOptOut} send={send} />;
}
function App() {
const state = useDashboardStore((store) => store.state);
const activeTab = useDashboardStore((store) => store.activeTab);
const hydrate = useDashboardStore((store) => store.hydrate);
const setActiveTab = useDashboardStore((store) => store.setActiveTab);
const notice = useDashboardStore((store) => store.notice);
const clearNotice = useDashboardStore((store) => store.clearNotice);
const modelsRefresh = useDashboardStore((store) => store.modelsRefresh);
const activeProfile = useDashboardStore((store) => store.activeProfile);
const authState = useDashboardStore((store) => store.authState);
const richViewEntry = useDashboardStore((store) => store.richViewEntry);
const externalViewers = useDashboardStore((store) => store.externalViewers);
const setRichViewEntry = useDashboardStore((store) => store.setRichViewEntry);
const reduceMotion = useReducedMotion();
const [modelFilter, setModelFilter] = useState("");
const [historyFilter, setHistoryFilter] = useState("");
const deferredModelFilter = useDeferredValue(modelFilter);
const deferredHistoryFilter = useDeferredValue(historyFilter);
const hydrateRef = useRef(hydrate);
hydrateRef.current = hydrate;
const onMessage = useCallback((event: MessageEvent<ExtensionMessage>) => {
const msg = event.data;
if (msg.type === "action:result") {
useDashboardStore.getState().markActionDone(msg.id);
return;
}
if (msg.type === "auth:state") {
useDashboardStore.getState().setAuthState(msg.payload);
return;
}
if (msg.type === "profile:list") {
useDashboardStore.getState().setProfiles(msg.payload);
return;
}
if (msg.type === "auth:otp-prompt") {
useDashboardStore.getState().openOtpPrompt(msg.payload);
return;
}
hydrateRef.current(msg);
}, []);
useEffect(() => {
if (initialDashboardState) {
hydrate({ type: "dashboard:state", payload: initialDashboardState });
}
window.addEventListener("message", onMessage);
send({ type: "ready" });
return () => window.removeEventListener("message", onMessage);
}, [hydrate, onMessage]);
const snapshot = state?.snapshot;
const filteredHistory = filterHistory(state?.history ?? [], deferredHistoryFilter);
const modelGroups = buildModelGroups(state, deferredModelFilter);
const openTab = useCallback((tab: AppTab) => {
startTransition(() => setActiveTab(tab));
}, [setActiveTab]);
return (
<div className="app-shell">
<div className="absolute inset-0 pointer-events-none overflow-hidden">
<div className="orb orb-a" />
<div className="orb orb-b" />
</div>
<ExpiredBanner send={send} />
<OtpModal send={send} />
{richViewEntry ? (
<RichView
entry={richViewEntry}
viewers={externalViewers}
send={send}
onClose={() => setRichViewEntry(null)}
/>
) : null}
<header className="glass-panel sidebar-panel">
<div className="app-header-row">
<div className="brand-mark">
<Bot size={14} />
</div>
<div className="app-header-title">
<div className="app-header-eyebrow">Perplexity</div>
<div className="text-sm font-semibold text-[var(--text-primary)] truncate">
{!activeProfile ? "No Account Yet" : snapshot?.loggedIn ? "Command Center" : "Login Required"}
</div>
</div>
<div className="app-header-actions">
{snapshot ? (
<div className={`chip app-tier-chip ${tierClass(snapshot.tier)}`}>
<ShieldCheck size={12} />
<span>{snapshot.tier}</span>
</div>
) : null}
<ProfileSwitcher send={send} />
</div>
</div>
<div className="tab-bar">
{tabs.map((tab) => {
const Icon = tab.icon;
return (
<button
key={tab.id}
className={`nav-item ${activeTab === tab.id ? "nav-item-active" : ""}`}
onClick={() => openTab(tab.id)}
>
<Icon size={14} />
<span>{tab.label}</span>
</button>
);
})}
</div>
<div className="app-quick-actions">
<button
className="ghost-button app-quick-action"
onClick={() => send({ type: "models:refresh" })}
disabled={modelsRefresh.phase === "pending"}
title="Re-fetch live models + account info from Perplexity"
>
<RefreshCcw size={13} className={modelsRefresh.phase === "pending" ? "refresh-spin" : undefined} />
<span>{modelsRefresh.phase === "pending" ? "Refreshing..." : "Refresh"}</span>
</button>
{!activeProfile ? (
<button className="primary-button app-quick-action" onClick={() => send({ type: "profile:add-prompt" })}>
<Sparkles size={13} />
<span>Add account</span>
</button>
) : authState?.status === "logging-in" || authState?.status === "awaiting_otp" ? (
// Cancel button replaces Login while a runner is in flight, so the
// user can break out of a hung browser-fallback login (e.g. CF
// turnstile didn't surface, or the impit→browser fallback opened
// a window the user closed). Hitting Login again would otherwise
// bounce with "Login already in progress".
<button
className="ghost-button app-quick-action app-quick-action-muted"
onClick={() => send({ type: "auth:cancel", payload: { profile: activeProfile } })}
title="Abort the in-flight login attempt and release the lock"
>
<Sparkles size={13} />
<span>Cancel login</span>
</button>
) : snapshot?.loggedIn ? (
<button className="ghost-button app-quick-action app-quick-action-muted" onClick={() => send({ type: "auth:login" })}>
<Sparkles size={13} />
<span>Re-login</span>
</button>
) : (
<button className="primary-button app-quick-action" onClick={() => send({ type: "auth:login" })}>
<Sparkles size={13} />
<span>Login</span>
</button>
)}
</div>
</header>
<main className="content-shell">
<AnimatePresence mode="wait">
<motion.section
key={activeTab}
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -12 }}
transition={reduceMotion ? { duration: 0 } : { duration: 0.22, ease: "easeOut" }}
className="grid gap-3"
>
{notice ? (
<div
className={`glass-panel notice notice-${notice.level}`}
role={notice.level === "error" ? "alert" : "status"}
aria-live={notice.level === "error" ? "assertive" : "polite"}
>
<div className="text-sm text-[var(--text-primary)]">{notice.message}</div>
<button className="ghost-button" onClick={clearNotice}>
Dismiss
</button>
</div>
) : null}
{!state ? <div className="glass-panel hero-panel">Waiting for extension state...</div> : null}
{state && activeTab === "dashboard" ? (
<DashboardView state={state} send={send} onOpenTab={openTab} />
) : null}
{state && activeTab === "models" ? (
<ModelsView filter={modelFilter} setFilter={setModelFilter} groups={modelGroups} state={state} send={send} />
) : null}
{state && activeTab === "history" ? (
<HistoryView
filter={historyFilter}
setFilter={setHistoryFilter}
items={filteredHistory}
totalCount={state.historyTotalCount ?? state.history.length}
cloudCount={state.history.filter(i => i.source === "cloud").length}
totalSources={state.history.reduce((s, i) => s + (i.sourceCount ?? 0), 0)}
send={send}
/>
) : null}
{state && activeTab === "settings" ? <SettingsView state={state} send={send} /> : null}
{state && activeTab === "rules" ? <RulesView state={state} send={send} /> : null}
{state && activeTab === "prompts" ? <PromptsTab prompts={state.prompts?.prompts ?? []} send={send} /> : null}
{activeTab === "doctor" ? (
<DoctorTabWrapper send={send} />
) : null}
</motion.section>
</AnimatePresence>
</main>
</div>
);
}
export default App;