diff --git a/docs/architecture/web-pandar-print-host.md b/docs/architecture/web-pandar-print-host.md
index f54fdcc322..114a20853b 100644
--- a/docs/architecture/web-pandar-print-host.md
+++ b/docs/architecture/web-pandar-print-host.md
@@ -1,4 +1,4 @@
-# Web print host: send a sliced plate to Pandar
+# Web print host: Pandar Cloud sign-in, Devices tab and sending a sliced plate
## Source boundary
@@ -22,8 +22,13 @@ Plate sliced file (`libslic3r`, the rewrite boundary):
Print host UI (GUI, ported only as browser behaviour):
-- `PhysicalPrinterDialog` (`src/slic3r/GUI/PhysicalPrinterDialog.cpp`) stores a host type, the
- host address (`print_host`) and the API key (`printhost_apikey`).
+- `GUI_App::request_login` and `ShowUserLogin` (`src/slic3r/GUI/GUI_App.cpp:5135`, `:5363`) open the
+ cloud sign-in WebView. `GUI_App::request_user_logout` (`:5448`) forgets the account and its
+ devices (`DeviceManager::clean_user_info`).
+- `MainFrame` adds the Device tab (`m_monitor_page`, `MonitorPanel`, `_L("Device")`,
+ `tab_monitor_active`; `src/slic3r/GUI/MainFrame.cpp:1606-1608`). `MainFrame::show_device`
+ (`:1661-1745`) inserts it after Preview and takes it away again. `StatusPanel` shows each
+ printer's temperatures and print progress.
- `PrintHostSendDialog` (`src/slic3r/GUI/PrintHostDialogs.cpp`) confirms the upload name and the
post-upload action (upload, or upload and print).
@@ -38,10 +43,25 @@ Print host UI (GUI, ported only as browser behaviour):
plate 1 of a saved single-plate 3MF (the bytes `saveProjectWithProfiles` returns) with archive capture
and returns the `min_save` `.gcode.3mf`. Slicing and packaging stay in Rust.
- Web app:
- - "Physical printer" settings (host type `Pandar`, Hub URL, tenant ID, tenant API token), kept in
- browser `localStorage` like the rest of the app config.
- - "Print plate" side button: opens the physical printer settings when none are set, then the send
- dialog. The dialog lists the tenant's printers (`GET /api/v1/tenants/{tenant}/printers`) and
+ - A "Cloud" menu next to "File" signs in to a Pandar Hub. The sign-in dialog asks only for the Hub
+ URL and remembers the last one. A popup opens `{hub}/web-sign-in` with `redirect_url` (the
+ app's `cloud-callback.html`), a PKCE S256 `code_challenge` and a random `state`. The Hub sends
+ the popup back to `cloud-callback.html` with a one-use ticket. That page posts
+ `{ ticket, state }` on the `ares.cloud` BroadcastChannel: the app's
+ `Cross-Origin-Opener-Policy: same-origin` severs `window.opener` across the Hub hop. The app
+ exchanges the ticket and its verifier at `POST /api/v1/web/login-tickets/exchange` for a
+ 30-day `web:session` tenant token and its profile.
+ - The session (token, expiry, tenant, user name) and the Hub URL are kept in the `cloud` field of
+ the `ares.config` `localStorage` record. An expired session is not restored. "Sign out" and any
+ 401 from the tenant API drop the session and keep the Hub URL. The manual `printHost` field of
+ earlier builds is dropped on load, not migrated.
+ - A "Devices" tab (`#/devices`) follows Preview while signed in. It lists the tenant's printers
+ (`GET /api/v1/tenants/{tenant}/printers`) with their status, nozzle, bed and chamber
+ temperatures and the running print's name, layer, time left and progress. It then opens the
+ printer-event socket (`POST /api/v1/tenants/{tenant}/printer-events/tickets`, then
+ `GET /api/v1/tenants/{tenant}/printer-events?ticket=`), and each `printer_snapshot` replaces
+ its printer. A closed socket reconnects after 5 s. The socket is open only while the tab is shown.
+ - "Print plate" side button: opens the Cloud sign-in when signed out, then the send dialog. The dialog lists the tenant's printers (`GET /api/v1/tenants/{tenant}/printers`) and
uploads. A Bambu printer offers the Hub's calibration modes (0 off, 1 on, 2 auto) with the paired
booleans set to `mode != 0`, plus AMS and timelapse.
- The upload goes to the Pandar Hub client API:
@@ -51,7 +71,8 @@ Print host UI (GUI, ported only as browser behaviour):
- A Moonraker printer in Pandar accepts only `.gcode` (Hub `artifact_requires_gcode`), so it
gets the plate's plain G-code. A Bambu printer gets the `.gcode.3mf`.
- The Hub must allow the web origin through its `PANDAR_CORS_ALLOWED_ORIGINS` allowlist
- (ProjectPandar/pandar#17). The browser sends no cookies.
+ (ProjectPandar/pandar#17). The same allowlist bounds the sign-in `redirect_url` origin. The
+ browser sends no cookies.
## Included / deferred
@@ -67,6 +88,8 @@ Deferred, rejected with a message rather than approximated:
thumbnail renderer port yet.
- AMS slot mapping (`ams_mapping`); the job is sent without a mapping and `use_ams` as chosen.
- Other host types (OctoPrint, Moonraker direct, …).
+- Device control from the Devices tab (pause, stop, light, AMS), print history and the camera view.
+ The tab is read-only.
- "Export plate sliced file" in the File menu. It can reuse the same export, but it is a separate
menu slice.
@@ -90,10 +113,20 @@ reuse the preview slice. Two consequences follow, both upstream CLI behaviour:
- Web E2E (`web/e2e/pandarSend.spec.ts`): the P1S project `tests/parity/auto-lift-query-frame/project.3mf`
is opened with the P1S installed and sliced. A fake cross-origin Hub answers the CORS preflight,
checks the bearer token and records each job. The spec asserts the following:
- - the physical printer config is stored;
+ - the Cloud sign-in through the popup is stored;
- each job's path and fields;
- the Bambu `.gcode.3mf` has exactly the 11 `--min-save` members;
- its G-code equals the preview G-code apart from the three CLI-kept config lines;
- the Moonraker `.gcode` equals the preview G-code.
`target/web-e2e/pandar-send/` keeps both uploads and `requests.json` as the repeatable artifact.
+- Web E2E (`web/e2e/pandarCloud.spec.ts`): the fake Hub (`web/e2e/pandarHub.ts`) redirects the
+ sign-in popup with a ticket and accepts the exchange only for the verifier whose SHA-256 is the
+ issued challenge. The spec asserts the following:
+ - `#/devices` falls back to Prepare and no Devices tab shows while signed out;
+ - the stored session after sign-in;
+ - the printer cards, then a `printer_snapshot` updating temperatures and print progress;
+ - the session outlives a reload;
+ - sign-out leaves Devices, drops the session and keeps the Hub URL for the next sign-in.
+
+ `target/web-e2e/pandar-cloud/` keeps the two Devices screenshots and `session.json`.
diff --git a/web/app/public/cloud-callback.html b/web/app/public/cloud-callback.html
new file mode 100644
index 0000000000..d579b2b56c
--- /dev/null
+++ b/web/app/public/cloud-callback.html
@@ -0,0 +1,16 @@
+
+
+
+
+ Ares Cloud sign-in
+
+
+ Signed in. You can close this window.
+
+
+
diff --git a/web/app/src/assets/orca/tab_monitor_active.svg b/web/app/src/assets/orca/tab_monitor_active.svg
new file mode 100644
index 0000000000..6270ca49e7
--- /dev/null
+++ b/web/app/src/assets/orca/tab_monitor_active.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/web/app/src/devices/DevicesPage.tsx b/web/app/src/devices/DevicesPage.tsx
new file mode 100644
index 0000000000..db591752c6
--- /dev/null
+++ b/web/app/src/devices/DevicesPage.tsx
@@ -0,0 +1,83 @@
+import type { HubPrinter } from "../state/cloud";
+import { useDevices } from "../state/devices";
+
+const temperature = (current?: string | null, target?: string | null) =>
+ current == null ? "—" : target && Number(target) > 0 ? `${current} / ${target} °C` : `${current} °C`;
+
+const remaining = (minutes: number) =>
+ minutes >= 60 ? `${Math.floor(minutes / 60)} h ${minutes % 60} min` : `${minutes} min`;
+
+/** StatusPanel's temperatures and print progress (StatusPanel.cpp) for one Hub printer. */
+function DeviceCard({ printer }: { printer: HubPrinter }) {
+ const { print } = printer;
+ const active = print?.gcode_state && !["IDLE", "FINISH", "FAILED"].includes(print.gcode_state);
+ const rows: [string, string][] = [
+ ...(printer.nozzle_temperatures ?? []).map(
+ ({ label, current_celsius, target_celsius }, index): [string, string] => [
+ label ?? `Nozzle ${index + 1}`,
+ temperature(current_celsius, target_celsius),
+ ],
+ ),
+ ["Bed", temperature(printer.bed_temperature_celsius, printer.bed_target_temperature_celsius)],
+ ];
+ if (printer.chamber_temperature_celsius != null)
+ rows.push([
+ "Chamber",
+ temperature(printer.chamber_temperature_celsius, printer.chamber_target_temperature_celsius),
+ ]);
+ return (
+
+
+ {printer.name}
+
+ {printer.status}
+
+
+ {printer.model && {printer.model}
}
+
+ {rows.map(([name, value]) => (
+
+
{name}
+ {value}
+
+ ))}
+
+ {active && (
+
+
+ {print.subtask_name ?? print.gcode_state}
+ {print.current_layer != null && print.total_layers != null && (
+
+ {" "}
+ · Layer {print.current_layer}/{print.total_layers}
+
+ )}
+ {print.remaining_time_minutes != null && · {remaining(print.remaining_time_minutes)} left }
+
+
+
+ )}
+
+ );
+}
+
+/** MainFrame's Device tab (MonitorPanel, MainFrame.cpp:1606-1608): the signed-in tenant's printers. */
+export function DevicesPage() {
+ const { printers, error } = useDevices();
+ return (
+
+ {error && (
+
+ {error}
+
+ )}
+ {printers?.length === 0 && No printers in this Pandar tenant.
}
+ {!printers && !error && Loading printers…
}
+
+ {printers?.map((printer) => (
+
+ ))}
+
+
+ );
+}
diff --git a/web/app/src/router.tsx b/web/app/src/router.tsx
index b912256626..dc589ba587 100644
--- a/web/app/src/router.tsx
+++ b/web/app/src/router.tsx
@@ -1,5 +1,6 @@
import { createHashHistory, createRootRoute, createRoute, createRouter, redirect } from "@tanstack/react-router";
import { Shell } from "./shell/Shell";
+import { useApp } from "./state/store";
const rootRoute = createRootRoute({ component: Shell });
@@ -21,8 +22,17 @@ const previewRoute = createRoute({
path: "/preview",
});
+/** MainFrame's Device tab, only while signed in to Pandar Cloud. */
+const devicesRoute = createRoute({
+ getParentRoute: () => rootRoute,
+ path: "/devices",
+ beforeLoad: () => {
+ if (!useApp.getState().cloud) throw redirect({ to: "/prepare" });
+ },
+});
+
export const router = createRouter({
- routeTree: rootRoute.addChildren([indexRoute, prepareRoute, previewRoute]),
+ routeTree: rootRoute.addChildren([indexRoute, prepareRoute, previewRoute, devicesRoute]),
history: createHashHistory(),
});
diff --git a/web/app/src/shell/CloudMenu.tsx b/web/app/src/shell/CloudMenu.tsx
new file mode 100644
index 0000000000..e2775d2c8e
--- /dev/null
+++ b/web/app/src/shell/CloudMenu.tsx
@@ -0,0 +1,56 @@
+import { useEffect, useRef, useState } from "react";
+import { signOut } from "../state/cloud";
+import { useApp } from "../state/store";
+
+/**
+ * The top bar's Pandar account menu: sign in (GUI_App::request_login, GUI_App.cpp:5363) or, once
+ * signed in, the account and sign out (GUI_App::request_user_logout, :5448). Closes on a pick,
+ * Escape or a click elsewhere.
+ */
+export function CloudMenu({ onSignIn }: { onSignIn: () => void }) {
+ const cloud = useApp((state) => state.cloud);
+ const [open, setOpen] = useState(false);
+ const root = useRef(null);
+ useEffect(() => {
+ if (!open) return;
+ const close = (event: Event) => {
+ if (event instanceof KeyboardEvent ? event.key === "Escape" : !root.current?.contains(event.target as Node))
+ setOpen(false);
+ };
+ document.addEventListener("pointerdown", close);
+ document.addEventListener("keydown", close);
+ return () => {
+ document.removeEventListener("pointerdown", close);
+ document.removeEventListener("keydown", close);
+ };
+ }, [open]);
+ const pick = (action: () => void) => () => {
+ setOpen(false);
+ action();
+ };
+ return (
+
+
setOpen(!open)}>
+ Cloud
+
+ {open && (
+
+ {cloud ? (
+ <>
+
+ {cloud.userName} · {cloud.tenantName}
+
+
+ Sign out
+
+ >
+ ) : (
+
+ Sign in…
+
+ )}
+
+ )}
+
+ );
+}
diff --git a/web/app/src/shell/PrintHostDialogs.tsx b/web/app/src/shell/PrintHostDialogs.tsx
index 13de3948db..34a61d4633 100644
--- a/web/app/src/shell/PrintHostDialogs.tsx
+++ b/web/app/src/shell/PrintHostDialogs.tsx
@@ -1,15 +1,7 @@
import { useEffect, useRef, useState } from "react";
-import {
- type CalibrationMode,
- type HubPrinter,
- listPrinters,
- type PrintHost,
- type PrintOptions,
- printHost,
- sendBlocker,
- sendPlate,
- setPrintHost,
-} from "../state/printHost";
+import { cloudHubUrl, type HubPrinter, listPrinters, signIn } from "../state/cloud";
+import { type CalibrationMode, type PrintOptions, sendBlocker, sendPlate } from "../state/printHost";
+import { useApp } from "../state/store";
function useModal(onClose: () => void) {
const dialog = useRef(null);
@@ -28,42 +20,66 @@ function Header({ id, title, close }: { id: string; title: string; close: () =>
);
}
-/** PhysicalPrinterDialog (PhysicalPrinterDialog.cpp) for the `Pandar` host type. */
-export function PhysicalPrinterDialog({ onClose, onSaved }: { onClose: () => void; onSaved: () => void }) {
+/**
+ * The Cloud menu's sign-in (GUI_App::request_login, GUI_App.cpp:5363; ZUserLogin's WebView): the
+ * Pandar Hub URL, then the Hub's own sign-in page in a popup until it hands back a ticket.
+ */
+export function CloudSignInDialog({ onClose, onSignedIn }: { onClose: () => void; onSignedIn: () => void }) {
const { ref, close } = useModal(onClose);
- const [host, setHost] = useState(printHost() ?? { hubUrl: "", tenantId: "", token: "" });
- const field = (key: keyof PrintHost, label: string, type = "text") => (
-
- {label}
- setHost({ ...host, [key]: event.target.value })}
- />
-
- );
+ const [hubUrl, setHubUrl] = useState(cloudHubUrl);
+ const [waiting, setWaiting] = useState();
+ const [error, setError] = useState();
+ useEffect(() => () => waiting?.abort(), [waiting]);
return (
-
-
+
+
@@ -77,9 +93,9 @@ const MODES: [CalibrationMode, string][] = [
];
/** PrintHostSendDialog (PrintHostDialogs.cpp): picks a Hub printer and its print options, then uploads. */
-export function PrintHostSendDialog({ onClose, onEditHost }: { onClose: () => void; onEditHost: () => void }) {
+export function PrintHostSendDialog({ onClose }: { onClose: () => void }) {
const { ref, close } = useModal(onClose);
- const host = printHost()!;
+ const cloud = useApp((state) => state.cloud)!;
const [printers, setPrinters] = useState();
const [printerId, setPrinterId] = useState("");
const [options, setOptions] = useState({
@@ -91,14 +107,14 @@ export function PrintHostSendDialog({ onClose, onEditHost }: { onClose: () => vo
});
const [state, setState] = useState<{ sending?: true; error?: string; sent?: true }>({});
useEffect(() => {
- listPrinters(host).then(
+ listPrinters().then(
(list) => {
setPrinters(list);
setPrinterId(list[0]?.id ?? "");
},
(error: Error) => setState({ error: error.message }),
);
- }, [host]);
+ }, []);
const printer = printers?.find(({ id }) => id === printerId);
const blocker = printer && sendBlocker(printer);
const bambu = printer?.printer_family === "bambu_lab";
@@ -135,17 +151,14 @@ export function PrintHostSendDialog({ onClose, onEditHost }: { onClose: () => vo
onSubmit={(event) => {
event.preventDefault();
setState({ sending: true });
- sendPlate(host, printer!, options).then(
+ sendPlate(printer!, options).then(
() => setState({ sent: true }),
(error: Error) => setState({ error: error.message }),
);
}}
>
- {host.hubUrl}{" "}
-
- Edit
-
+ {cloud.tenantName} · {cloud.hubUrl}
Printer
diff --git a/web/app/src/shell/Shell.tsx b/web/app/src/shell/Shell.tsx
index cceac4632c..3ffab536a0 100644
--- a/web/app/src/shell/Shell.tsx
+++ b/web/app/src/shell/Shell.tsx
@@ -4,14 +4,14 @@ import { exportGcode, importFiles, selectObject, slicePlate } from "../state/act
import { PreparePage } from "../prepare/PreparePage";
import { PreviewPage } from "../preview/PreviewPage";
import { Sidebar } from "../sidebar/Sidebar";
-import { printHost } from "../state/printHost";
+import { DevicesPage } from "../devices/DevicesPage";
import { useApp } from "../state/store";
import { usePlacedScene } from "../viewport/usePlacedScene";
import { AboutDialog } from "./AboutDialog";
import { cmdDown, isShortcut } from "./keys";
import { LoadWarning } from "./LoadWarning";
import { MultipartDialog } from "./MultipartDialog";
-import { PhysicalPrinterDialog, PrintHostSendDialog } from "./PrintHostDialogs";
+import { CloudSignInDialog, PrintHostSendDialog } from "./PrintHostDialogs";
import { EngineCrashDialog } from "./EngineCrashDialog";
import { ShortcutsDialog } from "./ShortcutsDialog";
import { StatusBar } from "./StatusBar";
@@ -29,19 +29,26 @@ export function Shell() {
const [dragging, setDragging] = useState(false);
const [shortcutsOpen, setShortcutsOpen] = useState(false);
const [aboutOpen, setAboutOpen] = useState(false);
- const [printDialog, setPrintDialog] = useState<"host" | "send" | null>(null);
+ const [cloudDialog, setCloudDialog] = useState<"sign-in" | "sign-in-to-send" | "send" | null>(null);
const importInput = useRef(null);
const projectInput = useRef(null);
const router = useRouter();
// One Sidebar and both tab panes, built once; the route shows one (Plater::priv::set_current_panel,
// Plater.cpp:12564-12865).
- const preview = useRouterState({ select: (state) => state.location.pathname }) === "/preview";
+ const pathname = useRouterState({ select: (state) => state.location.pathname });
+ const preview = pathname === "/preview";
+ const signedIn = useApp((state) => state.cloud !== null);
const placed = usePlacedScene();
// Layout effect: CSS theme variables must be live before the viewport reads them.
useLayoutEffect(() => {
document.documentElement.dataset.theme = theme;
}, [theme]);
+ // GUI_App::request_user_logout drops the Device tab (MainFrame::show_device(false)): leave it first.
+ useEffect(() => {
+ if (!signedIn && pathname === "/devices") void router.navigate({ to: "/prepare" });
+ }, [signedIn, pathname, router]);
+
// MainFrame key handler (Ctrl+O/I/R/G) and plater keys: ? list, Esc deselect, Tab switches tabs.
useEffect(() => {
const onKey = (event: KeyboardEvent) => {
@@ -77,8 +84,9 @@ export function Shell() {
projectInput={projectInput}
onShortcuts={() => setShortcutsOpen(true)}
onAbout={() => setAboutOpen(true)}
+ onSignIn={() => setCloudDialog("sign-in")}
/>
- setPrintDialog(printHost() ? "send" : "host")} />
+ setCloudDialog(useApp.getState().cloud ? "send" : "sign-in-to-send")} />
-
+
+ {pathname === "/devices" &&
}
{dragging && (
@@ -121,17 +130,14 @@ export function Shell() {
setShortcutsOpen(false)} />
setAboutOpen(false)} />
- {printDialog === "host" && (
- setPrintDialog((open) => (open === "host" ? null : open))}
- onSaved={() => setPrintDialog("send")}
+ {(cloudDialog === "sign-in" || cloudDialog === "sign-in-to-send") && (
+ setCloudDialog((open) => (open === "send" ? open : null))}
+ onSignedIn={() => setCloudDialog(cloudDialog === "sign-in-to-send" ? "send" : null)}
/>
)}
- {printDialog === "send" && (
- setPrintDialog((open) => (open === "send" ? null : open))}
- onEditHost={() => setPrintDialog("host")}
- />
+ {cloudDialog === "send" && signedIn && (
+ setCloudDialog((open) => (open === "send" ? null : open))} />
)}
{wizard && (
diff --git a/web/app/src/shell/TopBar.tsx b/web/app/src/shell/TopBar.tsx
index d2c82a8292..13da9784ae 100644
--- a/web/app/src/shell/TopBar.tsx
+++ b/web/app/src/shell/TopBar.tsx
@@ -11,20 +11,23 @@ import {
} from "../state/actions";
import { importPresetFiles, presetSliceBlocker } from "../state/presets";
import { useApp } from "../state/store";
+import { CloudMenu } from "./CloudMenu";
import { FileMenu } from "./FileMenu";
import { MoonIcon, OrcaIcon, SunIcon } from "./icons";
-/** BBLTopbar: the File menu and the project title. */
+/** BBLTopbar: the File and Cloud menus and the project title. */
export function TitleBar({
importInput: input,
projectInput,
onShortcuts,
onAbout,
+ onSignIn,
}: {
importInput: RefObject;
projectInput: RefObject;
onShortcuts: () => void;
onAbout: () => void;
+ onSignIn: () => void;
}) {
const { theme, file } = useApp();
const presetInput = useRef(null);
@@ -36,6 +39,7 @@ export function TitleBar({
Ares
+
void; onAbout:
* sliced plate.
*/
export function TabBar({ onPrint }: { onPrint: () => void }) {
- const { engine, scene, slice, presetSelection, plateSlices } = useApp();
+ const { engine, scene, slice, presetSelection, plateSlices, cloud } = useApp();
const slicing = slice.status === "slicing";
const blocker = scene && presetSelection ? presetSliceBlocker(presetSelection, scene) : null;
const multiPlate = (scene?.plates.length ?? 0) > 1;
@@ -160,6 +164,12 @@ export function TabBar({ onPrint }: { onPrint: () => void }) {
Preview
+ {/* MainFrame::show_device (MainFrame.cpp:1661-1745): the Device tab after Preview, while signed in. */}
+ {cloud && (
+
+ Devices
+
+ )}
void }) {
Export G-code file
- {/* SideButton "Print plate" (Plater::send_gcode): a physical printer first, then the send dialog. */}
+ {/* SideButton "Print plate" (Plater::send_gcode): a Cloud sign-in first, then the send dialog. */}
Print plate
diff --git a/web/app/src/state/cloud.ts b/web/app/src/state/cloud.ts
new file mode 100644
index 0000000000..40492d093d
--- /dev/null
+++ b/web/app/src/state/cloud.ts
@@ -0,0 +1,142 @@
+/**
+ * The Cloud menu's Pandar Hub account: GUI_App::request_login and request_user_logout
+ * (GUI_App.cpp:5363-5470) over the Hub's web login ticket. A popup signs in on `{hub}/web-sign-in`;
+ * the Hub redirects it to `cloud-callback.html` with a one-use ticket, which the page broadcasts
+ * back here (the app's `Cross-Origin-Opener-Policy` severs `window.opener`), and the ticket and
+ * the PKCE verifier exchange for a `web:session` tenant token.
+ */
+import { saveConfig, storedConfig } from "./persistence";
+import { useApp } from "./store";
+
+/** The BroadcastChannel `cloud-callback.html` posts `{ ticket, state }` on. */
+const CHANNEL = "ares.cloud";
+
+export interface HubNozzleTemperature {
+ label: string | null;
+ current_celsius: string | null;
+ target_celsius: string | null;
+}
+
+export interface HubPrint {
+ gcode_state: string | null;
+ subtask_name: string | null;
+ progress_percent: number | null;
+ remaining_time_minutes: number | null;
+ current_layer: number | null;
+ total_layers: number | null;
+}
+
+/** A Hub `Printer` (contracts/hub-client.openapi.json), as far as Ares reads it. */
+export interface HubPrinter {
+ id: string;
+ name: string;
+ model: string | null;
+ printer_family: "bambu_lab" | "moonraker";
+ status: string;
+ nozzle_temperatures?: HubNozzleTemperature[];
+ bed_temperature_celsius?: string | null;
+ bed_target_temperature_celsius?: string | null;
+ chamber_temperature_celsius?: string | null;
+ chamber_target_temperature_celsius?: string | null;
+ print?: HubPrint | null;
+}
+
+interface TicketExchange {
+ token: string;
+ expires_at: string;
+ profile: { user_name: string; tenant_id: string; tenant_name: string };
+}
+
+/** The Hub URL of the last sign-in, for the next one. */
+export const cloudHubUrl = () => storedConfig.cloud?.hubUrl ?? "";
+
+const base64url = (bytes: Uint8Array) =>
+ btoa(String.fromCharCode(...bytes))
+ .replace(/\+/g, "-")
+ .replace(/\//g, "_")
+ .replace(/=+$/, "");
+const randomToken = (size: number) => base64url(crypto.getRandomValues(new Uint8Array(size)));
+
+async function hubJson(response: Response): Promise {
+ if (!response.ok) {
+ const body = (await response.json().catch(() => null)) as { error?: string } | null;
+ throw new Error(`Pandar Hub: ${body?.error ?? `HTTP ${response.status}`}`);
+ }
+ return response.json();
+}
+
+/** Signs in to `hubUrl` in a popup; resolves once signed in. Aborting `signal` stops waiting for the popup. */
+export async function signIn(hubUrl: string, signal: AbortSignal) {
+ const hub = hubUrl.replace(/\/+$/, "");
+ const verifier = randomToken(32);
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
+ const state = randomToken(16);
+ const signInUrl = new URL(`${hub}/web-sign-in`);
+ signInUrl.search = new URLSearchParams({
+ redirect_url: new URL("cloud-callback.html", location.origin + location.pathname).href,
+ code_challenge: base64url(new Uint8Array(digest)),
+ state,
+ }).toString();
+ if (!window.open(signInUrl, "ares-cloud-sign-in", "popup,width=520,height=720"))
+ throw new Error("The browser blocked the sign-in window. Allow pop-ups for this site and try again.");
+ // Listening starts in this task, before the popup can load its callback.
+ const channel = new BroadcastChannel(CHANNEL);
+ try {
+ const ticket = new Promise((resolve, reject) => {
+ signal.addEventListener("abort", () => reject(signal.reason as Error));
+ channel.onmessage = ({ data }: MessageEvent<{ ticket: string | null; state: string | null }>) => {
+ if (data.state !== state) return;
+ if (data.ticket) resolve(data.ticket);
+ else reject(new Error("Pandar Hub sign-in returned no ticket."));
+ };
+ });
+ const response = await fetch(`${hub}/api/v1/web/login-tickets/exchange`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ticket: await ticket, code_verifier: verifier }),
+ });
+ const { token, expires_at, profile } = (await hubJson(response)) as TicketExchange;
+ const session = {
+ token,
+ expiresAt: expires_at,
+ tenantId: profile.tenant_id,
+ tenantName: profile.tenant_name,
+ userName: profile.user_name,
+ };
+ saveConfig({ cloud: { hubUrl: hub, session } });
+ useApp.setState({ cloud: { hubUrl: hub, ...session } });
+ } finally {
+ channel.close();
+ }
+}
+
+/** Forgets the session, keeping the Hub URL for the next sign-in. */
+export function signOut() {
+ const { cloud } = useApp.getState();
+ if (!cloud) return;
+ saveConfig({ cloud: { hubUrl: cloud.hubUrl } });
+ useApp.setState({ cloud: null });
+}
+
+/** The signed-in tenant's URL for `path` (`/printers`, ...). */
+export function tenantUrl(path: string) {
+ const { hubUrl, tenantId } = useApp.getState().cloud!;
+ return `${hubUrl}/api/v1/tenants/${encodeURIComponent(tenantId)}${path}`;
+}
+
+/** A tenant API request with the session token; a rejected token signs out. */
+export async function tenantRequest(path: string, init?: RequestInit): Promise {
+ const response = await fetch(tenantUrl(path), {
+ ...init,
+ headers: { Authorization: `Bearer ${useApp.getState().cloud!.token}` },
+ });
+ if (response.status === 401) {
+ signOut();
+ throw new Error("Pandar Hub: the session expired. Sign in again from the Cloud menu.");
+ }
+ return hubJson(response);
+}
+
+export async function listPrinters(): Promise {
+ return ((await tenantRequest("/printers")) as { printers: HubPrinter[] }).printers;
+}
diff --git a/web/app/src/state/devices.ts b/web/app/src/state/devices.ts
new file mode 100644
index 0000000000..ac64a026a5
--- /dev/null
+++ b/web/app/src/state/devices.ts
@@ -0,0 +1,62 @@
+/**
+ * The Devices tab's printers (DeviceManager's machine list, DeviceManager.cpp): the tenant's Hub
+ * printers, then each `printer_snapshot` of the Hub's printer-event socket in their place.
+ */
+import { useEffect, useState } from "react";
+import { type HubPrinter, listPrinters, tenantRequest, tenantUrl } from "./cloud";
+
+/** The wait before reconnecting a closed event socket. */
+const RECONNECT_MS = 5000;
+
+type PrinterEvent = { type: "printer_snapshot"; printer: HubPrinter } | { type: "job_progress" | "command_result" };
+
+export interface Devices {
+ printers?: HubPrinter[];
+ error?: string;
+}
+
+/** The signed-in tenant's printers, live while mounted. */
+export function useDevices(): Devices {
+ const [devices, setDevices] = useState({});
+ useEffect(() => {
+ let socket: WebSocket | undefined;
+ let retry: number | undefined;
+ let stopped = false;
+ const connect = async () => {
+ try {
+ const printers = await listPrinters();
+ const { ticket } = (await tenantRequest("/printer-events/tickets", { method: "POST" })) as { ticket: string };
+ if (stopped) return;
+ setDevices({ printers });
+ const url = new URL(tenantUrl("/printer-events"));
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
+ url.searchParams.set("ticket", ticket);
+ socket = new WebSocket(url);
+ socket.onmessage = ({ data }: MessageEvent) => {
+ const event = JSON.parse(data) as PrinterEvent;
+ if (event.type !== "printer_snapshot") return;
+ const { printer } = event;
+ setDevices(({ printers: list = [] }) => ({
+ printers: list.some(({ id }) => id === printer.id)
+ ? list.map((item) => (item.id === printer.id ? printer : item))
+ : [...list, printer],
+ }));
+ };
+ socket.onclose = () => {
+ if (!stopped) retry = window.setTimeout(() => void connect(), RECONNECT_MS);
+ };
+ } catch (error) {
+ if (stopped) return;
+ setDevices((current) => ({ ...current, error: (error as Error).message }));
+ retry = window.setTimeout(() => void connect(), RECONNECT_MS);
+ }
+ };
+ void connect();
+ return () => {
+ stopped = true;
+ window.clearTimeout(retry);
+ socket?.close();
+ };
+ }, []);
+ return devices;
+}
diff --git a/web/app/src/state/persistence.ts b/web/app/src/state/persistence.ts
index c34a1fc24d..921dc63508 100644
--- a/web/app/src/state/persistence.ts
+++ b/web/app/src/state/persistence.ts
@@ -10,11 +10,20 @@ import type { ModelFile, Theme, ViewMode } from "./store";
const CONFIG_KEY = "ares.config";
const VERSION = 1;
-/** A Pandar Hub tenant: `print_host` and `printhost_apikey` of a `Pandar` host type. */
-export interface PrintHost {
- hubUrl: string;
- tenantId: string;
+/** A Pandar Hub sign-in (GUI_App::request_login): the tenant token its web login ticket exchanged for. */
+export interface CloudSession {
token: string;
+ /** RFC 3339. */
+ expiresAt: string;
+ tenantId: string;
+ tenantName: string;
+ userName: string;
+}
+
+/** The Cloud menu's Pandar Hub and its session, absent once signed out. */
+export interface CloudConfig {
+ hubUrl: string;
+ session?: CloudSession;
}
/** Per-printer settings (AppConfig::set_printer_setting, AppConfig.hpp:239-249). */
@@ -55,8 +64,8 @@ export interface StoredConfig {
preferredFilamentMapMode: "Auto For Flush" | "Auto For Match" | "Manual";
/** Section `arrange` (GLCanvas3D.cpp:1526-1561), app-config strings by key; absent in older records. */
arrange?: Record;
- /** The physical printer (PhysicalPrinterDialog): a Pandar Hub print host; absent until set. */
- printHost?: PrintHost;
+ /** The Pandar Hub of the Cloud menu; absent until a first sign-in. */
+ cloud?: CloudConfig;
}
const DEFAULTS: StoredConfig = {
@@ -93,6 +102,19 @@ function isPrinterSettings(value: unknown): value is PrinterSettings {
);
}
+function isCloudConfig(value: unknown): value is CloudConfig {
+ const session = isRecord(value) ? value.session : undefined;
+ return (
+ isRecord(value) &&
+ typeof value.hubUrl === "string" &&
+ (session === undefined ||
+ (isRecord(session) &&
+ [session.token, session.expiresAt, session.tenantId, session.tenantName, session.userName].every(
+ (item) => typeof item === "string",
+ )))
+ );
+}
+
function isStoredConfig(value: Record): boolean {
return (
(value.theme === "dark" || value.theme === "light") &&
@@ -111,11 +133,7 @@ function isStoredConfig(value: Record): boolean {
["Auto For Flush", "Auto For Match", "Manual"].includes(value.preferredFilamentMapMode as string) &&
(value.arrange === undefined ||
(isRecord(value.arrange) && Object.values(value.arrange).every((item) => typeof item === "string"))) &&
- (value.printHost === undefined ||
- (isRecord(value.printHost) &&
- [value.printHost.hubUrl, value.printHost.tenantId, value.printHost.token].every(
- (item) => typeof item === "string",
- )))
+ (value.cloud === undefined || isCloudConfig(value.cloud))
);
}
@@ -130,6 +148,8 @@ function loadConfig(): StoredConfig | null {
// The vendor-level `vendors` field of earlier builds is dropped, not expanded into models:
// no printer is installed, so the setup wizard opens.
delete config.vendors;
+ // The manual Pandar print host of earlier builds is dropped: the Cloud sign-in replaces it.
+ delete config.printHost;
config.installedPrinters ??= {};
if (version === VERSION && isStoredConfig(config)) return config as unknown as StoredConfig;
} catch {
diff --git a/web/app/src/state/printHost.ts b/web/app/src/state/printHost.ts
index ecfcd4bc26..9a59b82ed1 100644
--- a/web/app/src/state/printHost.ts
+++ b/web/app/src/state/printHost.ts
@@ -1,24 +1,14 @@
/**
- * The Pandar Hub print host: PhysicalPrinterDialog's host settings and PrintHostSendDialog's upload
- * (Plater::send_gcode, Plater.cpp:21228-21248). A Bambu printer receives the plate's print-job
- * `.gcode.3mf`; a Moonraker printer accepts only `.gcode` (Hub `artifact_requires_gcode`).
+ * PrintHostSendDialog's upload to the signed-in Pandar Hub (Plater::send_gcode, Plater.cpp:21228-21248).
+ * A Bambu printer receives the plate's print-job `.gcode.3mf`; a Moonraker printer accepts only
+ * `.gcode` (Hub `artifact_requires_gcode`).
*/
import { gcodeFileName } from "./actions";
-import { type PrintHost, saveConfig, storedConfig } from "./persistence";
+import { type HubPrinter, tenantRequest } from "./cloud";
import { projectBytes } from "./saveProject";
import { slicer } from "./slicer";
import { useApp } from "./store";
-export type { PrintHost };
-
-export interface HubPrinter {
- id: string;
- name: string;
- model: string | null;
- printer_family: "bambu_lab" | "moonraker";
- status: string;
-}
-
/** Calibration mode (Pandar `PrintCalibrationMode`): 0 off, 1 on, 2 auto. */
export type CalibrationMode = 0 | 1 | 2;
@@ -30,28 +20,6 @@ export interface PrintOptions {
timelapse: boolean;
}
-export const printHost = () => storedConfig.printHost;
-
-export function setPrintHost(host: PrintHost) {
- saveConfig({ printHost: { ...host, hubUrl: host.hubUrl.replace(/\/+$/, "") } });
-}
-
-async function hub(host: PrintHost, path: string, init?: RequestInit) {
- const response = await fetch(`${host.hubUrl}/api/v1/tenants/${encodeURIComponent(host.tenantId)}${path}`, {
- ...init,
- headers: { Authorization: `Bearer ${host.token}` },
- });
- if (!response.ok) {
- const body = (await response.json().catch(() => null)) as { error?: string } | null;
- throw new Error(`Pandar Hub: ${body?.error ?? `HTTP ${response.status}`}`);
- }
- return response.json() as Promise;
-}
-
-export async function listPrinters(host: PrintHost): Promise {
- return ((await hub(host, "/printers")) as { printers: HubPrinter[] }).printers;
-}
-
/** Why the current plate cannot be sent to `printer`, if it cannot. */
export function sendBlocker(printer: HubPrinter): string | undefined {
const { slice, scene } = useApp.getState();
@@ -62,7 +30,7 @@ export function sendBlocker(printer: HubPrinter): string | undefined {
}
/** Uploads the current plate to `printer` as a Hub print job. */
-export async function sendPlate(host: PrintHost, printer: HubPrinter, options: PrintOptions) {
+export async function sendPlate(printer: HubPrinter, options: PrintOptions) {
const { slice, scene, currentPlate } = useApp.getState();
if (slice.status !== "done") throw new Error("Slice the plate first.");
let file: Blob;
@@ -91,5 +59,5 @@ export async function sendPlate(host: PrintHost, printer: HubPrinter, options: P
form.set("auto_flow_cali", String(options.flowCali));
form.set("auto_offset_cali", String(options.offsetCali));
form.set("timelapse", String(options.timelapse));
- await hub(host, `/printers/${encodeURIComponent(printer.id)}/jobs`, { method: "POST", body: form });
+ await tenantRequest(`/printers/${encodeURIComponent(printer.id)}/jobs`, { method: "POST", body: form });
}
diff --git a/web/app/src/state/store.ts b/web/app/src/state/store.ts
index f3fe9bd7c5..d9312990e2 100644
--- a/web/app/src/state/store.ts
+++ b/web/app/src/state/store.ts
@@ -18,7 +18,7 @@ import type {
import type { FilamentSelection } from "./filamentAssignment";
import { create } from "zustand";
import type { FilamentInfo } from "../sidebar/filamentGroups";
-import { storedConfig } from "./persistence";
+import { type CloudSession, storedConfig } from "./persistence";
import type { PrinterPanel } from "./printerPanel";
import type { TypedSettings } from "./typedSettings";
@@ -152,8 +152,15 @@ export interface AppState {
preview: PreviewView;
/** G-code window visibility (GUI_App `show_gcode_window`). */
gcodeWindow: boolean;
+ /** The signed-in Pandar Hub account (GUI_App::is_user_login), if any. */
+ cloud: CloudAccount | null;
}
+/** A Pandar Hub and its unexpired session. */
+export type CloudAccount = CloudSession & { hubUrl: string };
+
+const storedCloud = storedConfig.cloud;
+
/** The vendor bundles `PresetBundle::apply_vendor_config` installs: those with a model (PresetBundle.cpp:1968-1975). */
export const installedVendors = (installed: InstalledPrinters) =>
Object.keys(installed)
@@ -204,4 +211,8 @@ export const useApp = create(() => ({
printerPanel: null,
preview: DEFAULT_PREVIEW,
gcodeWindow: storedConfig.gcodeWindow,
+ cloud:
+ storedCloud?.session && Date.parse(storedCloud.session.expiresAt) > Date.now()
+ ? { hubUrl: storedCloud.hubUrl, ...storedCloud.session }
+ : null,
}));
diff --git a/web/app/src/styles.css b/web/app/src/styles.css
index 0dc2b64f68..866bc32c63 100644
--- a/web/app/src/styles.css
+++ b/web/app/src/styles.css
@@ -3,6 +3,7 @@
@import "./styles/sidebar.css";
@import "./styles/printer.css";
@import "./styles/printHost.css";
+@import "./styles/devices.css";
@import "./styles/wizard.css";
@import "./styles/viewport.css";
@import "./styles/mobile.css";
diff --git a/web/app/src/styles/devices.css b/web/app/src/styles/devices.css
new file mode 100644
index 0000000000..c4e0133455
--- /dev/null
+++ b/web/app/src/styles/devices.css
@@ -0,0 +1,84 @@
+/* Cloud menu and the Devices tab (DevicesPage). */
+.cloud-menu {
+ position: relative;
+}
+.cloud-menu > .context-menu {
+ position: absolute;
+ top: 100%;
+ left: 0;
+}
+.page[hidden] {
+ display: none;
+}
+.devices-page {
+ height: 100%;
+ overflow-y: auto;
+ padding: 16px;
+}
+.devices-empty {
+ color: var(--text-dim);
+}
+.devices-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
+ gap: 12px;
+}
+.device-card {
+ display: grid;
+ gap: 8px;
+ padding: 12px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--panel);
+}
+.device-card-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+}
+.device-card h3 {
+ margin: 0;
+ font-size: 14px;
+ overflow-wrap: anywhere;
+}
+.device-status {
+ padding: 1px 8px;
+ border-radius: 10px;
+ background: var(--panel-raised);
+ color: var(--text-dim);
+ font-size: 11px;
+}
+.device-status[data-status="online"] {
+ background: var(--accent-fill);
+ color: var(--accent-text);
+}
+.device-model,
+.device-print p {
+ margin: 0;
+ color: var(--text-dim);
+ font-size: 12px;
+}
+.device-values {
+ display: grid;
+ gap: 4px;
+ margin: 0;
+ font-size: 12px;
+}
+.device-values div {
+ display: flex;
+ justify-content: space-between;
+}
+.device-values dt {
+ color: var(--text-dim);
+}
+.device-values dd {
+ margin: 0;
+}
+.device-print {
+ display: grid;
+ gap: 4px;
+}
+.device-print progress {
+ width: 100%;
+}
diff --git a/web/app/src/styles/printHost.css b/web/app/src/styles/printHost.css
index 7b1c7665a4..517ef78d93 100644
--- a/web/app/src/styles/printHost.css
+++ b/web/app/src/styles/printHost.css
@@ -1,4 +1,4 @@
-/* PhysicalPrinterDialog and PrintHostSendDialog. */
+/* CloudSignInDialog and PrintHostSendDialog. */
.print-host-dialog {
width: min(440px, 92vw);
padding: 0;
diff --git a/web/e2e/pandarCloud.spec.ts b/web/e2e/pandarCloud.spec.ts
new file mode 100644
index 0000000000..924db7e47a
--- /dev/null
+++ b/web/e2e/pandarCloud.spec.ts
@@ -0,0 +1,105 @@
+import { mkdirSync, writeFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { expect, type Page } from "@playwright/test";
+import { test } from "./failureDiagnostics";
+import { expiresAt, fakeHub, hub, signInDialog, token } from "./pandarHub";
+
+// The Cloud menu's Pandar sign-in and the Devices tab (docs/architecture/web-pandar-print-host.md).
+const artifacts = fileURLToPath(new URL("../../target/web-e2e/pandar-cloud/", import.meta.url));
+const idle = {
+ id: "p-bambu",
+ name: "Bambu P1S",
+ model: "P1S",
+ printer_family: "bambu_lab",
+ status: "online",
+ nozzle_temperatures: [{ label: null, current_celsius: "25", target_celsius: "0" }],
+ bed_temperature_celsius: "24",
+ bed_target_temperature_celsius: "0",
+ chamber_temperature_celsius: null,
+ print: { gcode_state: "IDLE", subtask_name: null, progress_percent: null, remaining_time_minutes: null },
+};
+const voron = {
+ id: "p-klipper",
+ name: "Voron",
+ model: null,
+ printer_family: "moonraker",
+ status: "offline",
+ nozzle_temperatures: [],
+ bed_temperature_celsius: null,
+ print: null,
+};
+const printing = {
+ ...idle,
+ nozzle_temperatures: [{ label: null, current_celsius: "219", target_celsius: "220" }],
+ bed_temperature_celsius: "55",
+ bed_target_temperature_celsius: "55",
+ print: {
+ gcode_state: "RUNNING",
+ subtask_name: "benchy",
+ progress_percent: 42,
+ remaining_time_minutes: 75,
+ current_layer: 12,
+ total_layers: 80,
+ },
+};
+
+const cloudMenu = (page: Page) => page.getByRole("button", { name: "Cloud" });
+const devicesTab = (page: Page) => page.getByRole("link", { name: "Devices" });
+const storedCloud = (page: Page) => page.evaluate(() => JSON.parse(localStorage.getItem("ares.config")!).cloud);
+
+test("signs in to Pandar Cloud and shows its printers live in the Devices tab", async ({ page }) => {
+ mkdirSync(artifacts, { recursive: true });
+ const hubState = await fakeHub(page.context(), [idle, voron]);
+ await page.goto("/#/devices");
+ // Signed out: no Devices tab, and its route falls back to Prepare.
+ await expect(page).toHaveURL(/#\/prepare$/);
+ await expect(devicesTab(page)).toHaveCount(0);
+
+ await cloudMenu(page).click();
+ await page.getByRole("menuitem", { name: "Sign in…" }).click();
+ await signInDialog(page);
+ const session = { token, expiresAt, tenantId: "t1", tenantName: "Workshop", userName: "Ada" };
+ expect(await storedCloud(page)).toEqual({ hubUrl: hub, session });
+
+ await devicesTab(page).click();
+ await expect(page).toHaveURL(/#\/devices$/);
+ const bambu = page.getByRole("article", { name: "Bambu P1S" });
+ await expect(bambu).toContainText("online");
+ await expect(bambu).toContainText("Nozzle 125 °C");
+ await expect(bambu).toContainText("Bed24 °C");
+ await expect(bambu.getByRole("progressbar")).toHaveCount(0);
+ await expect(page.getByRole("article", { name: "Voron" })).toContainText("offline");
+ await expect.poll(() => hubState.sockets.map(({ ticket }) => ticket)).toEqual(["events-1"]);
+ const signedIn = await page.screenshot();
+
+ // A printer_snapshot replaces the printer it names.
+ hubState.sockets[0]!.socket.send(JSON.stringify({ type: "printer_snapshot", printer: printing }));
+ await expect(bambu).toContainText("Nozzle 1219 / 220 °C");
+ await expect(bambu).toContainText("benchy · Layer 12/80 · 1 h 15 min left");
+ await expect(bambu.getByRole("progressbar", { name: "Bambu P1S progress" })).toHaveAttribute("value", "42");
+ const live = await page.screenshot();
+
+ // The session outlives a reload.
+ await page.reload();
+ await expect(page.getByRole("article", { name: "Bambu P1S" })).toBeVisible();
+ await expect.poll(() => hubState.sockets.length).toBe(2);
+
+ await cloudMenu(page).click();
+ await expect(page.getByRole("menu", { name: "Cloud" })).toContainText("Ada · Workshop");
+ await page.getByRole("menuitem", { name: "Sign out" }).click();
+ await expect(page).toHaveURL(/#\/prepare$/);
+ await expect(devicesTab(page)).toHaveCount(0);
+ expect(await storedCloud(page)).toEqual({ hubUrl: hub });
+
+ // The next sign-in offers the last Hub.
+ await cloudMenu(page).click();
+ await page.getByRole("menuitem", { name: "Sign in…" }).click();
+ await expect(page.getByRole("textbox", { name: "Hub URL" })).toHaveValue(hub);
+
+ writeFileSync(`${artifacts}signed-in.png`, signedIn);
+ writeFileSync(`${artifacts}live.png`, live);
+ writeFileSync(
+ `${artifacts}session.json`,
+ JSON.stringify({ signedIn: session, sockets: hubState.sockets.map(({ ticket }) => ticket) }, null, 2),
+ );
+});
diff --git a/web/e2e/pandarHub.ts b/web/e2e/pandarHub.ts
new file mode 100644
index 0000000000..33e2eae0ad
--- /dev/null
+++ b/web/e2e/pandarHub.ts
@@ -0,0 +1,87 @@
+import { createHash } from "node:crypto";
+import { type BrowserContext, expect, type Page, type Request, type WebSocketRoute } from "@playwright/test";
+
+/** A fake Pandar Hub tenant `t1` for the Cloud menu (docs/architecture/web-pandar-print-host.md). */
+export const hub = "http://hub.pandar.test";
+export const token = "pandar_web_token";
+export const expiresAt = "2099-01-01T00:00:00Z";
+const app = "http://127.0.0.1:4174";
+const cors = {
+ "access-control-allow-origin": app,
+ "access-control-allow-methods": "GET, POST, OPTIONS",
+ "access-control-allow-headers": "authorization, content-type",
+};
+
+export interface FakeHub {
+ /** Each job upload. */
+ jobs: Request[];
+ /** Each printer-event socket the app opened, by ticket. */
+ sockets: { ticket: string; socket: WebSocketRoute }[];
+}
+
+/**
+ * Routes the Hub for every page of `context`, the sign-in popup included: `/web-sign-in` redirects
+ * at once to the app's callback with a ticket, and the exchange checks the PKCE verifier against
+ * the challenge it was issued for.
+ */
+export async function fakeHub(context: BrowserContext, printers: object[]): Promise {
+ const hubState: FakeHub = { jobs: [], sockets: [] };
+ const challenges = new Map();
+ let tickets = 0;
+ await context.route(`${hub}/**`, async (route) => {
+ const request = route.request();
+ const url = new URL(request.url());
+ const path = url.pathname;
+ if (path === "/web-sign-in") {
+ const redirect = new URL(url.searchParams.get("redirect_url")!);
+ if (redirect.href !== `${app}/cloud-callback.html`) return route.fulfill({ status: 400, body: "redirect_url" });
+ const ticket = `pandar_web_ticket_${++tickets}`;
+ challenges.set(ticket, url.searchParams.get("code_challenge")!);
+ redirect.search = new URLSearchParams({ ticket, state: url.searchParams.get("state")! }).toString();
+ return route.fulfill({ status: 302, headers: { location: redirect.href } });
+ }
+ if (request.method() === "OPTIONS") return route.fulfill({ status: 204, headers: cors });
+ if (request.method() === "POST" && path === "/api/v1/web/login-tickets/exchange") {
+ const { ticket, code_verifier } = request.postDataJSON() as { ticket: string; code_verifier: string };
+ const challenge = createHash("sha256").update(code_verifier).digest("base64url");
+ if (challenges.get(ticket) !== challenge)
+ return route.fulfill({ status: 401, headers: cors, json: { error: "invalid_plugin_ticket" } });
+ challenges.delete(ticket);
+ return route.fulfill({
+ headers: cors,
+ json: {
+ token,
+ expires_at: expiresAt,
+ profile: { user_id: "u1", user_name: "Ada", tenant_id: "t1", tenant_name: "Workshop" },
+ },
+ });
+ }
+ if (request.headers().authorization !== `Bearer ${token}`)
+ return route.fulfill({ status: 401, headers: cors, json: { error: "unauthorized" } });
+ if (request.method() === "GET" && path === "/api/v1/tenants/t1/printers")
+ return route.fulfill({ headers: cors, json: { printers } });
+ if (request.method() === "POST" && path === "/api/v1/tenants/t1/printer-events/tickets")
+ return route.fulfill({
+ status: 201,
+ headers: cors,
+ json: { ticket: `events-${hubState.sockets.length + 1}`, expires_at: expiresAt },
+ });
+ if (request.method() === "POST" && /^\/api\/v1\/tenants\/t1\/printers\/[^/]+\/jobs$/.test(path)) {
+ hubState.jobs.push(request);
+ return route.fulfill({ status: 201, headers: cors, json: { id: `job-${hubState.jobs.length}` } });
+ }
+ return route.fulfill({ status: 404, headers: cors, json: { error: "not_found" } });
+ });
+ await context.routeWebSocket(/^ws:\/\/hub\.pandar\.test\/api\/v1\/tenants\/t1\/printer-events\?/, (socket) => {
+ hubState.sockets.push({ ticket: new URL(socket.url()).searchParams.get("ticket")!, socket });
+ });
+ return hubState;
+}
+
+/** Fills the Cloud sign-in dialog and waits for the popup's round trip. */
+export async function signInDialog(page: Page) {
+ const dialog = page.getByRole("dialog", { name: "Sign in to Pandar Cloud" });
+ await dialog.getByRole("textbox", { name: "Hub URL" }).fill(`${hub}/`);
+ await Promise.all([page.waitForEvent("popup"), dialog.getByRole("button", { name: "Sign in" }).click()]);
+ await expect(dialog).toBeHidden();
+}
diff --git a/web/e2e/pandarSend.spec.ts b/web/e2e/pandarSend.spec.ts
index 9cd3e04160..def902162b 100644
--- a/web/e2e/pandarSend.spec.ts
+++ b/web/e2e/pandarSend.spec.ts
@@ -3,13 +3,12 @@ import { fileURLToPath } from "node:url";
import { expect, type Page, type Request } from "@playwright/test";
import { unzipSync } from "fflate";
import { test } from "./failureDiagnostics";
+import { expiresAt, fakeHub, hub, signInDialog, token } from "./pandarHub";
-// Plater::send_gcode to a Pandar Hub print host (docs/architecture/web-pandar-print-host.md).
+// Plater::send_gcode to the signed-in Pandar Hub (docs/architecture/web-pandar-print-host.md).
const repositoryRoot = fileURLToPath(new URL("../../", import.meta.url));
const artifacts = fileURLToPath(new URL("../../target/web-e2e/pandar-send/", import.meta.url));
const fixture = `${repositoryRoot}tests/parity/auto-lift-query-frame/project.3mf`;
-const hub = "http://hub.pandar.test";
-const token = "tenant-token";
const printers = [
{ id: "p-bambu", name: "Bambu P1S", model: "P1S", printer_family: "bambu_lab", status: "idle" },
{ id: "p-klipper", name: "Voron", model: null, printer_family: "moonraker", status: "idle" },
@@ -27,31 +26,6 @@ const config = {
nozzleVolumeTypes: {},
preferredFilamentMapMode: "Auto For Flush",
};
-const cors = {
- "access-control-allow-origin": "http://127.0.0.1:4174",
- "access-control-allow-methods": "GET, POST, OPTIONS",
- "access-control-allow-headers": "authorization, content-type",
-};
-
-/** A fake Hub tenant that records each job upload. */
-async function fakeHub(page: Page) {
- const jobs: Request[] = [];
- await page.route(`${hub}/**`, async (route) => {
- const request = route.request();
- const path = new URL(request.url()).pathname;
- if (request.method() === "OPTIONS") return route.fulfill({ status: 204, headers: cors });
- if (request.headers().authorization !== `Bearer ${token}`)
- return route.fulfill({ status: 401, headers: cors, json: { error: "unauthorized" } });
- if (request.method() === "GET" && path === "/api/v1/tenants/t1/printers")
- return route.fulfill({ headers: cors, json: { printers } });
- if (request.method() === "POST" && /^\/api\/v1\/tenants\/t1\/printers\/[^/]+\/jobs$/.test(path)) {
- jobs.push(request);
- return route.fulfill({ status: 201, headers: cors, json: { id: `job-${jobs.length}` } });
- }
- return route.fulfill({ status: 404, headers: cors, json: { error: "not_found" } });
- });
- return jobs;
-}
async function form(request: Request) {
const body = new Response(new Uint8Array(request.postDataBuffer()!), {
@@ -76,7 +50,7 @@ test.use({ firstRunConfig: false });
test("sends the sliced plate to Bambu and Moonraker printers through a Pandar Hub", async ({ page }) => {
mkdirSync(artifacts, { recursive: true });
- const jobs = await fakeHub(page);
+ const { jobs } = await fakeHub(page.context(), printers);
await page.addInitScript((record) => {
if (localStorage.getItem("ares.config") === null) localStorage.setItem("ares.config", record);
}, JSON.stringify(config));
@@ -93,16 +67,15 @@ test("sends the sliced plate to Bambu and Moonraker printers through a Pandar Hu
const [download] = await Promise.all([page.waitForEvent("download"), exportGcode.click()]);
const preview = new Uint8Array(readFileSync((await download.path())!));
- // No host yet: the physical printer comes first, then the send dialog.
+ // Not signed in yet: the Cloud sign-in comes first, then the send dialog.
await print.click();
- const host = page.getByRole("dialog", { name: "Physical Printer" });
- await host.getByRole("textbox", { name: "Hub URL" }).fill(`${hub}/`);
- await host.getByRole("textbox", { name: "Tenant ID" }).fill("t1");
- await host.getByLabel("API Token").fill(token);
- await host.getByRole("button", { name: "OK" }).click();
+ await signInDialog(page);
await page.getByRole("dialog", { name: "Send to Printer" }).getByRole("button", { name: "Close" }).click();
- const stored = await page.evaluate(() => JSON.parse(localStorage.getItem("ares.config")!).printHost);
- expect(stored).toEqual({ hubUrl: hub, tenantId: "t1", token });
+ const stored = await page.evaluate(() => JSON.parse(localStorage.getItem("ares.config")!).cloud);
+ expect(stored).toEqual({
+ hubUrl: hub,
+ session: { token, expiresAt, tenantId: "t1", tenantName: "Workshop", userName: "Ada" },
+ });
await send(page, "Bambu P1S");
await send(page, "Voron");
diff --git a/web/scripts/extract-process-layout.mjs b/web/scripts/extract-process-layout.mjs
index 77201ca420..c64d5ae911 100644
--- a/web/scripts/extract-process-layout.mjs
+++ b/web/scripts/extract-process-layout.mjs
@@ -145,7 +145,7 @@ for (const page of Object.values(tabs).flat()) {
// Plater sidebar titles (printer/filament/process) and preset edit buttons, MainFrame tabs and topbar.
const SHELL_ICONS = [
- "printer", "filament", "process", "edit", "settings", "tab_3d_active", "tab_preview_active", "topbar_file",
+ "printer", "filament", "process", "edit", "settings", "tab_3d_active", "tab_preview_active", "tab_monitor_active", "topbar_file",
// MenuFactory ADD_VOLUME_MENU_ITEMS: ObjectList volume icons.
"menu_add_part", "menu_add_negative", "menu_add_modifier", "menu_support_blocker", "menu_support_enforcer",
// GLCanvas3D::_init_main_toolbar, GLGizmosManager::init and _init_assemble_view_toolbar icons.