Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(desktop): make LAN WebUI pairing copyable and scannable

vastsac7483744ffff
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 0b7eba89c..b48f67900 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -62,6 +62,7 @@
"lucide-react": "^1.31.0",
"mermaid": "^11.16.1",
"pinyin-pro": "3.29.1",
+ "qrcode-generator": "2.0.4",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"react-i18next": "^15.6.0",
diff --git a/apps/desktop/resources/lan-webui/app.js b/apps/desktop/resources/lan-webui/app.js
index 945d873cc..0765ab097 100644
--- a/apps/desktop/resources/lan-webui/app.js
+++ b/apps/desktop/resources/lan-webui/app.js
@@ -82,7 +82,7 @@
}
if (!response.ok) {
const code = data?.code || "FAILED";
- if (response.status === 401 && path.startsWith("/v1/")) {
+ if (response.status === 401 && path.startsWith("/v1/") && state.me) {
state.me = null;
closeEvents();
showPair();
@@ -111,6 +111,11 @@
else location.hash = hash;
};
window.addEventListener("hashchange", () => {
+ const prefill = takePairingCode();
+ if (prefill && !state.me) {
+ showPair("", prefill);
+ return;
+ }
state.route = parseRoute();
render();
});
@@ -439,11 +444,21 @@
}
// ---------- pairing ----------
- function showPair(message) {
+ function takePairingCode() {
+ if (!location.hash.startsWith("#pair=")) return "";
+ const value = /^#pair=([0-9]{6})$/.exec(location.hash)?.[1] ?? "";
+ history.replaceState(history.state, "", location.pathname + location.search);
+ return value;
+ }
+
+ function showPair(message, prefill = "") {
closeEvents();
- const code = el("input", { id: "pair-code", class: "code", inputmode: "numeric", autocomplete: "one-time-code", maxlength: "6", required: true });
+ const code = el("input", {
+ id: "pair-code", class: "code", inputmode: "numeric", autocomplete: "one-time-code",
+ maxlength: "32", required: true, value: prefill, "aria-describedby": "pair-status",
+ });
const label = el("input", { id: "pair-label", maxlength: "60", value: /iPhone|iPad|Android/.exec(navigator.userAgent)?.[0] || "Browser" });
- const status = el("p", { class: "hint", role: "status", text: message || "" });
+ const status = el("p", { id: "pair-status", class: "hint", role: "status", text: message || "" });
const submit = el("button", { type: "submit", class: "primary", text: t("pairSubmit") });
const form = el("form", { class: "pair" }, [
el("h1", { text: t("pairTitle") }),
@@ -454,11 +469,24 @@
]);
form.addEventListener("submit", async (event) => {
event.preventDefault();
+ if (submit.disabled) return;
+ const value = code.value.normalize("NFKC").replace(/[\s-]+/g, "");
+ if (!/^[0-9]{6}$/.test(value)) {
+ status.textContent = t("pairFormat");
+ code.focus();
+ return;
+ }
+ code.value = value;
submit.disabled = true;
status.textContent = t("pairConnecting");
try {
- await api("POST", "/pair", { code: code.value.trim(), label: label.value.trim() });
- await start();
+ const result = await api("POST", "/pair", { code: value, label: label.value.trim() });
+ if (result?.state !== "paired") {
+ status.textContent = t("pairRestart");
+ submit.disabled = false;
+ return;
+ }
+ await start("", true);
} catch (error) {
submit.disabled = false;
const codeName = error instanceof ApiError ? error.code : "FAILED";
@@ -466,10 +494,10 @@
}
});
show(form);
- code.focus();
+ if (prefill) submit.focus();
+ else code.focus();
}
-
async function signOut() {
try {
await api("POST", "/v1/logout", {});
@@ -480,12 +508,13 @@
showPair();
}
- async function start() {
+ async function start(prefill = "", justPaired = false) {
try {
state.me = await api("GET", "/v1/me");
} catch (error) {
- if (!(error instanceof ApiError && error.code === "UNAUTHORIZED")) showPair(errorText(error instanceof ApiError ? error.code : "FAILED"));
- else showPair();
+ const code = error instanceof ApiError ? error.code : "FAILED";
+ const message = code === "UNAUTHORIZED" ? justPaired ? t("pairCookieBlocked") : "" : errorText(code);
+ showPair(message, prefill);
return;
}
state.route = parseRoute();
@@ -494,5 +523,5 @@
}
document.title = t("appTitle");
- void start();
+ void start(takePairingCode());
})();
diff --git a/apps/desktop/resources/lan-webui/locale.js b/apps/desktop/resources/lan-webui/locale.js
index c13d17dc7..23b8b5124 100644
--- a/apps/desktop/resources/lan-webui/locale.js
+++ b/apps/desktop/resources/lan-webui/locale.js
@@ -8,6 +8,9 @@ window.LAN_LOCALES = {
deviceLabel: "Device name",
pairSubmit: "Pair",
pairConnecting: "Connecting…",
+ pairFormat: "Enter the six digits shown on the computer.",
+ pairRestart: "This computer is running an older pairing service. Restart PI-Desktop and try again with a new code.",
+ pairCookieBlocked: "The code was accepted, but the browser did not save the sign-in. Allow cookies for this site and use a new code.",
pairFailed: "That code is wrong or expired. Show a new code on the computer.",
pairClosed: "Show a pairing code on the computer first.",
projects: "Projects",
@@ -72,6 +75,9 @@ window.LAN_LOCALES = {
deviceLabel: "设备名称",
pairSubmit: "配对",
pairConnecting: "正在连接…",
+ pairFormat: "请输入电脑上显示的六位数字。",
+ pairRestart: "电脑仍在运行旧版配对服务。请完整退出并重启 PI-Desktop,再使用新码。",
+ pairCookieBlocked: "配对码已验证,但浏览器没有保存登录状态。请允许此站点使用 Cookie,再使用新码。",
pairFailed: "配对码错误或已过期,请在电脑上重新显示配对码。",
pairClosed: "请先在电脑上显示配对码。",
projects: "项目",
diff --git a/apps/desktop/src/features/lan-webui/LanPairDialog.tsx b/apps/desktop/src/features/lan-webui/LanPairDialog.tsx
index e29ef1661..2db25e1df 100644
--- a/apps/desktop/src/features/lan-webui/LanPairDialog.tsx
+++ b/apps/desktop/src/features/lan-webui/LanPairDialog.tsx
@@ -1,12 +1,13 @@
-import { useEffect, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import type { LanAdminView } from "@pi-desktop/shared";
import { Button, cx } from "../../components/ui";
import { IconCheck, IconCopy, IconRefresh, IconSmartphone } from "../../components/icons";
import { LanDialog } from "./LanDialog";
+import { pairingQr } from "./pairing-qr";
import { useCountdown } from "./use-lan-webui-admin";
-export function CopyButton({ text }: { text: string }) {
+export function CopyButton({ text, label }: { text: string; label?: string }) {
const { t } = useTranslation("lan");
const [feedback, setFeedback] = useState<"copied" | "copyFailed" | null>(null);
useEffect(() => {
@@ -30,7 +31,7 @@ export function CopyButton({ text }: { text: string }) {
}}
>
{feedback === "copied" ? <IconCheck size={14} aria-hidden="true" /> : <IconCopy size={14} aria-hidden="true" />}
- {t(feedback ?? "copy")}
+ {feedback ? t(feedback) : label ?? t("copy")}
</Button>
);
}
@@ -46,6 +47,7 @@ export function LanPairDialog({ origin, code, busy, error, issueCode, onClose }:
const { t } = useTranslation("lan");
const seconds = useCountdown(code?.expiresAt);
const value = code && !busy && seconds > 0 ? code.value : null;
+ const qr = useMemo(() => value ? pairingQr(origin, value) : null, [origin, value]);
const digits = (value ?? "······").split("");
return (
@@ -63,37 +65,55 @@ export function LanPairDialog({ origin, code, busy, error, issueCode, onClose }:
</p>
) : null}
>
- <ol className="lan-pair-steps" role="list">
- <li className="lan-pair-step">
- <span className="lan-pair-step-number" aria-hidden="true">1</span>
- <div className="lan-pair-step-body">
- <p className="lan-pair-step-title">{t("pairStepOpen")}</p>
- <div className="lan-pair-url">
- <code className="lan-pair-url-text">{origin}</code>
- <CopyButton text={origin} />
- </div>
+ <div className="lan-pair-content">
+ {qr ? (
+ <div className="lan-pair-scan">
+ <svg
+ className="lan-pair-qr"
+ role="img"
+ aria-label={t("pairQrLabel")}
+ viewBox={`0 0 ${qr.size} ${qr.size}`}
+ shapeRendering="crispEdges"
+ >
+ <rect width={qr.size} height={qr.size} />
+ <path d={qr.path} />
+ </svg>
+ <p>{t("pairScan")}</p>
</div>
- </li>
- <li className="lan-pair-step">
- <span className="lan-pair-step-number" aria-hidden="true">2</span>
- <div className="lan-pair-step-body">
- <p className="lan-pair-step-title">{t("pairStepCode")}</p>
- <span className="sr-only" aria-live="polite">{value ? digits.join(" ") : ""}</span>
- <div className={cx("lan-code", !value && "is-expired")} aria-hidden="true">
- {digits.map((digit, index) => <span key={index} className="lan-code-digit">{digit}</span>)}
+ ) : null}
+ <ol className="lan-pair-steps" role="list">
+ <li className="lan-pair-step">
+ <span className="lan-pair-step-number" aria-hidden="true">1</span>
+ <div className="lan-pair-step-body">
+ <p className="lan-pair-step-title">{t("pairStepOpen")}</p>
+ <div className="lan-pair-url">
+ <code className="lan-pair-url-text">{origin}</code>
+ <CopyButton text={origin} />
+ </div>
</div>
- <div className="lan-code-meta">
- {value ? <span>{t("codeExpiresIn", { seconds })}</span> : (
- <span role="status">{busy ? t("codeLoading") : !error ? t("codeExpired") : null}</span>
- )}
- <Button type="button" size="sm" variant="ghost" aria-disabled={busy || undefined} onClick={busy ? undefined : issueCode}>
- <IconRefresh size={14} aria-hidden="true" />
- {t("newCode")}
- </Button>
+ </li>
+ <li className="lan-pair-step">
+ <span className="lan-pair-step-number" aria-hidden="true">2</span>
+ <div className="lan-pair-step-body">
+ <p className="lan-pair-step-title">{t("pairStepCode")}</p>
+ <span className="sr-only" aria-live="polite">{value ? digits.join(" ") : ""}</span>
+ <div className={cx("lan-code", !value && "is-expired")} aria-hidden="true">
+ {digits.map((digit, index) => <span key={index} className="lan-code-digit">{digit}</span>)}
+ </div>
+ <div className="lan-code-meta">
+ {value ? <span>{t("codeExpiresIn", { seconds })}</span> : (
+ <span role="status">{busy ? t("codeLoading") : !error ? t("codeExpired") : null}</span>
+ )}
+ {value ? <CopyButton key={value} text={value} label={t("copyCode")} /> : null}
+ <Button type="button" size="sm" variant="ghost" aria-disabled={busy || undefined} onClick={busy ? undefined : issueCode}>
+ <IconRefresh size={14} aria-hidden="true" />
+ {t("newCode")}
+ </Button>
+ </div>
</div>
- </div>
- </li>
- </ol>
+ </li>
+ </ol>
+ </div>
</LanDialog>
);
}
diff --git a/apps/desktop/src/features/lan-webui/pairing-qr.ts b/apps/desktop/src/features/lan-webui/pairing-qr.ts
new file mode 100644
index 000000000..d25afb949
--- /dev/null
+++ b/apps/desktop/src/features/lan-webui/pairing-qr.ts
@@ -0,0 +1,21 @@
+import qrcode from "qrcode-generator";
+
+export function pairingQr(origin: string, code: string) {
+ const url = new URL(origin);
+ // Loopback points at the device scanning the code, not at this computer.
+ if (url.hostname === "127.0.0.1") return null;
+ // Fragments stay in the browser; the HTTP request does not contain the code.
+ url.hash = `pair=${code}`;
+ const qr = qrcode(0, "M");
+ qr.addData(url.toString());
+ qr.make();
+ const count = qr.getModuleCount();
+ const quietZone = 4;
+ const path: string[] = [];
+ for (let row = 0; row < count; row++) {
+ for (let col = 0; col < count; col++) {
+ if (qr.isDark(row, col)) path.push(`M${col + quietZone} ${row + quietZone}h1v1h-1z`);
+ }
+ }
+ return { size: count + quietZone * 2, path: path.join("") };
+}
diff --git a/apps/desktop/src/locales/lan.ts b/apps/desktop/src/locales/lan.ts
index d0975c9d0..354569b4b 100644
--- a/apps/desktop/src/locales/lan.ts
+++ b/apps/desktop/src/locales/lan.ts
@@ -17,6 +17,7 @@ export const lanEn = {
address: "Address",
addressHint: "Open this address in the browser on your phone.",
copy: "Copy",
+ copyCode: "Copy code",
copied: "Copied",
copyFailed: "Couldn't copy",
devices: "Devices",
@@ -25,6 +26,8 @@ export const lanEn = {
remove: "Remove",
activeAt: "Active {{time}}",
pairTitle: "Add a device",
+ pairScan: "Scan with your phone camera",
+ pairQrLabel: "QR code for this device pairing",
pairDescription: "This code lets a device view and change local projects and conversations, including temporary ones.",
pairStepOpen: "On the device, open",
pairStepCode: "Enter this pairing code",
@@ -61,6 +64,7 @@ export const lanZh: typeof lanEn = {
address: "访问地址",
addressHint: "在手机浏览器中打开这个地址。",
copy: "复制",
+ copyCode: "复制配对码",
copied: "已复制",
copyFailed: "复制失败",
devices: "设备",
@@ -69,6 +73,8 @@ export const lanZh: typeof lanEn = {
remove: "移除",
activeAt: "{{time}}活跃",
pairTitle: "添加设备",
+ pairScan: "用手机相机扫码",
+ pairQrLabel: "设备配对二维码",
pairDescription: "持有此码的设备可直接查看并操作本机项目及临时会话。",
pairStepOpen: "在设备上打开",
pairStepCode: "输入配对码",
diff --git a/apps/desktop/src/styles/lan-webui.css b/apps/desktop/src/styles/lan-webui.css
index ab66e73af..b2b1547b5 100644
--- a/apps/desktop/src/styles/lan-webui.css
+++ b/apps/desktop/src/styles/lan-webui.css
@@ -216,6 +216,52 @@
border-top: 1px solid var(--ds-border-subtle);
}
+.lan-pair-content {
+ display: grid;
+ align-items: start;
+ gap: 16px;
+}
+
+.lan-pair-scan {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 12px;
+ border-radius: var(--radius-md);
+ background: var(--ds-tile);
+ color: var(--ds-text-primary);
+ font-size: var(--text-sm-plus);
+}
+
+.lan-pair-scan p {
+ margin: 0;
+}
+
+.lan-pair-qr {
+ display: block;
+ width: 112px;
+ aspect-ratio: 1;
+ max-width: 100%;
+ flex: 0 0 auto;
+}
+
+/* A fixed light quiet zone keeps the code readable in both themes. */
+.lan-pair-qr rect { fill: var(--ds-qr-background); }
+.lan-pair-qr path { fill: var(--ds-qr-foreground); }
+
+@media (min-width: 560px) {
+ .lan-pair-content:has(> .lan-pair-scan) {
+ grid-template-columns: 160px minmax(0, 1fr);
+ }
+
+ .lan-pair-scan {
+ flex-direction: column;
+ text-align: center;
+ }
+
+ .lan-pair-qr { width: 136px; }
+}
+
.lan-pair-steps {
display: grid;
gap: 20px;
diff --git a/apps/desktop/src/styles/tokens.css b/apps/desktop/src/styles/tokens.css
index 6d5e63d47..e5501a206 100644
--- a/apps/desktop/src/styles/tokens.css
+++ b/apps/desktop/src/styles/tokens.css
@@ -105,6 +105,9 @@
--ds-accent-soft: var(--gray-300);
/* Focus rings / resize affordances. Tied to the accent so themes stay monochrome. */
--ds-focus: var(--ds-accent);
+ /* Cameras need the same dark modules on a light background in both themes. */
+ --ds-qr-background: var(--gray-0);
+ --ds-qr-foreground: var(--gray-1000);
/* Settings fields and shared inset searches keep their built-in tones. */
--ds-settings-field-bg: #212121;
--ds-settings-nav-active: color-mix(in oklab, var(--gray-0) 10%, transparent);
diff --git a/apps/desktop/test/lan-webui-browser-user-path.test.mjs b/apps/desktop/test/lan-webui-browser-user-path.test.mjs
index 1d951bb1c..e5fb2ecda 100644
--- a/apps/desktop/test/lan-webui-browser-user-path.test.mjs
+++ b/apps/desktop/test/lan-webui-browser-user-path.test.mjs
@@ -37,8 +37,14 @@ const journey = String.raw`(async () => {
// Pair with the code shown on Desktop.
const code = await wait(() => document.getElementById("pair-code"), "pair form");
- code.value = window.__code;
- document.querySelector(".pair button[type=submit]").click();
+ code.value = "123";
+ const form = document.querySelector(".pair");
+ const submit = form.querySelector("button[type=submit]");
+ submit.click();
+ await wait(() => /six digits|六位数字/.test(document.getElementById("pair-status").textContent), "client input validation");
+ code.value = Array.from(window.__code, (digit) => String.fromCharCode(digit.charCodeAt(0) + 0xfee0)).join(" ");
+ submit.click();
+ form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
// Redeeming the code connects immediately, without a second Desktop action.
await wait(() => rowByTitle("Alpha"), "projects");
@@ -88,16 +94,19 @@ const journey = String.raw`(async () => {
document.querySelector("main > button.link").click();
await wait(() => document.getElementById("pair-code"), "sign-out returns to pairing");
result.polledApproval = performance.getEntriesByType("resource").some((entry) => new URL(entry.name).pathname === "/pair/status");
+ result.pairRequests = performance.getEntriesByType("resource").filter((entry) => new URL(entry.name).pathname === "/pair").length;
return JSON.stringify(result);
})()`;
-test("a phone pairs by code, uses projects and temporary conversations, and signs out", { timeout: 60_000 }, async (t) => {
+async function runPhone(t, script, { scan = false, blockCookie = false } = {}) {
const { electronBinary } = resolveElectronBinary();
const fake = desktop();
const server = createLanServer({ handler: fake.workspace, assets: await assets() });
const { port } = await server.start("127.0.0.1", 0);
server.issueCode();
const code = server.code().value;
+ const origin = `http://127.0.0.1:${port}`;
+ const entry = `${origin}/${scan ? `#pair=${code}` : ""}`;
const temp = await mkdtemp(join(process.env.PI_SCRATCH_DIR ?? tmpdir(), "lan-webui-ui-"));
t.after(async () => {
await server.stop();
@@ -111,9 +120,15 @@ app.setPath("userData", path.join(__dirname, "profile"));
app.whenReady().then(async () => {
const window = new BrowserWindow({ show: false, width: 390, height: 844, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
try {
- await window.loadURL(${JSON.stringify(`http://127.0.0.1:${port}/`)});
- await window.webContents.executeJavaScript("window.__code = '${code}';");
- const output = await window.webContents.executeJavaScript(${JSON.stringify(journey)});
+ if (${blockCookie}) {
+ window.webContents.session.webRequest.onHeadersReceived({ urls: [${JSON.stringify(`${origin}/pair`)}] }, (details, reply) => {
+ const responseHeaders = Object.fromEntries(Object.entries(details.responseHeaders ?? {}).filter(([key]) => key.toLowerCase() !== "set-cookie"));
+ reply({ responseHeaders });
+ });
+ }
+ await window.loadURL(${JSON.stringify(entry)});
+ await window.webContents.executeJavaScript(${JSON.stringify(`window.__code = ${JSON.stringify(code)};`)});
+ const output = await window.webContents.executeJavaScript(${JSON.stringify(script)});
process.stdout.write("RESULT " + output + "\\n");
app.exit(0);
} catch (error) {
@@ -133,7 +148,11 @@ app.whenReady().then(async () => {
assert.equal(exitCode, 0, stderr);
const line = stdout.split("\n").find((entry) => entry.startsWith("RESULT "));
assert.ok(line, stdout + stderr);
- const result = JSON.parse(line.slice(7));
+ return { result: JSON.parse(line.slice(7)), fake, server };
+}
+
+test("a phone pairs with a formatted paste, uses projects and conversations, and signs out", { timeout: 60_000 }, async (t) => {
+ const { result, fake, server } = await runPhone(t, journey);
assert.match(result.projects[0], /^(Temporary conversations|临时会话)$/);
assert.deepEqual(result.projects.slice(1), ["Alpha", "Beta"]);
@@ -152,5 +171,73 @@ app.whenReady().then(async () => {
assert.equal(result.smallTargets, 0);
assert.equal(result.backHash, "#/p/g-a");
assert.equal(result.polledApproval, false);
+ assert.equal(result.pairRequests, 1, "invalid input and a duplicate submit did not reach the listener");
assert.equal(server.devices().length, 0, "browser sign-out revoked its device");
});
+
+const scanJourney = String.raw`(async () => {
+ const field = () => document.getElementById("pair-code");
+ async function wait(check) {
+ const deadline = performance.now() + 5000;
+ while (performance.now() < deadline) {
+ if (check()) return;
+ await new Promise(requestAnimationFrame);
+ }
+ throw new Error("Scanned code did not advance the pairing flow");
+ }
+ await wait(() => field()?.value === window.__code && !location.hash);
+ const other = window.__code === "000000" ? "111111" : "000000";
+ location.hash = "#pair=" + other;
+ await wait(() => field()?.value === other && !location.hash);
+ location.hash = "#pair=" + window.__code;
+ await wait(() => field()?.value === window.__code && !location.hash);
+ const submittedEarly = performance.getEntriesByType("resource").some((entry) => new URL(entry.name).pathname === "/pair");
+ document.querySelector('.pair button[type="submit"]').click();
+ await wait(() => [...document.querySelectorAll(".row-title")].some((row) => row.textContent === "Alpha"));
+ return JSON.stringify({ submittedEarly, fragment: location.hash });
+})()`;
+
+test("a scanned fragment prefills and clears without redeeming the code until submit", { timeout: 60_000 }, async (t) => {
+ const { result, server } = await runPhone(t, scanJourney, { scan: true });
+ assert.deepEqual(result, { submittedEarly: false, fragment: "" });
+ assert.equal(server.devices().length, 1);
+});
+
+const rejectedCookieJourney = String.raw`(async () => {
+ const deadline = performance.now() + 5000;
+ const input = () => document.getElementById("pair-code");
+ while (!input()?.value && performance.now() < deadline) await new Promise(requestAnimationFrame);
+ document.querySelector('.pair button[type="submit"]').click();
+ while (performance.now() < deadline) {
+ const status = document.getElementById("pair-status")?.textContent;
+ if (/cookies|Cookie/.test(status ?? "")) return JSON.stringify({ prompted: true, cleared: input().value === "" });
+ await new Promise(requestAnimationFrame);
+ }
+ throw new Error("A rejected session cookie did not show an actionable pairing error");
+})()`;
+
+test("a browser that rejects the session cookie gets an actionable pairing error", { timeout: 60_000 }, async (t) => {
+ const { result, server } = await runPhone(t, rejectedCookieJourney, { scan: true, blockCookie: true });
+ assert.deepEqual(result, { prompted: true, cleared: true });
+ assert.equal(server.code(), null, "the one-time code was accepted, not retried");
+});
+
+test("a legacy pending response tells the user to restart the desktop", { timeout: 60_000 }, async (t) => {
+ const script = String.raw`(async () => {
+ const field = () => document.getElementById("pair-code");
+ const deadline = performance.now() + 5000;
+ while (!field() && performance.now() < deadline) await new Promise(requestAnimationFrame);
+ const request = window.fetch.bind(window);
+ window.fetch = (path, options) => path === "/pair"
+ ? Promise.resolve(Response.json({ state: "pending" })) : request(path, options);
+ field().value = window.__code;
+ document.querySelector('.pair button[type="submit"]').click();
+ while (performance.now() < deadline) {
+ const status = document.getElementById("pair-status")?.textContent ?? "";
+ if (/Restart PI-Desktop|重启 PI-Desktop/.test(status)) return JSON.stringify(true);
+ await new Promise(requestAnimationFrame);
+ }
+ throw new Error("Missing restart guidance for the old pairing response");
+ })()`;
+ assert.equal((await runPhone(t, script)).result, true);
+});
diff --git a/apps/desktop/test/lan-webui-settings-user-path.test.mjs b/apps/desktop/test/lan-webui-settings-user-path.test.mjs
index f0d0e09b2..b8d4d318c 100644
--- a/apps/desktop/test/lan-webui-settings-user-path.test.mjs
+++ b/apps/desktop/test/lan-webui-settings-user-path.test.mjs
@@ -66,7 +66,7 @@ window.piDesktop = {
break;
case "issueCode":
issueCount++;
- view.code = { value: ["000012", "134209", "512309"][issueCount - 1], expiresAt: Date.now() + (issueCount === 1 ? -1000 : 300_000) };
+ view.code = { value: ["000012", "034209", "512309"][issueCount - 1], expiresAt: Date.now() + (issueCount === 1 ? -1000 : 300_000) };
break;
case "revoke":
view.devices = view.devices.filter((item) => item.id !== action.id);
@@ -147,8 +147,14 @@ window.lanSettingsProbe = async () => {
await wait(() => title() === lanEn.pairTitle && dialog().textContent.includes(lanEn.codeExpired), "expired pairing code");
check(fitsDialog(), "pairing fits a narrow dark window");
check(dialog().textContent.includes(lanEn.pairDescription), "the code dialog discloses its access");
+ check(!q(".lan-pair-qr") && !button(lanEn.copyCode), "expired codes cannot be copied or scanned");
click(button(lanEn.newCode, dialog()));
- await wait(() => q(".lan-code")?.textContent === "134209", "replacement code");
+ await wait(() => q(".lan-code")?.textContent === "034209" && q(".lan-pair-qr"), "replacement code and QR");
+ const qr = q(".lan-pair-qr");
+ const firstPath = q("path", qr)?.getAttribute("d");
+ check(firstPath && qr.getAttribute("aria-label") === lanEn.pairQrLabel && fitsDialog(), "scannable code fits the dark window");
+ click(button(lanEn.copyCode, dialog()));
+ await wait(() => button(lanEn.copied, dialog()), "code clipboard feedback");
await wait(() => dialog().contains(document.activeElement), "focus in pair dialog");
press("Escape");
await wait(() => !dialog() && document.activeElement === button(lanEn.addDevice), "Escape returns focus");
@@ -156,6 +162,8 @@ window.lanSettingsProbe = async () => {
click(button(lanEn.addDevice));
await wait(() => q(".lan-code")?.textContent === "512309", "fresh code when opened again");
check(fitsDialog() && !dialog().querySelector('input[type="checkbox"]'), "pairing fits the light window without permission controls");
+ const nextPath = q(".lan-pair-qr path")?.getAttribute("d");
+ check(nextPath && nextPath !== firstPath, "the QR changes with the new code");
q(".lan-dialog-close", dialog()).focus();
check(!press("Tab", true) && document.activeElement === button(lanEn.newCode, dialog()), "Shift+Tab stays in the pairing dialog");
view.devices.push({ id: "device", label: "iPhone", lastActiveAt: Date.now() });
@@ -227,7 +235,7 @@ app.whenReady().then(async () => {
{ kind: "issueCode" }, { kind: "issueCode" }, { kind: "issueCode" },
{ kind: "revoke", id: "device" }, { kind: "stop" },
],
- copied: ["http://192.168.1.20:38180"],
+ copied: ["http://192.168.1.20:38180", "034209"],
remainingListeners: 0,
});
});
diff --git a/docs/adr/lan-webui-code-pairing.md b/docs/adr/lan-webui-code-pairing.md
index c9802ab15..6882b23c7 100644
--- a/docs/adr/lan-webui-code-pairing.md
+++ b/docs/adr/lan-webui-code-pairing.md
@@ -24,6 +24,10 @@ and CSRF validation, and memory-only credentials. Pairing does not issue an
owner or SSH principal or grant generic IPC. Resource eligibility, the remote
`ask` ceiling, and Desktop-only tool and plan approvals are unchanged.
+The optional QR encodes only the bound address and the one-time code in a URL
+fragment. The browser removes the fragment locally and requires an explicit
+submit, so loading or previewing the scanned URL cannot consume the code.
+
## Consequences
Anyone who obtains an active code can pair without another prompt. Display it
diff --git a/docs/spec/01-product/03-lan-webui-mvp.md b/docs/spec/01-product/03-lan-webui-mvp.md
index 9b232804d..cb733f706 100644
--- a/docs/spec/01-product/03-lan-webui-mvp.md
+++ b/docs/spec/01-product/03-lan-webui-mvp.md
@@ -44,13 +44,16 @@ numbers refer to the [WebUI acceptance catalog](../06-delivery/e2e/live-and-remo
rebinding) or whose `Origin` is foreign, requires a CSRF token on every
authenticated mutation, and serves a restrictive CSP. Adding HTTPS later must
not change the browser API.
-3. Once the listener is on, **Add device** shows the address and a one-time
- 6-digit code. The dialog discloses that the code grants access to the local
- WebUI, including temporary conversations and supported changes. A valid
+3. Once the listener is on, **Add device** shows the address and a copyable
+ one-time 6-digit code. For a LAN address, Desktop generates a QR code locally.
+ Scanning opens the browser with the code prefilled, not submitted. The
+ dialog discloses access to local and temporary conversations and supported changes. A valid
code immediately issues the device cookie; no additional Desktop approval
or permission configuration is required. No project data is sent before
pairing. Each code lasts five minutes at most and is invalidated after use
- or five failed attempts. Only Desktop can generate a code. A QR code is deferred.
+ or five failed attempts. Only Desktop can generate a code. The browser accepts
+ pasted digits with spaces, dashes or full-width forms and does not consume
+ attempts for malformed input or duplicate submits while pairing.
4. Devices shows the label and last activity of each paired browser. **Remove**
and browser sign-out invalidate that device's cookie and streams. Turning
off closes the listener and signs out every device; a subsequent start
@@ -216,7 +219,9 @@ Use a Host-issued `HttpOnly`, host-only, `SameSite=Strict` session cookie
(12 hours; no `Secure` flag because the MVP is HTTP), exact Host/Origin
validation, and CSRF tokens for authenticated mutations. Device credentials live
only in Desktop memory: stopping the service or quitting Desktop signs every
-device out. No credentials in URLs, local storage or logs. Serve assets locally
+device out. No session credentials in URLs, local storage or logs. A QR may
+include the one-time code in a fragment; the browser removes it before sending
+requests, and submits it only in the pairing POST body. Serve assets locally
under a restrictive CSP; never cache authenticated data (`no-store`). Logs
record only start/stop and failure codes, not prompts, history, codes or
cookies. Bound request bodies (300 KiB), prompts (256 KiB), pages (50 items)
@@ -278,7 +283,7 @@ settings) and `apps/desktop/src/features/lan-webui/lan-catalog-sync.ts`
| Area | Delivered | Not yet |
|---|---|---|
-| W01 | Off by default; interface + port; direct one-time-code pairing; remove devices; stop signs everyone out | QR code; HTTPS (deliberately deferred) |
+| W01 | Off by default; interface + port; one-time-code pairing with copy and QR; remove devices; stop signs everyone out | HTTPS (deliberately deferred) |
| W02/W03 | Local projects and temporary conversations; search; archived filter; rename, pin, archive/restore with revision conflicts; new session in the explicit project | Reuse of an existing empty session |
| W04 | Paged history; live assistant text; send; queue; cancel queued; stop the named turn; “waiting on Desktop” for approvals and input | Answering ordinary questions from the browser; model label is the raw model id |
| W05 | Idempotency keys for every mutation; SSE change notices with refetch; reconnect banner | Cursor-based replay (refetch is used instead) |
diff --git a/docs/spec/06-delivery/e2e/live-and-remote.md b/docs/spec/06-delivery/e2e/live-and-remote.md
index 0fc491ba0..ddd4ff458 100644
--- a/docs/spec/06-delivery/e2e/live-and-remote.md
+++ b/docs/spec/06-delivery/e2e/live-and-remote.md
@@ -762,17 +762,17 @@ user's running instance.
- **Preconditions:** Fresh Desktop profile with projects A and B; a real phone
on the selected private LAN. Repeat on iOS Safari and Android Chrome.
-- **Steps:** Choose the interface and start. Open **Add device**, copy the shown
- `http://` address, and enter the displayed code on the phone. Do not click
- another Desktop control. Open a local project and a temporary conversation,
- then add project C on Desktop. Test an expired code, a second redemption,
- five wrong attempts and the keyboard flow. Stop, quit and relaunch Desktop.
+- **Steps:** Start on a private interface. Open **Add device**, copy the address
+ and code, then try pasting six digits with spaces or full-width digits. Scan
+ a fresh QR with the phone camera and submit the prefilled code. Open a project
+ and a temporary conversation; add project C on Desktop. Repeat with cookies
+ blocked, wrong and expired codes, and rapid duplicate submit. Stop and restart.
- **Expected:** No listener by default and no project data before pairing.
- The valid code immediately connects the phone and lists the device on
- Desktop. No approval or per-device grants are required; A, B, C and
- temporary conversations are available. Closing the tab does not sign out.
- Invalid, expired or redeemed codes fail. Stopping invalidates credentials and
- releases the port; restarting requires pairing again.
+ A scan opens the bound origin and clears its fragment without submitting;
+ a valid code connects on one submit. The desktop lists the device without
+ extra approval. A, B, C and temporary conversations are available. Invalid,
+ expired or redeemed codes fail, and blocked cookies show a specific error.
+ Stopping invalidates credentials and releases the port; restart requires pairing.
- **Acceptance:** A, E; W01, W06.
### E2E-270: Organize projects and sessions without stealing navigation
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 226c1fee6..3372180a1 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -310,6 +310,9 @@ importers:
pinyin-pro:
specifier: 3.29.1
version: 3.29.1
+ qrcode-generator:
+ specifier: 2.0.4
+ version: 2.0.4
react:
specifier: ^19.2.8
version: 19.2.8
@@ -3950,6 +3953,9 @@ packages:
resolution: {integrity: sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==}
engines: {node: '>=16.0.0'}
+ resolution: {integrity: sha512-mZSiP6RnbHl4xL2Ap5HfkjLnmxfKcPWpWe/c+5XxCuetEenqmNFf1FH/ftXPCtFG5/TDobjsjz6sSNL0Sr8Z9g==}
+
resolution: {integrity: sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==}
engines: {node: '>=10'}
@@ -8535,6 +8541,8 @@ snapshots:
+