Merge branch 'dev' into prod

This commit is contained in:
2026-06-28 22:09:44 +08:00
12 changed files with 3588 additions and 18 deletions
+291
View File
@@ -0,0 +1,291 @@
"use client"
import { useState, useEffect, Suspense } from "react"
import { useSearchParams, useRouter } from "next/navigation"
import Link from "next/link"
import { useSession } from "@/lib/auth-client"
import {
QrCodeIcon,
CheckCircle2,
Loader2,
AlertCircle,
Gamepad2,
ShieldCheck,
ArrowRight,
} from "lucide-react"
import { motion } from "motion/react"
function PairContent() {
const searchParams = useSearchParams()
const router = useRouter()
const token = searchParams.get("token")
const { data: session, isPending } = useSession()
const [status, setStatus] = useState<"idle" | "confirming" | "success" | "error">("idle")
const [error, setError] = useState<string | null>(null)
const [checkedToken, setCheckedToken] = useState(false)
const [tokenValid, setTokenValid] = useState<boolean | null>(null)
// Validate the token exists on the server before showing the confirm UI
useEffect(() => {
if (!token) {
setCheckedToken(true)
setTokenValid(false)
return
}
let cancelled = false
fetch(`/api/plugin/pair/status/${encodeURIComponent(token)}`)
.then(async (res) => {
if (cancelled) return
const data = await res.json()
if (data.status === "pending") {
setTokenValid(true)
} else if (data.status === "confirmed") {
setTokenValid(false)
setError("This pairing link has already been used.")
} else {
setTokenValid(false)
setError(data.error || "This pairing link is invalid or expired.")
}
})
.catch(() => {
if (!cancelled) {
setTokenValid(false)
setError("Could not verify pairing link.")
}
})
.finally(() => {
if (!cancelled) setCheckedToken(true)
})
return () => {
cancelled = true
}
}, [token])
async function handleConfirm() {
if (!token) return
setStatus("confirming")
setError(null)
try {
const res = await fetch("/api/plugin/pair/confirm", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token }),
})
const data = await res.json()
if (!res.ok) {
setStatus("error")
setError(data.error || "Failed to link plugin.")
return
}
setStatus("success")
} catch {
setStatus("error")
setError("Network error. Please try again.")
}
}
// ── Loading ───────────────────────────────────────────────
if (isPending || !checkedToken) {
return (
<div className="min-h-[60vh] flex items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-text/40" />
</div>
)
}
// ── No token ──────────────────────────────────────────────
if (!token || tokenValid === false) {
return (
<CenterCard>
<AlertCircle className="h-12 w-12 text-red-400 mx-auto mb-4" />
<h1 className="text-xl font-bold text-text mb-2">
Invalid Pairing Link
</h1>
<p className="text-sm text-text/60 mb-6">
{error ||
"This link is missing a token or has expired. Start a new pairing session from the DeckyVault plugin on your Steam Deck."}
</p>
<Link
href="/"
className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-primary text-white text-sm font-medium hover:bg-primary/90 transition-colors"
>
Go Home
</Link>
</CenterCard>
)
}
// ── Not logged in ─────────────────────────────────────────
if (!session) {
const callback = encodeURIComponent(`/pair?token=${token}`)
return (
<CenterCard>
<Gamepad2 className="h-12 w-12 text-primary mx-auto mb-4" />
<h1 className="text-xl font-bold text-text mb-2">
Log in to link your plugin
</h1>
<p className="text-sm text-text/60 mb-6">
You need to be logged in to DeckyVault so we can create an API
key for your account.
</p>
<div className="flex flex-col sm:flex-row gap-3 justify-center">
<Link
href={`/login?callbackUrl=${callback}`}
className="inline-flex items-center justify-center gap-2 px-4 py-2 rounded-lg bg-primary text-white text-sm font-medium hover:bg-primary/90 transition-colors"
>
Log In
<ArrowRight className="h-4 w-4" />
</Link>
<Link
href={`/signup?callbackUrl=${callback}`}
className="inline-flex items-center justify-center gap-2 px-4 py-2 rounded-lg border border-border text-text text-sm font-medium hover:border-primary/40 transition-colors"
>
Create Account
</Link>
</div>
</CenterCard>
)
}
// ── Success ───────────────────────────────────────────────
if (status === "success") {
return (
<CenterCard>
<motion.div
initial={{ scale: 0.8, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
transition={{ type: "spring", stiffness: 200, damping: 15 }}
>
<CheckCircle2 className="h-16 w-16 text-green-400 mx-auto mb-4" />
</motion.div>
<h1 className="text-xl font-bold text-text mb-2">
Plugin Linked!
</h1>
<p className="text-sm text-text/60 mb-6">
Your DeckyVault plugin is now connected to{" "}
<span className="text-text font-medium">{session.user.name}</span>
&apos;s account. An API key named{" "}
<span className="font-mono text-primary">Decky Loader Plugin</span>{" "}
was created. You can close this page and return to your Steam Deck.
</p>
<Link
href="/profile/settings?tab=api-keys"
className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-primary text-white text-sm font-medium hover:bg-primary/90 transition-colors"
>
Manage API Keys
</Link>
</CenterCard>
)
}
// ── Confirm ───────────────────────────────────────────────
return (
<CenterCard>
<div className="flex items-center justify-center gap-3 mb-6">
<div className="flex items-center justify-center w-14 h-14 rounded-xl bg-primary/10 border border-primary/20">
<QrCodeIcon className="h-7 w-7 text-primary" />
</div>
<div className="flex items-center justify-center w-14 h-14 rounded-xl bg-text/5 border border-border">
<Gamepad2 className="h-7 w-7 text-text/60" />
</div>
</div>
<h1 className="text-xl font-bold text-text mb-2 text-center">
Link DeckyVault Plugin
</h1>
<p className="text-sm text-text/60 mb-6 text-center max-w-md">
Confirm to connect the DeckyVault plugin on your Steam Deck to your
account. We&apos;ll create an API key so the plugin can upload
performance entries on your behalf.
</p>
<div className="w-full rounded-xl border border-border bg-text/2 p-4 mb-6">
<div className="flex items-center gap-3">
{session.user.image ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={session.user.image}
alt=""
className="w-10 h-10 rounded-full"
/>
) : (
<div className="w-10 h-10 rounded-full bg-primary/20 flex items-center justify-center text-primary font-medium">
{session.user.name?.[0]?.toUpperCase()}
</div>
)}
<div className="min-w-0">
<p className="text-sm font-medium text-text truncate">
{session.user.name}
</p>
<p className="text-xs text-text/50 truncate">
{session.user.email}
</p>
</div>
</div>
</div>
<div className="w-full flex items-start gap-2 text-xs text-text/50 mb-6">
<ShieldCheck className="h-4 w-4 shrink-0 mt-0.5 text-green-400" />
<span>
An API key (<span className="font-mono">Decky Loader Plugin</span>)
will be created for your account. You can revoke it anytime from
Settings API Keys.
</span>
</div>
{error && (
<div className="w-full text-sm text-red-400 flex items-center gap-2 mb-4 px-3 py-2 rounded-lg bg-red-500/10 border border-red-500/20">
<AlertCircle className="h-4 w-4 shrink-0" />
{error}
</div>
)}
<button
onClick={handleConfirm}
disabled={status === "confirming"}
className="w-full inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg bg-primary text-white text-sm font-medium hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
>
{status === "confirming" ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Linking
</>
) : (
<>
<CheckCircle2 className="h-4 w-4" />
Confirm & Link Plugin
</>
)}
</button>
</CenterCard>
)
}
function CenterCard({ children }: { children: React.ReactNode }) {
return (
<div className="min-h-[80vh] flex items-center justify-center px-4 py-12">
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className="w-full max-w-md flex flex-col items-center rounded-2xl border border-border bg-card p-8"
>
{children}
</motion.div>
</div>
)
}
export default function PairPage() {
return (
<Suspense
fallback={
<div className="min-h-[60vh] flex items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-text/40" />
</div>
}
>
<PairContent />
</Suspense>
)
}
@@ -0,0 +1,12 @@
CREATE TABLE "plugin_pairings" (
"token" text PRIMARY KEY NOT NULL,
"user_id" text,
"api_key_id" text,
"api_key" text,
"status" text DEFAULT 'pending' NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL,
"confirmed_at" timestamp,
"expires_at" timestamp NOT NULL
);
--> statement-breakpoint
CREATE INDEX "plugin_pairings_userId_idx" ON "plugin_pairings" USING btree ("user_id");
File diff suppressed because it is too large Load Diff
+7
View File
@@ -197,6 +197,13 @@
"when": 1782593630361,
"tag": "0027_slimy_stryfe",
"breakpoints": true
},
{
"idx": 28,
"version": "7",
"when": 1782655457218,
"tag": "0028_thin_bloodstrike",
"breakpoints": true
}
]
}
+2
View File
@@ -52,6 +52,7 @@ import { eq } from "drizzle-orm"
import { mobileRoutes } from "@/lib/api/mobile"
import { gamesLookupRoutes } from "@/lib/api/games-lookup"
import { performanceImportRoutes } from "@/lib/api/performance-import"
import { pluginPairingRoutes } from "@/lib/api/plugin-pairing"
const betterAuth = new Elysia({ name: "better-auth" })
.mount(auth.handler)
@@ -245,6 +246,7 @@ export const app = new Elysia({ prefix: "/api" })
.use(screenshotRoutes)
.use(gamesLookupRoutes)
.use(mobileRoutes)
.use(pluginPairingRoutes)
)
// ── Write routes ───────────────────────────────────────────
.group("", (app) =>
+200
View File
@@ -0,0 +1,200 @@
import { Elysia, t } from "elysia"
import { randomBytes } from "node:crypto"
import { db } from "@/lib/db/index"
import { pluginPairing } from "@/lib/db/schema"
import { eq, and, lt } from "drizzle-orm"
import { auth } from "@/lib/auth"
const PAIRING_TTL_MS = 10 * 60 * 1000 // 10 minutes
function generatePairingToken(): string {
return "pair_" + randomBytes(24).toString("hex")
}
/**
* Build the public site origin used in the QR code URL.
* Prefers the configured BETTER_AUTH_URL, falls back to the request origin.
*/
function getSiteOrigin(request: Request): string {
const configured = process.env.BETTER_AUTH_URL
if (configured) return configured.replace(/\/$/, "")
const url = new URL(request.url)
return `${url.protocol}//${url.host}`
}
export const pluginPairingRoutes = new Elysia({
prefix: "/plugin",
detail: { tags: ["Plugin"] },
})
// ── Initiate: plugin requests a pairing token (no auth) ──────
.post(
"/pair/initiate",
async ({ request, set }) => {
const token = generatePairingToken()
const now = new Date()
const expiresAt = new Date(now.getTime() + PAIRING_TTL_MS)
const origin = getSiteOrigin(request)
await db.insert(pluginPairing).values({
token,
status: "pending",
createdAt: now,
expiresAt,
})
return {
token,
qrUrl: `${origin}/pair?token=${token}`,
expiresAt: expiresAt.toISOString(),
}
},
{
detail: {
summary: "Initiate Decky plugin pairing",
description:
"Creates a short-lived pairing token. The returned qrUrl should be shown as a QR code in the plugin for the user to scan with a logged-in phone.",
},
},
)
// ── Status: plugin polls until confirmed (no auth, token-gated) ──
.get(
"/pair/status/:token",
async ({ params, set }) => {
const [row] = await db
.select()
.from(pluginPairing)
.where(eq(pluginPairing.token, params.token))
.limit(1)
if (!row) {
set.status = 404
return { status: "invalid", error: "Pairing session not found" }
}
// Expired and not confirmed
if (row.expiresAt < new Date() && row.status !== "confirmed") {
set.status = 410
return { status: "expired", error: "Pairing session expired" }
}
if (row.status === "confirmed" && row.apiKey) {
// Hand over the plaintext key and clear it from the row so it
// can only be retrieved once.
const apiKey = row.apiKey
await db
.update(pluginPairing)
.set({ apiKey: null })
.where(eq(pluginPairing.token, params.token))
return {
status: "confirmed",
apiKey,
keyName: "Decky Loader Plugin",
}
}
return { status: "pending" }
},
{
detail: {
summary: "Check Decky plugin pairing status",
description:
"Polled by the plugin until the user confirms on their phone. Returns the plaintext API key once confirmed (one-time retrieval).",
},
},
)
// ── Confirm: user on phone confirms pairing (session auth) ────
.post(
"/pair/confirm",
async ({ body, request, set }) => {
const session = await auth.api.getSession({ headers: request.headers })
if (!session) {
set.status = 401
return { error: "You must be logged in to confirm pairing" }
}
const { token } = body
const [row] = await db
.select()
.from(pluginPairing)
.where(eq(pluginPairing.token, token))
.limit(1)
if (!row) {
set.status = 404
return { error: "Pairing session not found" }
}
if (row.expiresAt < new Date()) {
set.status = 410
return { error: "Pairing session expired. Start again on your Deck." }
}
if (row.status === "confirmed") {
set.status = 409
return { error: "This pairing session has already been confirmed" }
}
// Create an API key for this user via Better Auth (server-side).
// name is required by our api-key plugin config (requireName: true).
let created: { key: string; id: string } | null = null
try {
const result = (await auth.api.createApiKey({
body: {
name: "Decky Loader Plugin",
userId: session.user.id,
},
})) as unknown as { key: string; id: string }
created = { key: result.key, id: result.id }
} catch (err) {
console.error("[plugin-pairing] createApiKey failed:", err)
set.status = 500
return { error: "Failed to create API key" }
}
if (!created || !created.key) {
set.status = 500
return { error: "Failed to create API key" }
}
// Link the pairing session to the user + key
await db
.update(pluginPairing)
.set({
userId: session.user.id,
apiKeyId: created.id,
apiKey: created.key,
status: "confirmed",
confirmedAt: new Date(),
})
.where(eq(pluginPairing.token, token))
return {
success: true,
keyName: "Decky Loader Plugin",
}
},
{
body: t.Object({
token: t.String(),
}),
detail: {
summary: "Confirm Decky plugin pairing",
description:
"Called from the /pair page by a logged-in user. Creates an API key for the account and links it to the pairing token so the plugin can retrieve it.",
},
},
)
// ── Cleanup: periodically delete expired pairings ────────────
.post(
"/pair/cleanup",
async () => {
await db
.delete(pluginPairing)
.where(lt(pluginPairing.expiresAt, new Date()))
return { success: true }
},
{
detail: { hide: true },
},
)
+27
View File
@@ -178,3 +178,30 @@ export const apikeyRelations = relations(apikey, ({ one }) => ({
references: [user.id],
}),
}))
// ── Decky plugin pairing ────────────────────────────────────
// Short-lived pairing sessions that let a Steam Deck link to a
// user account by scanning a QR code on a logged-in phone.
export const pluginPairing = pgTable(
"plugin_pairings",
{
token: text("token").primaryKey(),
userId: text("user_id"),
apiKeyId: text("api_key_id"),
// Plaintext API key, only present between confirm and the plugin
// retrieving it. Cleared once the plugin has fetched it.
apiKey: text("api_key"),
status: text("status").default("pending").notNull(),
createdAt: timestamp("created_at").defaultNow().notNull(),
confirmedAt: timestamp("confirmed_at"),
expiresAt: timestamp("expires_at").notNull(),
},
(table) => [index("plugin_pairings_userId_idx").on(table.userId)],
)
export const pluginPairingRelations = relations(pluginPairing, ({ one }) => ({
user: one(user, {
fields: [pluginPairing.userId],
references: [user.id],
}),
}))
+4 -1
View File
@@ -83,10 +83,11 @@
},
"plugins/decky-vault": {
"name": "@deckyvault/plugin",
"version": "0.1.0",
"version": "1.0.0",
"dependencies": {
"@decky/api": "^1.1.3",
"@deckyvault/shared": "workspace:*",
"qrcode.react": "^4.2.0",
"react-icons": "^5.3.0",
"tslib": "^2.7.0",
},
@@ -1669,6 +1670,8 @@
"pvutils": ["pvutils@1.1.5", "", {}, "sha512-KTqnxsgGiQ6ZAzZCVlJH5eOjSnvlyEgx1m8bkRJfOhmGRqfo5KLvmAlACQkrjEtOQ4B7wF9TdSLIs9O90MX9xA=="],
"qrcode.react": ["qrcode.react@4.2.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA=="],
"queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="],
"react": ["react@19.2.6", "", {}, "sha512-sfWGGfavi0xr8Pg0sVsyHMAOziVYKgPLNrS7ig+ivMNb3wbCBw3KxtflsGBAwD3gYQlE/AEZsTLgToRrSCjb0Q=="],
+85 -3
View File
@@ -400,13 +400,29 @@ exec mangohud "$@"
return {"slug": slug, "name": name, "raw": product_name}
async def get_os_version(self) -> str:
"""RPC: Read OS version from /etc/os-release."""
"""RPC: Read OS version from /etc/os-release.
SteamOS only puts 'SteamOS' in PRETTY_NAME, so we build a more
useful string from VERSION_ID (and BUILD_ID) instead."""
try:
pretty = ""
version_id = ""
build_id = ""
with open("/etc/os-release", 'r') as f:
for line in f:
if line.startswith("PRETTY_NAME="):
return line.split("=", 1)[1].strip().strip('"')
return "unknown"
pretty = line.split("=", 1)[1].strip().strip('"')
elif line.startswith("VERSION_ID="):
version_id = line.split("=", 1)[1].strip().strip('"')
elif line.startswith("BUILD_ID="):
build_id = line.split("=", 1)[1].strip().strip('"')
# For SteamOS, combine name + version id for a meaningful label
if version_id:
name = "SteamOS" if (pretty == "SteamOS" or not pretty) else pretty
label = f"{name} {version_id}".strip()
if build_id:
label += f" (build {build_id})"
return label
return pretty or "unknown"
except (IOError, FileNotFoundError):
return "unknown"
@@ -647,3 +663,69 @@ exec mangohud "$@"
}
except Exception as e:
return {"success": False, "error": str(e)}
async def initiate_pair(self, base_url: str = "https://deckyvault.xyz") -> dict:
"""RPC: Start a plugin pairing session. Returns {success, token, qrUrl, expiresAt, error?}.
The qrUrl should be shown as a QR code in the plugin UI."""
import urllib.request
import urllib.error
try:
url = f"{base_url}/api/plugin/pair/initiate"
req = urllib.request.Request(
url,
data=b"{}",
headers={
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; rv:136.0) Gecko/20100101 Firefox/136.0",
"Accept": "application/json",
},
method="POST"
)
context = _get_ssl_context()
with urllib.request.urlopen(req, timeout=10, context=context) as response:
result = json.loads(response.read().decode('utf-8'))
return {
"success": True,
"token": result.get("token", ""),
"qrUrl": result.get("qrUrl", ""),
"expiresAt": result.get("expiresAt", ""),
}
except urllib.error.HTTPError as e:
return {"success": False, "error": f"Server returned status {e.code}"}
except urllib.error.URLError as e:
return {"success": False, "error": f"Network error: {str(e.reason)}"}
except Exception as e:
return {"success": False, "error": str(e)}
async def check_pair_status(self, token: str, base_url: str = "https://deckyvault.xyz") -> dict:
"""RPC: Poll pairing status. Returns {status: 'pending'|'confirmed'|'expired'|'invalid', apiKey?, error?}."""
import urllib.request
import urllib.error
try:
url = f"{base_url}/api/plugin/pair/status/{token}"
req = urllib.request.Request(
url,
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; rv:136.0) Gecko/20100101 Firefox/136.0",
"Accept": "application/json",
},
method="GET"
)
context = _get_ssl_context()
with urllib.request.urlopen(req, timeout=10, context=context) as response:
result = json.loads(response.read().decode('utf-8'))
return {
"status": result.get("status", "pending"),
"apiKey": result.get("apiKey"),
"keyName": result.get("keyName"),
}
except urllib.error.HTTPError as e:
try:
err = json.loads(e.read().decode('utf-8'))
return {"status": err.get("status", "invalid"), "error": err.get("error", f"status {e.code}")}
except Exception:
return {"status": "invalid", "error": f"Server returned status {e.code}"}
except urllib.error.URLError as e:
return {"status": "invalid", "error": f"Network error: {str(e.reason)}"}
except Exception as e:
return {"status": "invalid", "error": str(e)}
+1
View File
@@ -10,6 +10,7 @@
"dependencies": {
"@decky/api": "^1.1.3",
"@deckyvault/shared": "workspace:*",
"qrcode.react": "^4.2.0",
"react-icons": "^5.3.0",
"tslib": "^2.7.0"
},
+222 -12
View File
@@ -1,4 +1,4 @@
import { useEffect, useState } from "react"
import { useEffect, useState, useRef } from "react"
import {
ButtonItem,
PanelSection,
@@ -19,6 +19,8 @@ import {
FaFileExport,
FaFileImport,
FaSearch,
FaQrcode,
FaLink,
} from "react-icons/fa"
import type { RecordingState, SessionData, RecentSession, PluginSettings } from "../lib/store"
import { KNOWN_HARDWARE_SLUGS } from "@deckyvault/shared"
@@ -29,7 +31,10 @@ import {
getMangohudConfig,
exportConfig,
importConfig,
initiatePair,
checkPairStatus,
} from "../lib/api"
import { QRCodeSVG } from "qrcode.react"
import SessionForm from "./session-form"
interface MainPanelProps {
@@ -53,6 +58,34 @@ const HARDWARE_OPTIONS = [
...KNOWN_HARDWARE_SLUGS.map((slug) => ({ label: slug, data: slug })),
]
function SetupStep({ number, title, body }: { number: number; title: string; body: string }) {
return (
<PanelSectionRow>
<div style={{ display: "flex", gap: "10px", padding: "6px 0", alignItems: "flex-start" }}>
<div style={{
flexShrink: 0,
width: "22px",
height: "22px",
borderRadius: "50%",
background: "#1b9bf3",
color: "white",
fontSize: "12px",
fontWeight: 700,
display: "flex",
alignItems: "center",
justifyContent: "center",
}}>
{number}
</div>
<div className={staticClasses.Text} style={{ fontSize: "12px", lineHeight: "1.45", flex: 1 }}>
<div style={{ fontWeight: 600, marginBottom: "2px" }}>{title}</div>
<div style={{ opacity: 0.7 }}>{body}</div>
</div>
</div>
</PanelSectionRow>
)
}
export default function MainPanel({
recordingState,
session,
@@ -86,6 +119,15 @@ export default function MainPanel({
}>({ checked: false, valid: false, message: "" })
const [configStatus, setConfigStatus] = useState<{ message: string; isError: boolean } | null>(null)
// ── Pairing state ───────────────────────────────────────
const [pairState, setPairState] = useState<{
status: "idle" | "starting" | "showing-qr" | "polling" | "linked" | "error"
qrUrl: string
token: string
error: string
}>({ status: "idle", qrUrl: "", token: "", error: "" })
const pairPollRef = useRef<ReturnType<typeof setInterval> | null>(null)
// Timer for recording state
useEffect(() => {
if (recordingState !== "recording") {
@@ -198,6 +240,69 @@ export default function MainPanel({
}
}
// ── Pairing handlers ────────────────────────────────────
function stopPairPolling() {
if (pairPollRef.current) {
clearInterval(pairPollRef.current)
pairPollRef.current = null
}
}
async function handleStartPairing() {
setPairState({ status: "starting", qrUrl: "", token: "", error: "" })
const result = await initiatePair(settings.baseUrl)
if (!result.success || !result.token || !result.qrUrl) {
setPairState({
status: "error",
qrUrl: "",
token: "",
error: result.error || "Could not start pairing.",
})
return
}
setPairState({
status: "showing-qr",
qrUrl: result.qrUrl || "",
token: result.token || "",
error: "",
})
// Begin polling for confirmation
const token = result.token
const baseUrl = settings.baseUrl || "https://deckyvault.xyz"
stopPairPolling()
pairPollRef.current = setInterval(async () => {
const status = await checkPairStatus(token, baseUrl)
if (status.status === "confirmed" && status.apiKey) {
stopPairPolling()
onUpdateSetting("apiKey", status.apiKey)
setPairState({
status: "linked",
qrUrl: result.qrUrl || "",
token,
error: "",
})
} else if (status.status === "expired" || status.status === "invalid") {
stopPairPolling()
setPairState((prev) => ({
...prev,
status: "error",
error: status.error || "Pairing session expired. Try again.",
}))
}
}, 3000)
}
function handleCancelPairing() {
stopPairPolling()
setPairState({ status: "idle", qrUrl: "", token: "", error: "" })
}
// Clean up polling on unmount
useEffect(() => {
return () => stopPairPolling()
}, [])
// ── Stopped state: show the session form ──────────────────────
if (recordingState === "stopped") {
return (
@@ -330,6 +435,111 @@ export default function MainPanel({
)}
</PanelSection>
{/* ── Account ─────────────────────────────────────────── */}
<PanelSection title="Account">
{pairState.status === "idle" && (
<>
<PanelSectionRow>
<div className={staticClasses.Text} style={{ fontSize: "12px", padding: "4px 0", lineHeight: "1.5", opacity: 0.7 }}>
Link this plugin to your DeckyVault account by scanning a QR code with your phone no manual key entry needed.
</div>
</PanelSectionRow>
<PanelSectionRow>
<ButtonItem layout="below" onClick={handleStartPairing}>
<div style={{ display: "flex", alignItems: "center", gap: "8px", justifyContent: "center" }}>
<FaQrcode />
Pair with Phone
</div>
</ButtonItem>
</PanelSectionRow>
</>
)}
{pairState.status === "starting" && (
<PanelSectionRow>
<div className={staticClasses.Text} style={{ padding: "12px 0", textAlign: "center", fontSize: "13px", opacity: 0.7 }}>
Starting pairing session
</div>
</PanelSectionRow>
)}
{(pairState.status === "showing-qr" || pairState.status === "polling") && (
<>
<PanelSectionRow>
<div className={staticClasses.Text} style={{ fontSize: "12px", padding: "4px 0", lineHeight: "1.5", opacity: 0.8 }}>
Scan this code with your phone's camera, then confirm on the page that opens.
</div>
</PanelSectionRow>
<PanelSectionRow>
<div style={{ display: "flex", justifyContent: "center", padding: "12px 0", background: "#fff", borderRadius: "12px" }}>
<QRCodeSVG value={pairState.qrUrl} size={180} level="M" />
</div>
</PanelSectionRow>
<PanelSectionRow>
<div className={staticClasses.Text} style={{ fontSize: "12px", padding: "4px 0", textAlign: "center", opacity: 0.6 }}>
Waiting for confirmation…
</div>
</PanelSectionRow>
<PanelSectionRow>
<ButtonItem layout="below" onClick={handleCancelPairing}>
<div style={{ display: "flex", alignItems: "center", gap: "8px", justifyContent: "center" }}>
<FaTimes />
Cancel
</div>
</ButtonItem>
</PanelSectionRow>
</>
)}
{pairState.status === "linked" && (
<>
<PanelSectionRow>
<div className={staticClasses.Text} style={{ fontSize: "13px", color: "#2ecc71", padding: "4px 0", textAlign: "center" }}>
<FaCheck /> Plugin linked to your account!
</div>
</PanelSectionRow>
<PanelSectionRow>
<div className={staticClasses.Text} style={{ fontSize: "11px", opacity: 0.6, padding: "4px 0", textAlign: "center" }}>
API key saved. You can now upload performance entries.
</div>
</PanelSectionRow>
<PanelSectionRow>
<ButtonItem layout="below" onClick={handleCancelPairing}>
<div style={{ display: "flex", alignItems: "center", gap: "8px", justifyContent: "center" }}>
<FaLink />
Done
</div>
</ButtonItem>
</PanelSectionRow>
</>
)}
{pairState.status === "error" && (
<>
<PanelSectionRow>
<div className={staticClasses.Text} style={{ fontSize: "12px", color: "#e74c3c", padding: "4px 0" }}>
<FaTimes /> {pairState.error}
</div>
</PanelSectionRow>
<PanelSectionRow>
<ButtonItem layout="below" onClick={handleStartPairing}>
<div style={{ display: "flex", alignItems: "center", gap: "8px", justifyContent: "center" }}>
<FaQrcode />
Try Again
</div>
</ButtonItem>
</PanelSectionRow>
<PanelSectionRow>
<ButtonItem layout="below" onClick={handleCancelPairing}>
<div style={{ display: "flex", alignItems: "center", gap: "8px", justifyContent: "center" }}>
Dismiss
</div>
</ButtonItem>
</PanelSectionRow>
</>
)}
</PanelSection>
{/* ── Usage Instructions ──────────────────────────────────── */}
<PanelSection title="Usage Instructions">
<PanelSectionRow>
@@ -458,22 +668,22 @@ export default function MainPanel({
)}
</PanelSection>
{/* ── MangoHud Setup Guide ────────────────────────────────── */}
{/* ── MangoHud Setup Guide ────────────────────────────── */}
<PanelSection title="MangoHud Setup Guide">
<PanelSectionRow>
<div className={staticClasses.Text} style={{ fontSize: "12px", padding: "8px", lineHeight: "1.6" }}>
<strong>Steam Deck (SteamOS):</strong> MangoHud is pre-installed. Add <code>mangohud %command%</code> to your game's Steam launch options (right-click Properties Launch Options).
<div className={staticClasses.Text} style={{ fontSize: "12px", padding: "4px 0 8px 0", lineHeight: "1.5", opacity: 0.7 }}>
Follow these steps once to enable performance logging.
</div>
</PanelSectionRow>
<SetupStep number={1} title="Write MangoHud Config" body="Tap 'Write Config' above. This creates the logging config and a wrapper script automatically." />
<SetupStep number={2} title="Add the Launch Option" body="Right-click your game in Steam Properties Launch Options, and paste the launch option above." />
<SetupStep number={3} title="Launch the Game" body="Start the game from Steam. MangoHud loads automatically using the wrapper script." />
<SetupStep number={4} title="Record While Playing" body="Once in-game, open this panel and press Start Recording. Press Stop when done." />
<PanelSectionRow>
<div className={staticClasses.Text} style={{ fontSize: "12px", padding: "8px", lineHeight: "1.6" }}>
<strong>Other Linux:</strong> Install via <code>sudo apt install mangohud</code> or <code>flatpak install ...VulkanLayer.MangoHud</code>. See{" "}
<a href="https://github.com/flightlessmango/MangoHud" style={{ color: "#66c0f4" }}>github.com/flightlessmango/MangoHud</a>.
</div>
</PanelSectionRow>
<PanelSectionRow>
<div className={staticClasses.Text} style={{ fontSize: "12px", padding: "8px", lineHeight: "1.6" }}>
<strong>Troubleshooting:</strong> Log empty? Check MangoHud is enabled. Not attaching? Add <code>mangohud %command%</code> to launch options explicitly.
<div className={staticClasses.Text} style={{ fontSize: "11px", padding: "10px 0 0 0", lineHeight: "1.5", opacity: 0.5, borderTop: "1px solid rgba(255,255,255,0.08)", marginTop: "8px" }}>
Steam Deck ships with MangoHud pre-installed. On other Linux distros, install it with <span style={{ fontFamily: "monospace", opacity: 0.8 }}>sudo apt install mangohud</span> or via Flatpak.
</div>
</PanelSectionRow>
</PanelSection>
+16
View File
@@ -117,3 +117,19 @@ export const importConfig = callable<[], {
}
error?: string
}>("import_config")
// ── Plugin Pairing ──────────────────────────────────────────
export const initiatePair = callable<[baseUrl?: string], {
success: boolean
token?: string
qrUrl?: string
expiresAt?: string
error?: string
}>("initiate_pair")
export const checkPairStatus = callable<[token: string, baseUrl?: string], {
status: "pending" | "confirmed" | "expired" | "invalid"
apiKey?: string
keyName?: string
error?: string
}>("check_pair_status")