/** Standalone private required-human UI. Never runs inside Playwright Test and * never automates or imitates the external Grok desktop application. */ import { lstat, readFile } from "node:fs/promises"; import { chromium, test, type Browser, type BrowserContext, type Page } from "@playwright/test"; import { readValidatedPublicOriginReceipt } from "../chat-public-origin.js"; import { buildGrokAccessPrompt, buildGrokRoutinePrompt } from "../../../ui/src/lib/grok-bot-setup-prompt.js"; import type { GrokConnection, GrokInvitation } from "../../../packages/shared/src/grok-bot.js"; import type { McpConnectionRequest, McpDotPairingPreview } from "../../../packages/shared/src/public-mcp.js"; import { grokOperatorInputMatches, grokConsentUrlAllowed, grokCallbackOriginAllowed, type GrokOperatorInput, type GrokOperatorReceipt } from "./runtime-grok-operator-contract.js"; const esc = (s: string) => s.replace(/[&<>"']/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]!)); async function pane(page: Page, title: string, body: string, checks: string[], button: string) { await page.setContent(`
Attempt ${esc(i.attemptId)} · Operator ${esc(i.operatorRef)}
Existing Bot: ${esc(i.botName)} · authorization reference ${esc(i.botAuthorizationRef)}
Paperclip person ${esc(i.personName)} (${esc(i.personId)}), company ${esc(i.companyName)} (${esc(i.companyId)}).
`; const common = { operation: i.operation, executionId: i.executionId, attemptId: i.attemptId, companyId: i.companyId, personId: i.personId, operatorRef: i.operatorRef, botAuthorizationRef: i.botAuthorizationRef, processIsolation: true, testRunnerAttached: false, humanSelectedAuthorizedBot: true, publicPersonMatched: true, privateStorageClean: true, clipboardClean: true } as const; if (i.operation === "availability") { await pane(operator, "Required Grok operator availability", identity + "This is a required human prerequisite, before the canonical model request. No provider setup or consent has occurred. Presence must be confirmed within 15 seconds.
", ["I am the selected authorized operator of this exact existing Grok desktop Bot.", "I am available for this attempt and can use the real Bot and its OAuth browser flow; no substitute Bot or simulated receipt will be used."], "Confirm availability"); await humanConfirm(operator, 15000); return common; } const resumePath = `/api/companies/${i.companyId}/grok-invitations`, route = (id: string) => `/api/companies/${i.companyId}/agents/${id}/grok-binding`; product = await context.newPage(); let invitation = await jsonIn the real Grok desktop app, open this exact existing Bot and send ONLY these actual product-generated access instructions. Never send the pairing code to Bot chat.
Let the Bot initiate its real custom MCP OAuth flow. Paste the resulting Paperclip consent-page URL below; this private fixture-person browser will open it. Do not paste a callback URL or credentials.
`, ["I sent these actual instructions to the selected authorized existing Bot, and the URL comes from that Bot's actual OAuth flow."], "Open actual consent page"); await humanConfirm(operator, 150000); const consentUrl = await operator.locator("#consent-url").inputValue(); ownedClipboard.add(consentUrl); if (!grokConsentUrlAllowed(consentUrl, i.publicOrigin)) throw new Error("Operator supplied a foreign or unsupported consent URL"); const requestId = new URL(consentUrl).pathname.split("/").at(-1)!, requestPrefix = new URL(consentUrl).pathname.startsWith("/dot-connect/") ? "/api/dot-mcp/requests" : "/api/mcp/requests", request = await jsonActual request client: ${esc(request.clientName)}. Actual callback origin: ${esc(request.redirectOrigin)}.
Confirm this is the real selected Grok desktop Bot's pending connection. This approval only authorizes that exact callback origin for the real OAuth return.
`, ["I checked the real Bot's OAuth browser request and approve this exact client and callback origin."], "Review actual Paperclip consent"); await humanConfirm(operator, 60000); callbackOrigin = request.redirectOrigin; const consent = await context.newPage(); await consent.goto(consentUrl); const previewPending = consent.waitForResponse(r => r.url() === `${i.publicOrigin}${requestPrefix}/${requestId}/dot-pairing/preview` && r.request().method() === "POST" && r.ok()); await consent.getByLabel("Pairing code", { exact: true }).fill(pairingCode); const previewResponse = await previewPending; const preview = await previewResponse.json() as McpDotPairingPreview; if (preview.providerKind !== "grok_bot" || preview.company.id !== i.companyId || preview.agent.id !== agentId || preview.authorizingPerson !== i.personName) throw new Error("Actual consent preview selected another provider/company/agent/person"); const consentPending = consent.waitForResponse(r => r.url() === `${i.publicOrigin}${requestPrefix}/${requestId}/dot-pairing` && r.request().method() === "POST", { timeout: 120000 }); await pane(operator, "Approve only the reviewed real Paperclip form", identity + "The real Paperclip OAuth page is open in the other tab with the private code entered. Review its Company, Agent and Authorized by fields. Click Allow agent connection THERE if correct. The code never goes to Bot chat. Then return to this operator tab.
", [], "I reviewed the real consent tab"); await consent.bringToFront(); const consentResponse = await consentPending; if (!consentResponse.ok() || JSON.stringify(consentResponse.request().postDataJSON()) !== JSON.stringify({ pairingCode })) throw new Error("Actual human pairing consent did not submit the exact generated code"); const result = await consentResponse.json() as { redirectUrl?: string }; if (!result.redirectUrl || new URL(result.redirectUrl).origin !== callbackOrigin) throw new Error("Actual OAuth return escaped the operator-approved callback origin"); ownedClipboard.add(result.redirectUrl); for (const key of ["code", "state"]) { const value = new URL(result.redirectUrl).searchParams.get(key); if (value) ownedClipboard.add(value); } const publicPerson = await json<{ user: { id: string } }>(context, i.publicOrigin, "/api/auth/get-session"); if (publicPerson.user.id !== i.personId) throw new Error("Public authorizing person changed during consent"); await product.goto(`${i.publicOrigin}/${i.prefix}/agents/${agentId}/runtime`); const section = product.getByRole("region", { name: "Grok Bot connection", exact: true }); await section.getByText(/Agent access connected/).waitFor(); await section.getByLabel("Bot name in Grok", { exact: true }).fill(i.botName); const routine = await generatedPrompt(product, "Copy routine instructions"); if (routine !== buildGrokRoutinePrompt(bindingId, i.botName) || routine.includes(pairingCode) || routine.includes(i.webhookKey!)) throw new Error("Actual generated routine instructions are not secret-free and exactly target-bound"); ownedClipboard.add(routine); await pane(operator, "Enable the real same-Bot routine", identity + `Send these actual product-generated routine instructions to the SAME existing Bot. Reuse only the explicitly designated disposable routine; inspect its real Webhook panel and compare it with the selected credentials below. No model work or readiness is proven by this acknowledgement.
Selected webhook URL
Selected webhook key
`, ["I sent these actual routine instructions to the same authorized Bot; I did not send the pairing code or Paperclip credentials to Bot chat.", "I inspected the actual designated routine's Webhook panel and its URL/key match these selected credentials; no unrelated routine was adopted."], "Record human handoff only"); await humanConfirm(operator, 120000); if (privacyViolation) throw new Error("Pairing authority attempted to leave the actual public Paperclip form"); return { ...common, agentId, bindingId, productInvitationUi: true, accessInstructionsDelivered: true, routineInstructionsDelivered: true, publicPairingConsentSubmitted: true, publicCompanyAgentMatched: true, clientCallbackApproved: true, pairingCodeConfinedToPublicForm: true }; } finally { clearTimeout(deadline); process.removeListener("SIGTERM", stop); try { if (ownedClipboard.size && context) { const clipboardPage = product && !product.isClosed() ? product : await context.newPage(); if (new URL(clipboardPage.url()).origin !== i.publicOrigin) await clipboardPage.goto(i.publicOrigin); const current = await clipboardPage.evaluate(() => navigator.clipboard.readText()); if (ownedClipboard.has(current)) await clipboardPage.evaluate(() => navigator.clipboard.writeText("")); } } finally { try { await context?.clearCookies(); } finally { try { await context?.close(); } finally { await browser?.close(); pairingCode = ""; ownedClipboard.clear(); } } } } } main().then(receipt => process.stdout.write(JSON.stringify(receipt))).catch(() => { process.stderr.write("Grok private operator callback failed; pairing, OAuth and browser diagnostics withheld"); process.exitCode = 1; });