Skip to content

The VS Code of video editing, built for agents.

TypeScript

Add deep link support for checkout and auth in desktop app

konstantin-paulus08d10b927cf7
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.ts
index 69ede765..dca5e18b 100644
--- a/apps/desktop/forge.config.ts
+++ b/apps/desktop/forge.config.ts
@@ -18,6 +18,7 @@ const config: ForgeConfig = {
appCategoryType: 'public.app-category.video',
appVersion: version,
icon: './assets/icon',
+ protocols: [{ name: 'Diffusion Studio', schemes: ['diffusion'] }],
prune: false,
ignore: (path) =>
path !== '' &&
diff --git a/apps/desktop/src/main-channels.ts b/apps/desktop/src/main-channels.ts
index ad78c885..bd31fdc9 100644
--- a/apps/desktop/src/main-channels.ts
+++ b/apps/desktop/src/main-channels.ts
@@ -28,6 +28,7 @@ export const MAIN_CHANNELS = {
// Renderer→Main requests
APP_OPEN_EXTERNAL: "app:open-external",
AUTH_GET_PENDING_CALLBACK: "auth:get-pending-callback",
+ CHECKOUT_GET_PENDING_CALLBACK: "checkout:get-pending-callback",
WINDOW_IS_FULLSCREEN: "window:is-fullscreen",
WINDOW_CAPTURE: "window:capture",
FILE_TRANSFER: "file:transfer",
@@ -40,15 +41,23 @@ export const MAIN_CHANNELS = {
// Main→Renderer events
AUTH_CALLBACK: "auth:callback",
+ CHECKOUT_CALLBACK: "checkout:callback",
WINDOW_FULLSCREEN_CHANGE: "window:fullscreen-change",
HEADLESS_MODE: "headless:mode",
} as const;
export type MainChannel = (typeof MAIN_CHANNELS)[keyof typeof MAIN_CHANNELS];
+// Events fed by a `diffusion://` deep link. Main routes each link to exactly
+// one of these by its host, so auth and checkout never consume each other's.
+export type DeepLinkChannel =
+ | typeof MAIN_CHANNELS.AUTH_CALLBACK
+ | typeof MAIN_CHANNELS.CHECKOUT_CALLBACK;
+
export type MainRequestMap = {
[MAIN_CHANNELS.APP_OPEN_EXTERNAL]: { request: { url: string }; response: void };
[MAIN_CHANNELS.AUTH_GET_PENDING_CALLBACK]: { request: void; response: string | null };
+ [MAIN_CHANNELS.CHECKOUT_GET_PENDING_CALLBACK]: { request: void; response: string | null };
[MAIN_CHANNELS.WINDOW_IS_FULLSCREEN]: { request: void; response: boolean };
[MAIN_CHANNELS.WINDOW_CAPTURE]: { request: void; response: ScreenshotResult };
[MAIN_CHANNELS.FILE_TRANSFER]: {
@@ -78,6 +87,7 @@ export type MainRequestChannel = keyof MainRequestMap;
export type MainEventMap = {
[MAIN_CHANNELS.AUTH_CALLBACK]: { url: string };
+ [MAIN_CHANNELS.CHECKOUT_CALLBACK]: { url: string };
[MAIN_CHANNELS.WINDOW_FULLSCREEN_CHANGE]: { fullscreen: boolean };
[MAIN_CHANNELS.HEADLESS_MODE]: { active: boolean };
};
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index f6ee5ba2..cd1414cf 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -12,6 +12,7 @@ import { startCliServer, stopCliServer, isHeadless } from "./cli-server";
import { setupAppMenu } from "./menu";
import { mainBridge } from "./main-manager";
import { MAIN_CHANNELS } from "./main-channels";
+import type { DeepLinkChannel } from "./main-channels";
import type { LogEntry } from "@diffusionstudio/cli/protocol";
const DEV_URL = "http://localhost:5173";
@@ -56,7 +57,10 @@ if (app.isPackaged && !process.argv.includes("--hidden")) {
const openWrites = new Map<string, { handle: FileHandle; path: string }>();
let mainWindow: BrowserWindow | null = null;
-let pendingAuthUrl: string | null = null;
+
+// Deep links that arrived before the renderer could take them, keyed by the
+// channel they belong to so auth and checkout never drain each other's link.
+const pendingDeepLinks = new Map<DeepLinkChannel, string>();
// Renderer console mirror, served to the CLI via LOGS_GET. Lives in main so
// it survives reloads and captures everything the devtools console shows
@@ -89,13 +93,40 @@ function isHiddenLaunch(argv: string[]): boolean {
return argv.includes("--hidden");
}
-function deliverAuthUrl(url: string) {
+// diffusion://auth/callback → auth, diffusion://checkout/callback → checkout.
+function deepLinkChannel(url: string): DeepLinkChannel | null {
+ let host: string;
+ try {
+ host = new URL(url).hostname;
+ } catch {
+ return null;
+ }
+
+ if (host === "auth") return MAIN_CHANNELS.AUTH_CALLBACK;
+ if (host === "checkout") return MAIN_CHANNELS.CHECKOUT_CALLBACK;
+ return null;
+}
+
+function deliverDeepLink(url: string) {
+ const channel = deepLinkChannel(url);
+ if (!channel) return;
+
+ // A link that arrives before the page can receive it is parked rather than
+ // pushed: the renderer's subscription only exists once the component holding
+ // it mounts, which is well after did-finish-load. Parked links are handed
+ // over by the take* handlers below, which every consumer calls on mount.
if (!mainWindow || mainWindow.isDestroyed() || mainWindow.webContents.isLoading()) {
- pendingAuthUrl = url;
+ pendingDeepLinks.set(channel, url);
return;
}
- mainBridge.emit(mainWindow, MAIN_CHANNELS.AUTH_CALLBACK, { url });
+ mainBridge.emit(mainWindow, channel, { url });
+}
+
+function takePendingDeepLink(channel: DeepLinkChannel): string | null {
+ const url = pendingDeepLinks.get(channel) ?? null;
+ pendingDeepLinks.delete(channel);
+ return url;
}
async function setFileInputFiles(selector: string, absolutePath: string) {
@@ -133,13 +164,6 @@ function createWindow(show = true) {
captureConsole(mainWindow);
- mainWindow.webContents.on("did-finish-load", () => {
- if (pendingAuthUrl) {
- mainBridge.emit(mainWindow, MAIN_CHANNELS.AUTH_CALLBACK, { url: pendingAuthUrl });
- }
- pendingAuthUrl = null;
- });
-
applyCornerRadius(MACOS_CORNER_RADIUS);
applyBackdrop();
@@ -187,7 +211,7 @@ if (process.defaultApp && process.argv.length >= 2) {
if (app.requestSingleInstanceLock()) {
app.on("second-instance", (_event, argv) => {
const url = findProtocolUrl(argv);
- if (url) deliverAuthUrl(url);
+ if (url) deliverDeepLink(url);
const hidden = isHiddenLaunch(argv);
if (mainWindow && !mainWindow.isDestroyed()) {
@@ -202,15 +226,16 @@ if (app.requestSingleInstanceLock()) {
app.on("open-url", (event, url) => {
event.preventDefault();
- deliverAuthUrl(url);
+ deliverDeepLink(url);
});
mainBridge.handle(MAIN_CHANNELS.APP_OPEN_EXTERNAL, ({ url }) => shell.openExternal(url));
- mainBridge.handle(MAIN_CHANNELS.AUTH_GET_PENDING_CALLBACK, () => {
- const url = pendingAuthUrl;
- pendingAuthUrl = null;
- return url;
- });
+ mainBridge.handle(MAIN_CHANNELS.AUTH_GET_PENDING_CALLBACK, () =>
+ takePendingDeepLink(MAIN_CHANNELS.AUTH_CALLBACK),
+ );
+ mainBridge.handle(MAIN_CHANNELS.CHECKOUT_GET_PENDING_CALLBACK, () =>
+ takePendingDeepLink(MAIN_CHANNELS.CHECKOUT_CALLBACK),
+ );
mainBridge.handle(MAIN_CHANNELS.WINDOW_IS_FULLSCREEN, () => mainWindow?.isFullScreen() ?? false);
mainBridge.handle(MAIN_CHANNELS.WINDOW_CAPTURE, async () => {
if (!mainWindow || mainWindow.isDestroyed()) throw new Error("No main window");
@@ -268,7 +293,7 @@ if (app.requestSingleInstanceLock()) {
session.defaultSession.setDevicePermissionHandler(() => true);
const url = findProtocolUrl(process.argv);
- if (url) pendingAuthUrl = url;
+ if (url) deliverDeepLink(url);
startCliServer();
createWindow(!isHiddenLaunch(process.argv));
diff --git a/apps/web/public/checkout/electron-callback.html b/apps/web/public/checkout/electron-callback.html
new file mode 100644
index 00000000..62afa968
--- /dev/null
+++ b/apps/web/public/checkout/electron-callback.html
@@ -0,0 +1,42 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <meta name="robots" content="noindex" />
+ <title>Returning to Diffusion Studio…</title>
+ <style>
+ :root { color-scheme: dark; }
+ body {
+ font-family: -apple-system, BlinkMacSystemFont, "Inter", system-ui, sans-serif;
+ background: #0a0a0a;
+ color: #fafafa;
+ display: grid;
+ place-items: center;
+ min-height: 100vh;
+ margin: 0;
+ }
+ .card { text-align: center; max-width: 22rem; padding: 2rem; }
+ h1 { font-size: 1.125rem; font-weight: 600; margin: 0 0 0.5rem; }
+ p { color: #a3a3a3; margin: 0.5rem 0; font-size: 0.875rem; }
+ a { color: #5b9dff; text-decoration: none; }
+ a:hover { text-decoration: underline; }
+ </style>
+ </head>
+ <body>
+ <div class="card">
+ <h1>Returning you to Diffusion Studio…</h1>
+ <p>You can close this tab.</p>
+ <p><small>Nothing happening? <a id="link" href="#">Open the app</a>.</small></p>
+ </div>
+ <script>
+ (function () {
+ var params = new URLSearchParams(window.location.search);
+ var target = "diffusion://checkout/callback?" + params.toString();
+ var link = document.getElementById("link");
+ if (link) link.setAttribute("href", target);
+ window.location.replace(target);
+ })();
+ </script>
+ </body>
+</html>
diff --git a/apps/web/src/components/purchase-success.tsx b/apps/web/src/components/purchase-success.tsx
index 6dd8e35e..262c8163 100644
--- a/apps/web/src/components/purchase-success.tsx
+++ b/apps/web/src/components/purchase-success.tsx
@@ -3,21 +3,52 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import { useSearchParams } from "@solidjs/router";
-import { Show } from "solid-js";
+import { Show, createSignal, onCleanup, onMount } from "solid-js";
import { Icon } from "@/components/ui/icon";
+import { mainBridge } from "@/lib/ipc";
+import { MAIN_CHANNELS } from "@desktop/main-channels";
export function PurchaseSuccess() {
const [params, setParams] = useSearchParams();
+ const [deepLinkSuccess, setDeepLinkSuccess] = createSignal(false);
+
+ onMount(() => {
+ if (!window.desktop) return;
+
+ // Desktop returns from Stripe through a diffusion:// deep link rather than a
+ // query param — the app window never navigates away in the first place.
+ const handleCallbackUrl = (url: string | null) => {
+ if (!url) return;
+ try {
+ if (new URL(url).searchParams.get("status") === "success") {
+ setDeepLinkSuccess(true);
+ }
+ } catch {
+ // Malformed deep link — nothing to show.
+ }
+ };
+
+ void mainBridge
+ .call(MAIN_CHANNELS.CHECKOUT_GET_PENDING_CALLBACK, undefined)
+ .then(handleCallbackUrl);
+
+ const unsubscribe = mainBridge.handle(MAIN_CHANNELS.CHECKOUT_CALLBACK, ({ url }) => {
+ handleCallbackUrl(url);
+ });
+
+ onCleanup(unsubscribe);
+ });
const close = (e: MouseEvent) => {
e.stopPropagation();
e.preventDefault();
+ setDeepLinkSuccess(false);
setParams({ checkout: undefined }, { replace: true });
};
return (
- <Show when={params.checkout === "success"}>
+ <Show when={params.checkout === "success" || deepLinkSuccess()}>
<div
class="pointer-events-auto fixed inset-0 z-[999] flex flex-col items-center justify-center gap-2 bg-popover/30 backdrop-blur-3xl"
onClick={close}
diff --git a/apps/web/src/lib/checkout.ts b/apps/web/src/lib/checkout.ts
index e0ecc7ba..6410369a 100644
--- a/apps/web/src/lib/checkout.ts
+++ b/apps/web/src/lib/checkout.ts
@@ -11,6 +11,8 @@ import type {
} from "@diffusionstudio/api-contract";
import { trpc } from "./trpc";
+import { mainBridge } from "./ipc";
+import { MAIN_CHANNELS } from "@desktop/main-channels";
function toastMessage(err: unknown, fallback: string): string {
// Empty / non-JSON 500 bodies (e.g. upstream crashed before tRPC could
@@ -69,13 +71,33 @@ export function getTopupPrice(tier: TopupCredits): number {
return Math.round(credits * CREDIT_RATE * (1 + markup));
}
+const ELECTRON_CHECKOUT_REDIRECT =
+ "https://app.diffusion.studio/checkout/electron-callback.html";
+
function successAndCancelUrls(): { successUrl: string; cancelUrl: string } {
+ if (window.desktop) {
+ return {
+ successUrl: `${ELECTRON_CHECKOUT_REDIRECT}?status=success`,
+ cancelUrl: `${ELECTRON_CHECKOUT_REDIRECT}?status=cancel`,
+ };
+ }
+
const cancelUrl = window.location.href;
const success = new URL(window.location.href);
success.searchParams.set("checkout", "success");
return { successUrl: success.toString(), cancelUrl };
}
+/** Hands the URL to the system browser on desktop; navigates in place on web. */
+async function openCheckoutUrl(url: string): Promise<void> {
+ if (window.desktop) {
+ await mainBridge.call(MAIN_CHANNELS.APP_OPEN_EXTERNAL, { url });
+ return;
+ }
+
+ window.location.href = url;
+}
+
export async function startSubscriptionCheckout(input: {
creditQuantity: SubscriptionCredits;
billingPeriod: BillingPeriod;
@@ -85,7 +107,7 @@ export async function startSubscriptionCheckout(input: {
...input,
...successAndCancelUrls(),
});
- window.location.href = url;
+ await openCheckoutUrl(url);
} catch (err) {
toast.error(toastMessage(err, "Checkout failed"));
}
@@ -99,13 +121,25 @@ export async function startTopupCheckout(
creditQuantity,
...successAndCancelUrls(),
});
- window.location.href = url;
+ await openCheckoutUrl(url);
} catch (err) {
toast.error(toastMessage(err, "Checkout failed"));
}
}
export async function openBillingPortal(): Promise<void> {
+ if (window.desktop) {
+ try {
+ const { url } = await trpc.createBillingPortal.mutate();
+ await mainBridge.call(MAIN_CHANNELS.APP_OPEN_EXTERNAL, { url });
+ } catch (err) {
+ toast.error(toastMessage(err, "Failed to open billing portal"));
+ }
+ return;
+ }
+
+ // Web opens the tab up front so the click still counts as a user gesture by
+ // the time the portal URL comes back.
const tab = window.open("", "_blank");
if (!tab) return;