mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 01:24:30 +01:00
Add a desktop handoff to mobile Cloud onboarding (#23326)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Onboarding asks users to connect a model before they can finish setting up their agent. > - Cloud users can start setup on a phone, where provider sign-in and key entry can be difficult. > - They need a way to find the same workspace on a computer. > - This pull request adds a copyable link on the mobile model step and defers agent creation while the handoff is offered. > - A user can open the link on desktop or continue on the phone. ## Linked Issues or Issue Description **Subsystem affected** React onboarding UI and its Cloud health metadata. **Problem or motivation** On a phone, the Cloud model step does not explain how to find the same onboarding page on a computer. The fresh agent draft is local to that browser and can leave a provisional agent behind. **Proposed solution** Offer Continue on desktop and Keep going here at the start of the mobile model step. Copy the workspace's HTTPS `/onboarding` link. Ask users to sign in to the same account on desktop and explain that they may need to enter their choices again. **Alternatives considered** The original invite URL would carry an invite token. Copying the workspace's onboarding URL lets Cloud handle sign-in through its existing entry flow. **Roadmap alignment** This is a focused improvement to the existing onboarding wizard. It uses the current Cloud workspace entry flow and keeps model selection available on mobile. **Additional context** Refs #23315 for naming-step setup drafts. Related prior work: #3594 covered a native iOS-to-web handoff token and is closed. ## What Changed - Add the Cloud mobile handoff panel and clipboard fallback. - Prefer the canonical tenant HTTPS origin and build a clean `/onboarding` URL. Older tenants can use the current HTTPS tenant origin. - Defer the provisional agent in the naming and model steps while the mobile handoff is available. Desktop and self-hosted sessions keep the early-draft behavior from #23315. - Render the step indicators as round dots inside the step buttons so the mobile touch-height rule does not stretch them. - Add browser coverage for the Cloud and self-hosted paths and unit coverage for URL handling. ## Verification - Passed 52 focused Vitest tests for the onboarding route, stepper, handoff URL, and shared clipboard policy. - Passed UI typecheck, the test-budget guard, and `git diff --check`. - Passed 23 tests in desktop Chrome with four workers, including the affected CI browser shard and the upstream early-draft regression. The handoff scenarios cover the mobile dots, clipboard success and manual fallback, same-workspace desktop re-entry via simulated sign-in, continuing on mobile, and the self-hosted flow. - Manual reproduction: use a fresh Cloud test workspace and a 390 × 844 viewport. Enter an agent name and proceed to Connect a model. Open Continue on desktop and copy the link. Open it on desktop and sign in with the same account if needed. A real Cloud sign-in was outside the local fixture. ## Risks - Setup choices from the phone may need to be entered again on desktop. - Real Cloud sign-in and in-app mobile browsers still need a live tenant check. No database migration is needed. ## Model Used - OpenAI Codex with GPT-6.2 Sol (`gpt-6.2-sol`) for branch preparation and verification. Used the terminal and Chromium. The context window size is not available in the session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Scott Tong <1504818+scotttong@users.noreply.github.com>
This commit is contained in:
1 parent
d71d039ad7
commit
adc4501689
8 files changed
+394
-15
No files matched your search
@@ -0,0 +1,17 @@
|
||||
# Manual test: mobile setup desktop nudge
|
||||
|
||||
Use an isolated fixture or a fresh, authorized Cloud test workspace. The preview has no dependency on a live model for these checks. Do not use a real customer's invite or API credentials.
|
||||
|
||||
## Mobile to desktop
|
||||
|
||||
1. On a phone, open a fresh test invite (or use Chromium device emulation, 390 × 844, and open the preview's `/onboarding`). Complete the account/workspace entry if using an actual test tenant. Name the first agent and click **Next**.
|
||||
2. On **Connect a model**, before selecting a provider, expect **Setup is easier on desktop**. The model tiles should still be available.
|
||||
3. Open **Continue on desktop**. Check the instructions say to sign in with the same account and that setup choices may need to be re-entered. Use **Copy setup link** and confirm it copies the workspace’s HTTPS tenant hostname and `/onboarding`, with no query or fragment. Cloud prefers the canonical hostname from the workspace. Older tenants use the current HTTPS tenant hostname. If clipboard access is blocked, the link should be selected with a manual-copy message.
|
||||
4. Open that link in a different desktop browser profile. Sign in with the same account if required. Check that onboarding opens for the same workspace and that the phone left no provisional agent. Desktop onboarding may ask for the agent name again and create its own setup draft.
|
||||
5. Repeat with the phone's ordinary browser and an email app's in-app browser. This requires an actual configured Cloud test tenant to verify real invite/sign-in behavior; the fixture covers only the app entry point and shared tenant records.
|
||||
|
||||
## Keep going on mobile
|
||||
|
||||
1. Start fresh in mobile emulation or a new mobile session. At **Connect a model**, click **Keep going here**.
|
||||
2. The nudge disappears. The same model step and provider tiles remain; keyboard focus moves to the first tile. Select a provider and check the normal connection flow is available. Mobile users can also pick a model tile directly without using the banner.
|
||||
3. On a wide desktop viewport or a self-hosted instance, no banner should appear.
|
||||
@@ -0,0 +1,178 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { expect, test } from "@playwright/test";
|
||||
import type { BrowserContext, BrowserContextOptions } from "@playwright/test";
|
||||
|
||||
const controlPlane = "https://my.paperclip.app";
|
||||
const canonicalTenant = "https://example-workspace.paperclip.app";
|
||||
const stackSlug = "example-workspace";
|
||||
const mobileOptions: BrowserContextOptions = {
|
||||
viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true, serviceWorkers: "block",
|
||||
};
|
||||
|
||||
test("a Cloud mobile visitor copies the canonical tenant, can sign in there on desktop, or can keep going", async ({ browser, request, baseURL }, testInfo) => {
|
||||
const companyResponse = await request.post("/api/companies", { data: { name: `Mobile handoff ${randomUUID()}` } });
|
||||
expect(companyResponse.ok()).toBe(true);
|
||||
const company = await companyResponse.json();
|
||||
const healthResponse = await request.get("/api/health");
|
||||
expect(healthResponse.ok()).toBe(true);
|
||||
const cloudHealth = {
|
||||
...await healthResponse.json(),
|
||||
cloud: {
|
||||
managed: true, managedBy: "paperclip-cloud", cloudBaseUrl: controlPlane, stackSlug,
|
||||
runtimeIdentity: { canonicalOrigin: canonicalTenant, stackSlug },
|
||||
},
|
||||
};
|
||||
const featureResponse = await request.get("/api/instance/settings/experimental");
|
||||
expect(featureResponse.ok()).toBe(true);
|
||||
const featureSettings = { ...await featureResponse.json(), enableConferenceRoomChat: true };
|
||||
const mobile = await browser.newContext({ ...mobileOptions, baseURL });
|
||||
const continuedMobile = await browser.newContext({ ...mobileOptions, baseURL });
|
||||
const desktop = await browser.newContext({ baseURL, viewport: { width: 1280, height: 1080 }, serviceWorkers: "block", reducedMotion: "reduce" });
|
||||
|
||||
let desktopSignedIn = false;
|
||||
let cloudRedirects = 0;
|
||||
async function fixture(context: BrowserContext, workspace: { id: string }, needsDesktopSignIn = false) {
|
||||
await context.route("**/api/health", (route) => route.fulfill({
|
||||
json: { ...cloudHealth, ...(needsDesktopSignIn ? { deploymentMode: "authenticated", bootstrapStatus: "ready" } : {}) },
|
||||
}));
|
||||
await context.route("**/api/auth/get-session", async (route) => {
|
||||
if (needsDesktopSignIn && !desktopSignedIn) {
|
||||
return route.fulfill({ status: 401, json: { error: "Board authentication required" } });
|
||||
}
|
||||
const response = await route.fetch();
|
||||
const session = await response.json();
|
||||
delete session.boardBootstrap;
|
||||
return route.fulfill({ response, json: session });
|
||||
});
|
||||
if (needsDesktopSignIn) {
|
||||
await context.route((url) => url.pathname === "/api/cli-auth/me", (route) => route.fulfill({
|
||||
json: { userId: "local-board", isInstanceAdmin: false, companyIds: [workspace.id] },
|
||||
}));
|
||||
await context.route(`${controlPlane}/v1/stacks/${stackSlug}/entry-redirect?**`, (route) => {
|
||||
cloudRedirects++;
|
||||
expect(new URL(route.request().url()).searchParams.get("returnTo")).toBe("/onboarding");
|
||||
desktopSignedIn = true;
|
||||
return route.fulfill({ status: 302, headers: { Location: new URL("/onboarding", baseURL).href } });
|
||||
});
|
||||
}
|
||||
await context.route((url) => url.pathname === "/api/companies", (route) => route.request().method() === "GET"
|
||||
? route.fulfill({ json: [workspace] }) : route.continue());
|
||||
await context.route("**/api/instance/settings/experimental", (route) => route.request().method() === "GET"
|
||||
? route.fulfill({ json: featureSettings }) : route.continue());
|
||||
}
|
||||
|
||||
try {
|
||||
await mobile.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await fixture(mobile, company);
|
||||
await fixture(desktop, company, true);
|
||||
const page = await mobile.newPage();
|
||||
const mobileHealth = page.waitForResponse((response) => new URL(response.url()).pathname === "/api/health");
|
||||
await page.goto(`/${company.issuePrefix}/onboarding?invite=not-for-desktop#phone`);
|
||||
expect((await (await mobileHealth).json()).cloud).toEqual(cloudHealth.cloud);
|
||||
await page.locator("#onboarding-agent-name").fill("Scout");
|
||||
await expect.poll(() => page.evaluate(() => matchMedia("(width < 40rem)").matches)).toBe(true);
|
||||
await page.getByRole("button", { name: "Next", exact: true }).click();
|
||||
const nudge = page.getByRole("region", { name: "Setup is easier on desktop" });
|
||||
await expect(nudge).toBeVisible();
|
||||
await expect(page.getByRole("heading", { name: "Connect a model" })).toBeVisible();
|
||||
await expect(page.getByRole("radio").first()).toBeVisible();
|
||||
const progress = page.locator('button[aria-current="step"]').locator("..");
|
||||
const dots = progress.locator('button > span[aria-hidden="true"]');
|
||||
await expect(dots).toHaveCount(3);
|
||||
expect(await dots.evaluateAll((indicators) => indicators.every((indicator) => {
|
||||
const { width, height } = indicator.getBoundingClientRect();
|
||||
return width > 0 && width === height && parseFloat(getComputedStyle(indicator).borderTopLeftRadius) >= width / 2;
|
||||
}))).toBe(true);
|
||||
await page.screenshot({ path: testInfo.outputPath("mobile-01-nudge.png"), animations: "disabled" });
|
||||
|
||||
await nudge.getByRole("button", { name: "Continue on desktop" }).click();
|
||||
const handoff = nudge.getByRole("textbox", { name: "Desktop setup link" });
|
||||
const destination = new URL("/onboarding", canonicalTenant);
|
||||
await expect(handoff).toHaveValue(destination.href);
|
||||
await expect(nudge).toContainText("You may need to re-enter setup choices.");
|
||||
const copy = nudge.getByRole("button", { name: "Copy setup link" });
|
||||
await expect(copy).toBeInViewport();
|
||||
await page.screenshot({ path: testInfo.outputPath("mobile-cloud-https-handoff.png"), animations: "disabled" });
|
||||
await copy.click();
|
||||
const copied = nudge.getByRole("button", { name: "Link copied" });
|
||||
await expect(copied).toBeVisible();
|
||||
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(destination.href);
|
||||
await page.evaluate(() => {
|
||||
Object.defineProperty(navigator.clipboard, "writeText", {
|
||||
value: async () => {
|
||||
throw new DOMException("Clipboard access denied", "NotAllowedError");
|
||||
},
|
||||
});
|
||||
Object.defineProperty(document, "execCommand", { value: () => false });
|
||||
});
|
||||
await copied.click();
|
||||
await expect(nudge.getByText("Automatic copy is unavailable. Copy the selected link manually.")).toBeVisible();
|
||||
await expect(handoff).toBeFocused();
|
||||
expect(await handoff.evaluate((element: HTMLInputElement) =>
|
||||
element.value.slice(element.selectionStart ?? 0, element.selectionEnd ?? 0))).toBe(destination.href);
|
||||
expect(await (await request.get(`/api/companies/${company.id}/agents`)).json()).toEqual([]);
|
||||
|
||||
const desktopPage = await desktop.newPage();
|
||||
await desktopPage.goto(destination.pathname);
|
||||
const desktopName = desktopPage.locator("#onboarding-agent-name");
|
||||
await expect(desktopName).toBeVisible({ timeout: 25_000 });
|
||||
await desktopName.scrollIntoViewIfNeeded();
|
||||
expect(cloudRedirects).toBe(1);
|
||||
expect(new URL(desktopPage.url()).pathname).toBe(destination.pathname);
|
||||
await expect(desktopName).not.toHaveValue("Scout");
|
||||
await expect(desktopPage.getByRole("region", { name: "Setup is easier on desktop" })).toHaveCount(0);
|
||||
await desktopPage.screenshot({ path: testInfo.outputPath("mobile-03-desktop-handoff.png"), animations: "disabled" });
|
||||
await expect.poll(async () => (await (await request.get(`/api/companies/${company.id}/agents`)).json()))
|
||||
.toEqual([expect.objectContaining({ pauseReason: "setup" })]);
|
||||
|
||||
const continuedResponse = await request.post("/api/companies", { data: { name: `Continue mobile ${randomUUID()}` } });
|
||||
expect(continuedResponse.ok()).toBe(true);
|
||||
const continuedCompany = await continuedResponse.json();
|
||||
await fixture(continuedMobile, continuedCompany);
|
||||
const continuedPage = await continuedMobile.newPage();
|
||||
await continuedPage.goto(`/${continuedCompany.issuePrefix}/onboarding`);
|
||||
await continuedPage.locator("#onboarding-agent-name").fill("Scout");
|
||||
await continuedPage.getByRole("button", { name: "Next", exact: true }).click();
|
||||
const continuedNudge = continuedPage.getByRole("region", { name: "Setup is easier on desktop" });
|
||||
await continuedNudge.getByRole("button", { name: "Keep going here" }).click();
|
||||
await expect(continuedNudge).toHaveCount(0);
|
||||
await expect(continuedPage.getByRole("radio").first()).toBeFocused();
|
||||
await expect(continuedPage.getByRole("heading", { name: "Connect a model" })).toBeVisible();
|
||||
await expect.poll(async () => (await (await request.get(`/api/companies/${continuedCompany.id}/agents`)).json())
|
||||
.map((agent: { name: string }) => agent.name)).toEqual(["Scout"]);
|
||||
await continuedPage.screenshot({ path: testInfo.outputPath("mobile-04-kept-going.png"), animations: "disabled" });
|
||||
} finally {
|
||||
await mobile.close();
|
||||
await continuedMobile.close();
|
||||
await desktop.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("self-hosted mobile onboarding keeps its original model step and agent draft", async ({ browser, request, baseURL }) => {
|
||||
const response = await request.post("/api/companies", { data: { name: `Local mobile ${randomUUID()}` } });
|
||||
expect(response.ok()).toBe(true);
|
||||
const company = await response.json();
|
||||
const origin = await request.get("/api/health");
|
||||
expect(origin.ok()).toBe(true);
|
||||
expect((await origin.json()).cloud).toBeUndefined();
|
||||
|
||||
const features = await request.get("/api/instance/settings/experimental");
|
||||
expect(features.ok()).toBe(true);
|
||||
const featureSettings = { ...await features.json(), enableConferenceRoomChat: true };
|
||||
const mobile = await browser.newContext({ ...mobileOptions, baseURL });
|
||||
try {
|
||||
await mobile.route("**/api/instance/settings/experimental", (route) => route.request().method() === "GET"
|
||||
? route.fulfill({ json: featureSettings }) : route.continue());
|
||||
const page = await mobile.newPage();
|
||||
await page.goto(`/${company.issuePrefix}/onboarding`);
|
||||
await page.locator("#onboarding-agent-name").fill("Local Scout");
|
||||
await page.getByRole("button", { name: "Next", exact: true }).click();
|
||||
await expect(page.getByRole("heading", { name: "Connect a model" })).toBeVisible();
|
||||
await expect(page.getByRole("radio").first()).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Continue on desktop" })).toHaveCount(0);
|
||||
await expect.poll(async () => (await (await request.get(`/api/companies/${company.id}/agents`)).json())
|
||||
.map((agent: { name: string }) => agent.name)).toEqual(["Local Scout"]);
|
||||
} finally {
|
||||
await mobile.close();
|
||||
}
|
||||
});
|
||||
@@ -25,6 +25,7 @@ export type CloudInstanceHealthStatus = {
|
||||
stackSlug: string | null;
|
||||
stackDisplayName?: string;
|
||||
cloudBaseUrl: string | null;
|
||||
runtimeIdentity?: { canonicalOrigin: string; stackSlug: string };
|
||||
};
|
||||
|
||||
export type HealthStatus = {
|
||||
|
||||
@@ -183,6 +183,8 @@ import {
|
||||
} from "./onboarding/Stepper";
|
||||
import { AgentPreview } from "./onboarding/AgentPreview";
|
||||
import { ModelSourceTiles, type CredentialMode } from "./onboarding/ModelSourceTiles";
|
||||
import { MobileDesktopNudge, useMobileOnboardingViewport } from "./onboarding/MobileDesktopNudge";
|
||||
import { cloudDesktopOnboardingUrl } from "../lib/cloud-onboarding-handoff";
|
||||
import { CredentialModeLink } from "./onboarding/CredentialModeLink";
|
||||
import { FooterNav, type FooterPrimaryIcon } from "./onboarding/FooterNav";
|
||||
import { OnboardingHeading } from "./onboarding/OnboardingPrimitives";
|
||||
@@ -496,6 +498,7 @@ function OnboardingWizardInner({
|
||||
// Managed stacks create organizations on Cloud, so the route below never
|
||||
// resolves into the create wizard there — see resolveRouteOnboardingOptions.
|
||||
const cloudInstance = useCloudInstance();
|
||||
const mobileOnboardingViewport = useMobileOnboardingViewport();
|
||||
|
||||
// Support opening the wizard from a route (e.g. /onboarding or an existing
|
||||
// company's "add agent" entry point) in addition to the dialog context.
|
||||
@@ -623,6 +626,8 @@ function OnboardingWizardInner({
|
||||
* whether the row has been *answered* on this visit.
|
||||
*/
|
||||
const [sourcePicked, setSourcePicked] = useState(false);
|
||||
const [desktopNudgeDismissedFor, setDesktopNudgeDismissedFor] = useState<string | null>(null);
|
||||
const modelSourceContainer = useRef<HTMLDivElement>(null);
|
||||
const [setupNameConflict, setSetupNameConflict] = useState<string | null>(null);
|
||||
const [gatewayConnection, setGatewayConnection] = useState<{
|
||||
companyId: string; adapterType: string; binding: AiConnectionBinding;
|
||||
@@ -1429,6 +1434,15 @@ function OnboardingWizardInner({
|
||||
&& !selectedSavedKey && (restoredSetup.adapterConfig.env as Record<string, unknown> | undefined)?.[apiKeyEnvKeyFor(adapterType)];
|
||||
const connectStepReady = Boolean(setupPrepared || createdAgentId) && sourceSelected && !adapterEnvLoading && !savedKeys.loading && runnerDiscoveryReady && !browserSignInUnavailable && connectionModelReady;
|
||||
|
||||
const desktopOnboardingDestination = cloudInstance && mobileOnboardingViewport
|
||||
? cloudDesktopOnboardingUrl(cloudInstance, window.location.origin)
|
||||
: null;
|
||||
const mobileDesktopHandoffAvailable = Boolean(desktopOnboardingDestination
|
||||
&& createdCompanyId && !sourcePicked && !setupAgentId && !createdAgentId
|
||||
&& desktopNudgeDismissedFor !== createdCompanyId);
|
||||
const mobileDesktopHandoffAvailableRef = useRef(mobileDesktopHandoffAvailable);
|
||||
mobileDesktopHandoffAvailableRef.current = mobileDesktopHandoffAvailable;
|
||||
|
||||
useEffect(() => {
|
||||
if (step !== 3 || !createdCompanyId || !setupAgentId || createdAgentId || setupPrepared
|
||||
|| preparingSetup.current.has(createdCompanyId) || setupError) return;
|
||||
@@ -1449,7 +1463,7 @@ function OnboardingWizardInner({
|
||||
useEffect(() => {
|
||||
if (step !== 3 || !createdCompanyId || !adapterRegistryLoaded || setupAgentId || createdAgentId
|
||||
|| setupPrepared || preparingSetup.current.has(createdCompanyId) || earlySetupTried.current.has(createdCompanyId)
|
||||
|| setupError) return;
|
||||
|| setupError || mobileDesktopHandoffAvailable) return;
|
||||
const companyId = createdCompanyId;
|
||||
earlySetupTried.current.add(companyId);
|
||||
preparingSetup.current.add(companyId);
|
||||
@@ -1457,7 +1471,7 @@ function OnboardingWizardInner({
|
||||
void (async () => {
|
||||
if ((await agentsApi.list(companyId)).some(agent => agent.status !== "terminated")) return null;
|
||||
const provisionalAdapter = disabledTypes.has("process") ? recommendedAdapters[0]?.type : "process";
|
||||
if (!provisionalAdapter || !stillTheSameCompany(companyId)) return null;
|
||||
if (!provisionalAdapter || !stillTheSameCompany(companyId) || mobileDesktopHandoffAvailableRef.current) return null;
|
||||
setSetupAgentId(id);
|
||||
return agentsApi.create(companyId, {
|
||||
setupId: id, name: AGENT_ROLE_LABELS[agentRole], appearance: agentAppearance,
|
||||
@@ -1477,10 +1491,11 @@ function OnboardingWizardInner({
|
||||
preparingSetup.current.delete(companyId);
|
||||
setSetupAttempt(attempt => attempt + 1);
|
||||
});
|
||||
}, [step, createdCompanyId, adapterRegistryLoaded, setupAgentId, createdAgentId, setupPrepared, setupError]);
|
||||
}, [step, createdCompanyId, adapterRegistryLoaded, setupAgentId, createdAgentId, setupPrepared, setupError, mobileDesktopHandoffAvailable]);
|
||||
|
||||
useEffect(() => {
|
||||
if (step !== 4 || !createdCompanyId || !agentName.trim() || !adapterRegistryLoaded
|
||||
|| mobileDesktopHandoffAvailable
|
||||
|| createdAgentId || setupPrepared || preparingSetup.current.has(createdCompanyId) || setupError
|
||||
|| (!sourceSelected && setupNameConflict === JSON.stringify([createdCompanyId, agentName.trim().toLowerCase()]))) return;
|
||||
const companyId = createdCompanyId;
|
||||
@@ -1505,7 +1520,7 @@ function OnboardingWizardInner({
|
||||
const provisionalAdapter = disabledTypes.has("process") ? recommendedAdapters[0]?.type : "process";
|
||||
if (!sourceSelected && !provisionalAdapter) throw new Error("No agent adapters are available on this instance.");
|
||||
const createAdapter = sourceSelected ? adapterType : provisionalAdapter!;
|
||||
if (!stillTheSameCompany(companyId)) return null;
|
||||
if (!stillTheSameCompany(companyId) || mobileDesktopHandoffAvailableRef.current) return null;
|
||||
setSetupAgentId(id);
|
||||
return agentsApi.create(companyId, {
|
||||
setupId: id, name: agentName.trim() || AGENT_ROLE_LABELS[agentRole], appearance: agentAppearance,
|
||||
@@ -1563,7 +1578,7 @@ function OnboardingWizardInner({
|
||||
preparingSetup.current.delete(companyId);
|
||||
setSetupAttempt(attempt => attempt + 1);
|
||||
});
|
||||
}, [step, createdCompanyId, agentName, adapterRegistryLoaded, sourceSelected, setupNameConflict, runnerDiscoveryReady, createdAgentId, setupPrepared, setupAttempt]);
|
||||
}, [step, createdCompanyId, agentName, adapterRegistryLoaded, sourceSelected, setupNameConflict, runnerDiscoveryReady, createdAgentId, setupPrepared, setupAttempt, mobileDesktopHandoffAvailable]);
|
||||
|
||||
/**
|
||||
* Whether this step has a sign-in to do before it can hire.
|
||||
@@ -3347,7 +3362,13 @@ function OnboardingWizardInner({
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
{mobileDesktopHandoffAvailable && createdCompanyId && desktopOnboardingDestination && (
|
||||
<MobileDesktopNudge key={createdCompanyId} destination={desktopOnboardingDestination} onDismiss={() => {
|
||||
setDesktopNudgeDismissedFor(createdCompanyId);
|
||||
modelSourceContainer.current?.querySelector<HTMLElement>('[role="radio"]')?.focus();
|
||||
}} />
|
||||
)}
|
||||
<div ref={modelSourceContainer}>
|
||||
<ModelSourceTiles
|
||||
label="Model source"
|
||||
sources={recommendedAdapters.map((opt) => ({
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { useEffect, useId, useRef, useState, useSyncExternalStore } from "react";
|
||||
import { Check, Copy, Monitor } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { copyTextToClipboard } from "@/lib/clipboard";
|
||||
|
||||
const DESKTOP_WIDTH = "(min-width: 40rem)";
|
||||
|
||||
function subscribeToViewport(notify: () => void) {
|
||||
const query = window.matchMedia?.(DESKTOP_WIDTH);
|
||||
query?.addEventListener("change", notify);
|
||||
return () => query?.removeEventListener("change", notify);
|
||||
}
|
||||
|
||||
export function useMobileOnboardingViewport() {
|
||||
return useSyncExternalStore(
|
||||
subscribeToViewport,
|
||||
() => window.matchMedia?.(DESKTOP_WIDTH).matches === false,
|
||||
() => false,
|
||||
);
|
||||
}
|
||||
|
||||
export function MobileDesktopNudge({ destination, onDismiss }: { destination: string; onDismiss: () => void }) {
|
||||
const headingId = useId();
|
||||
const handoffId = useId();
|
||||
const linkId = useId();
|
||||
const linkRef = useRef<HTMLInputElement>(null);
|
||||
const handoffRef = useRef<HTMLDivElement>(null);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [copyState, setCopyState] = useState<"idle" | "copied" | "manual">("idle");
|
||||
|
||||
useEffect(() => {
|
||||
if (expanded) handoffRef.current?.scrollIntoView({ block: "nearest" });
|
||||
}, [expanded]);
|
||||
|
||||
async function copyLink() {
|
||||
try {
|
||||
await copyTextToClipboard(destination);
|
||||
setCopyState("copied");
|
||||
} catch {
|
||||
setCopyState("manual");
|
||||
linkRef.current?.focus();
|
||||
linkRef.current?.select();
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section aria-labelledby={headingId} className="flex flex-col gap-3 rounded-lg border bg-muted/40 p-3 text-left sm:hidden">
|
||||
<div className="flex items-start gap-3">
|
||||
<Monitor className="size-5 shrink-0 text-muted-foreground" aria-hidden="true" />
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<h2 id={headingId} className="text-sm font-medium text-foreground">Setup is easier on desktop</h2>
|
||||
<p className="text-sm text-muted-foreground">Especially if you need to sign in or paste a key.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-1">
|
||||
<Button type="button" variant="outline" className="h-(--sz-44px) px-2" aria-controls={handoffId} aria-expanded={expanded} onClick={() => setExpanded((open) => !open)}>
|
||||
Continue on desktop
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" className="h-(--sz-44px) px-2" onClick={onDismiss}>Keep going here</Button>
|
||||
</div>
|
||||
<div id={handoffId} ref={handoffRef} hidden={!expanded}>
|
||||
{expanded && (
|
||||
<div className="flex flex-col gap-2 border-t pt-3">
|
||||
<label htmlFor={linkId} className="text-sm text-muted-foreground">Open this link on your computer and sign in with the same account. You may need to re-enter setup choices.</label>
|
||||
<Input id={linkId} ref={linkRef} readOnly value={destination} aria-label="Desktop setup link" className="text-base" onFocus={(event) => event.currentTarget.select()} />
|
||||
<Button type="button" variant="outline" className="h-(--sz-44px) self-start" onClick={() => void copyLink()}>
|
||||
{copyState === "copied" ? <Check aria-hidden="true" /> : <Copy aria-hidden="true" />}
|
||||
{copyState === "copied" ? "Link copied" : "Copy setup link"}
|
||||
</Button>
|
||||
<span role="status" className="sr-only">{copyState === "copied" ? "Desktop setup link copied." : ""}</span>
|
||||
{copyState === "manual" && <p role="status" className="text-sm text-muted-foreground">Automatic copy is unavailable. Copy the selected link manually.</p>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -108,7 +108,7 @@ export function Stepper({
|
||||
onJumpToStep?: (target: number) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="mb-11 flex items-center justify-center gap-2">
|
||||
<div className="mb-11 flex items-center justify-center">
|
||||
{Array.from({ length: total }, (_, index) => index + 1).map((segment) => {
|
||||
const jumpable = Boolean(canJumpToStep?.(segment) && onJumpToStep);
|
||||
return (
|
||||
@@ -120,16 +120,18 @@ export function Stepper({
|
||||
disabled={!jumpable}
|
||||
onClick={() => jumpable && onJumpToStep?.(segment)}
|
||||
className={cn(
|
||||
// Dots, not bars: three of them, keeping the bar strip's gap so
|
||||
// the rhythm is unchanged. A full-width bar implied a continuous
|
||||
// quantity — how much of the arc is done — which three discrete
|
||||
// steps do not have. At 6px they carry the row on their own now
|
||||
// that no label sits under them.
|
||||
"size-1.5 shrink-0 rounded-full transition-colors",
|
||||
segment <= step ? "bg-foreground" : "bg-border",
|
||||
"grid h-1.5 w-3.5 shrink-0 place-items-center rounded-full",
|
||||
jumpable ? "cursor-pointer" : "cursor-default",
|
||||
)}
|
||||
/>
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"size-1.5 rounded-full transition-colors",
|
||||
segment <= step ? "bg-foreground" : "bg-border",
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{/* Out of flow, so it neither takes a row nor picks up the gap. */}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { CloudInstanceHealthStatus } from "@/api/health";
|
||||
import { cloudDesktopOnboardingUrl } from "./cloud-onboarding-handoff";
|
||||
|
||||
const cloud: CloudInstanceHealthStatus = {
|
||||
managed: true,
|
||||
managedBy: "paperclip-cloud",
|
||||
stackSlug: "example-workspace",
|
||||
cloudBaseUrl: "https://my.paperclip.app/control-plane",
|
||||
};
|
||||
const canonicalOrigin = "https://example-workspace.paperclip.app";
|
||||
const alias = "https://old-workspace.paperclip.app";
|
||||
|
||||
describe("Cloud desktop onboarding link", () => {
|
||||
it("uses the canonical HTTPS tenant rather than the current alias or fixture host", () => {
|
||||
const claimed = { ...cloud, runtimeIdentity: { canonicalOrigin, stackSlug: "example-workspace" } };
|
||||
expect(cloudDesktopOnboardingUrl(claimed, alias)).toBe(canonicalOrigin + "/onboarding");
|
||||
expect(cloudDesktopOnboardingUrl(claimed, "http://127.0.0.1:3811")).toBe(canonicalOrigin + "/onboarding");
|
||||
});
|
||||
|
||||
it("uses the current HTTPS tenant for older stacks without runtime identity", () => {
|
||||
expect(cloudDesktopOnboardingUrl(cloud, alias)).toBe(alias + "/onboarding");
|
||||
});
|
||||
|
||||
it.each([
|
||||
"https://example-workspace.paperclip.app/invite/secret",
|
||||
"https://example-workspace.paperclip.app/?token=secret",
|
||||
"https://example-workspace.paperclip.app/#secret",
|
||||
"https://someone:secret@example-workspace.paperclip.app",
|
||||
"http://example-workspace.paperclip.app",
|
||||
"https://localhost",
|
||||
"https://my.paperclip.app",
|
||||
"javascript:alert(1)",
|
||||
])("does not use invalid or non-tenant runtime origin %s", (invalidOrigin) => {
|
||||
const claimed = { ...cloud, runtimeIdentity: { canonicalOrigin: invalidOrigin, stackSlug: "example-workspace" } };
|
||||
expect(cloudDesktopOnboardingUrl(claimed, alias)).toBe(alias + "/onboarding");
|
||||
});
|
||||
|
||||
it("does not generate local or control-plane handoff URLs for real Cloud tenants", () => {
|
||||
expect(cloudDesktopOnboardingUrl(cloud, "http://127.0.0.1:3811")).toBeNull();
|
||||
expect(cloudDesktopOnboardingUrl(cloud, "https://localhost")).toBeNull();
|
||||
expect(cloudDesktopOnboardingUrl(cloud, "https://my.paperclip.app")).toBeNull();
|
||||
});
|
||||
|
||||
it("does not fall back to localhost even if a partial Cloud response has no control plane", () => {
|
||||
expect(cloudDesktopOnboardingUrl({ ...cloud, cloudBaseUrl: null }, "http://127.0.0.1:3811")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { CloudInstanceHealthStatus } from "@/api/health";
|
||||
import { cloudAppUrl } from "./cloudLinks";
|
||||
|
||||
function parseOrigin(value: string | undefined | null): URL | null {
|
||||
if (!value) return null;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
if (url.username || url.password || url.pathname !== "/" || url.search || url.hash) return null;
|
||||
return url;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function isLoopback(url: URL): boolean {
|
||||
const host = url.hostname.replace(/\.$/, "");
|
||||
return host === "localhost" || host.endsWith(".localhost") || /^127\.[\d.]+$/.test(host) || host === "[::1]";
|
||||
}
|
||||
|
||||
export function cloudDesktopOnboardingUrl(cloud: CloudInstanceHealthStatus, browserOrigin: string): string | null {
|
||||
const controlPlane = cloudAppUrl(cloud.cloudBaseUrl, "/");
|
||||
const controlPlaneOrigin = controlPlane ? new URL(controlPlane).origin : null;
|
||||
const usableTenantOrigin = (url: URL | null) => url?.protocol === "https:"
|
||||
&& !isLoopback(url)
|
||||
&& url.origin !== controlPlaneOrigin;
|
||||
const canonical = parseOrigin(cloud.runtimeIdentity?.canonicalOrigin);
|
||||
if (canonical && usableTenantOrigin(canonical)) return new URL("/onboarding", canonical).href;
|
||||
|
||||
const browser = parseOrigin(browserOrigin);
|
||||
if (!browser) return null;
|
||||
if (usableTenantOrigin(browser)) return new URL("/onboarding", browser).href;
|
||||
|
||||
return null;
|
||||
}
|
||||
Reference in new issue
Block a user