Skip to content

The Open Standard for Generative UI

Add Grok Build interactions and workspace selection (#937)

Visharad Kashyapd04a2772bfef
diff --git a/examples/harnesses/grok-build/.env.example b/examples/harnesses/grok-build/.env.example
index acd68f322..89b115682 100644
--- a/examples/harnesses/grok-build/.env.example
+++ b/examples/harnesses/grok-build/.env.example
@@ -4,7 +4,8 @@
# Grok Build executable. Defaults to `grok` on PATH.
# GROK_BUILD_BIN=/absolute/path/to/grok
-# Workspace the coding agent can inspect and modify. Defaults to this example directory.
+# Workspace the coding agent can inspect and modify. If omitted, `pnpm dev` prompts for it.
+# You can also pass it at launch: `pnpm dev -- /absolute/path/to/project`.
# GROK_BUILD_CWD=/absolute/path/to/project
# Optional model override. When omitted, the installed Grok Build CLI chooses its configured default.
diff --git a/examples/harnesses/grok-build/README.md b/examples/harnesses/grok-build/README.md
index e854266df..e578bc405 100644
--- a/examples/harnesses/grok-build/README.md
+++ b/examples/harnesses/grok-build/README.md
@@ -11,6 +11,8 @@ stdio mode for persistent coding sessions, live reasoning, tool activity, and ca
- One long-lived `grok agent --no-leader stdio` process hosting an isolated Grok session for each
OpenUI thread.
- ACP text, reasoning, and tool-call updates translated to AG-UI SSE events.
+- Blocking Grok Q&A and plan-approval requests rendered as browser dialogs, with responses sent
+ back over ACP so the same agent turn can continue.
- Retry-safe OpenUI output buffering: valid candidates are checkpointed across retries, the final
candidate is validated against the generated component schema, then revealed in paced chunks.
- One bounded, parser-guided correction turn when Grok's final OpenUI has syntax errors or unresolved
@@ -23,7 +25,7 @@ stdio mode for persistent coding sessions, live reasoning, tool activity, and ca
## Prerequisites
- Node.js 22 and pnpm 9
-- The released `grok` CLI on `PATH`
+- The latest stable `grok` CLI on `PATH`
- A Grok login or `XAI_API_KEY`
Install Grok Build by following the
@@ -45,16 +47,19 @@ Install dependencies from the OpenUI repository root:
pnpm install
```
-Then start the example:
+Then start the example and choose the project Grok Build should work in:
```bash
cd examples/harnesses/grok-build
cp .env.example .env.local
-pnpm dev
+pnpm dev -- /absolute/path/to/your/project
```
-Open [http://localhost:3000](http://localhost:3000). To let Grok work on a different project, set
-`GROK_BUILD_CWD` in `.env.local` before starting the server.
+Running `pnpm dev` without a path prompts for the workspace in an interactive terminal. You can
+also set `GROK_BUILD_CWD=/absolute/path` in `.env.local` or the shell to skip the prompt. The
+launcher validates the directory and prints the resolved workspace before starting Next.js.
+
+Open [http://localhost:3000](http://localhost:3000) after the server starts.
## How it works
@@ -62,6 +67,7 @@ Open [http://localhost:3000](http://localhost:3000). To let Grok work on a diffe
Browser / OpenUI AgentInterface
| localStorage threads + transcript
| POST /api/chat { threadId, messages }
+ | GET/POST /api/interactions (questions + plan decisions)
v
Next.js route
| latest user turn
@@ -98,6 +104,12 @@ retry_state -> checkpoint valid output + rotate Thinking state
prompt response -> validate, optionally correct once, then paced TEXT_MESSAGE_CONTENT + END
```
+Grok's `x.ai/ask_user_question` and `x.ai/exit_plan_mode` extension requests block the current ACP
+turn until the user responds. The server registers each request in a short-lived in-memory broker;
+the active browser thread polls `/api/interactions`, presents either the structured question form or
+plan review, and posts the selected outcome. Cancelling the browser turn resolves any outstanding
+interaction with a safe fallback so the ACP process cannot remain parked indefinitely.
+
Grok Build may emit progress prose and multiple full answers during one ACP prompt when an xAI
request is retried. AG-UI text deltas are append-only, so sending those candidates immediately
would concatenate them into invalid OpenUI Lang. This harness keeps only the latest line-start
@@ -113,28 +125,33 @@ The browser transcript persists user and assistant text, matching the lightweigh
Reasoning and tool cards are streamed live but are not restored after a page reload. Deleting an
OpenUI browser thread removes its local transcript; it does not delete Grok Build's on-disk session.
-Grok's interactive ask-user and exit-plan-mode ACP extension requests are cancelled immediately
-because this demo does not implement their dedicated response UI. Normal tool permissions are
-auto-approved when `GROK_BUILD_ALWAYS_APPROVE=true`.
+Normal tool permissions are auto-approved when `GROK_BUILD_ALWAYS_APPROVE=true`. This is separate
+from conversational questions and plan approval: those always require an explicit answer in the
+browser dialog.
## Configuration
-| Environment variable | Default | Purpose |
-| ----------------------------- | ------------------------ | --------------------------------------------------- |
-| `XAI_API_KEY` | existing `grok login` | Non-interactive Grok authentication |
-| `GROK_BUILD_BIN` | `grok` | Grok Build executable |
-| `GROK_BUILD_CWD` | this example's directory | Workspace the coding agent can inspect and modify |
-| `GROK_BUILD_MODEL` | CLI-configured default | Optional model override |
-| `GROK_BUILD_REASONING_EFFORT` | CLI-configured default | Optional reasoning-effort override |
-| `GROK_BUILD_ALWAYS_APPROVE` | `true` | Auto-approve Grok tool execution in the web harness |
+| Environment variable | Default | Purpose |
+| ----------------------------- | ---------------------- | --------------------------------------------------- |
+| `XAI_API_KEY` | existing `grok login` | Non-interactive Grok authentication |
+| `GROK_BUILD_BIN` | `grok` | Grok Build executable |
+| `GROK_BUILD_CWD` | launch prompt / cwd | Workspace the coding agent can inspect and modify |
+| `GROK_BUILD_MODEL` | CLI-configured default | Optional model override |
+| `GROK_BUILD_REASONING_EFFORT` | CLI-configured default | Optional reasoning-effort override |
+| `GROK_BUILD_ALWAYS_APPROVE` | `true` | Auto-approve Grok tool execution in the web harness |
## Project layout
```text
examples/harnesses/grok-build/
+|- scripts/launch.mjs # Launch-time workspace selector + validation
|- src/app/page.tsx # OpenUI AgentInterface
|- src/app/api/chat/route.ts # AG-UI SSE route
+|- src/app/api/interactions/route.ts # Pending-interaction read/response route
+|- src/components/grok-build-interaction-dialog.tsx # Question + plan UI
+|- src/hooks/use-grok-build-interaction.ts # Active-thread interaction polling
|- src/lib/grok-build-acp.ts # Grok ACP process, auth, sessions, prompts, cancellation
+|- src/lib/grok-build-interactions.ts # ACP reverse-request broker and validation
|- src/lib/grok-build-stream.ts # ACP session updates to AG-UI events
|- src/lib/openui-output.ts # Retry-safe validation, fallback, and paced output chunks
|- src/lib/grok-build-chat.ts # AgentInterface LLM + storage adapters
@@ -152,4 +169,4 @@ Do not expose this server to a network as-is. Add authentication and authorizati
inside an OS-level sandbox or container, restrict network access and credentials, and configure
Grok's permission policy for the deployment. Setting `GROK_BUILD_ALWAYS_APPROVE=false` makes this
demo cancel permission requests because `AgentInterface` does not currently provide a Grok-specific
-approval/resume UI.
+tool-permission approval UI; question and plan dialogs continue to work independently.
diff --git a/examples/harnesses/grok-build/package.json b/examples/harnesses/grok-build/package.json
index 62ef7b120..581475e6f 100644
--- a/examples/harnesses/grok-build/package.json
+++ b/examples/harnesses/grok-build/package.json
@@ -3,16 +3,16 @@
"version": "0.1.0",
"private": true,
"scripts": {
- "dev": "next dev --webpack",
+ "dev": "node scripts/launch.mjs dev",
"build": "next build --webpack",
- "start": "next start",
+ "start": "node scripts/launch.mjs start",
"lint": "eslint",
"test": "vitest run",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@ag-ui/core": "^0.0.53",
- "@agentclientprotocol/sdk": "0.10.0",
+ "@agentclientprotocol/sdk": "1.3.0",
"@openuidev/lang-core": "workspace:*",
"@openuidev/react-headless": "workspace:*",
"@openuidev/react-lang": "workspace:*",
diff --git a/examples/harnesses/grok-build/scripts/launch.mjs b/examples/harnesses/grok-build/scripts/launch.mjs
new file mode 100644
index 000000000..b866c40fd
--- /dev/null
+++ b/examples/harnesses/grok-build/scripts/launch.mjs
@@ -0,0 +1,73 @@
+// Resolve the coding agent's workspace before starting Next. Grok Build's
+// filesystem and shell tools use GROK_BUILD_CWD, so the harness must not
+// silently confine every session to this example directory.
+//
+// pnpm dev -- /path/to/project # explicit workspace
+// pnpm dev # interactive prompt
+// GROK_BUILD_CWD=/path pnpm dev # environment override
+import { spawn } from "node:child_process";
+import { existsSync, statSync } from "node:fs";
+import { resolve } from "node:path";
+import { stdin, stdout } from "node:process";
+import { createInterface } from "node:readline/promises";
+
+const NEXT_ARGS = {
+ dev: ["dev", "--webpack"],
+ start: ["start"],
+};
+
+const mode = process.argv[2];
+if (!NEXT_ARGS[mode]) {
+ console.error(`launch.mjs: unknown mode "${mode}" (expected: dev | start)`);
+ process.exit(1);
+}
+
+async function chooseWorkspace() {
+ const launchArgs = process.argv.slice(3);
+ const fromArg = launchArgs[0] === "--" ? launchArgs[1] : launchArgs[0];
+ if (fromArg) {
+ if (fromArg.startsWith("-")) {
+ console.error(`launch.mjs: "${fromArg}" looks like a flag, not a path.`);
+ console.error(
+ 'Pass the workspace after a space-separated "--", e.g.: pnpm dev -- /absolute/path',
+ );
+ process.exit(1);
+ }
+ return fromArg;
+ }
+ if (process.env.GROK_BUILD_CWD) return process.env.GROK_BUILD_CWD;
+ if (stdin.isTTY) {
+ const rl = createInterface({ input: stdin, output: stdout });
+ const answer = (
+ await rl.question(`\nWorkspace Grok Build may read, run, and edit in [${process.cwd()}]: `)
+ ).trim();
+ rl.close();
+ return answer || process.cwd();
+ }
+ return process.cwd();
+}
+
+const workspace = resolve(await chooseWorkspace());
+if (!existsSync(workspace) || !statSync(workspace).isDirectory()) {
+ console.error(`launch.mjs: not a directory: ${workspace}`);
+ console.error("Pass an existing directory, e.g.: pnpm dev -- /absolute/path");
+ process.exit(1);
+}
+
+console.log(`\n Grok Build workspace: ${workspace}`);
+console.log(" Filesystem and shell tools act here and may reach paths outside it.\n");
+
+const child = spawn("next", NEXT_ARGS[mode], {
+ stdio: "inherit",
+ env: { ...process.env, GROK_BUILD_CWD: workspace },
+});
+
+child.on("error", (error) => {
+ console.error(`launch.mjs: failed to start Next.js: ${error.message}`);
+ process.exit(1);
+});
+
+child.on("exit", (code, signal) => {
+ if (signal) process.kill(process.pid, signal);
+ else process.exit(code ?? 0);
+});
diff --git a/examples/harnesses/grok-build/src/app/api/interactions/route.ts b/examples/harnesses/grok-build/src/app/api/interactions/route.ts
new file mode 100644
index 000000000..c6a2138d7
--- /dev/null
+++ b/examples/harnesses/grok-build/src/app/api/interactions/route.ts
@@ -0,0 +1,59 @@
+import {
+ respondToGrokBuildInteraction,
+ waitForGrokBuildInteractionChange,
+} from "@/lib/grok-build-interactions";
+import type { NextRequest } from "next/server";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+interface InteractionResponseBody {
+ interactionId?: string;
+ response?: unknown;
+ threadId?: string;
+}
+
+function noStoreJson(body: unknown, init?: ResponseInit): Response {
+ const headers = new Headers(init?.headers);
+ headers.set("Cache-Control", "no-store");
+ return Response.json(body, { ...init, headers });
+}
+
+export async function GET(request: NextRequest) {
+ const threadId = request.nextUrl.searchParams.get("threadId")?.trim();
+ if (!threadId) return noStoreJson({ error: "threadId is required." }, { status: 400 });
+ const afterInteractionId = request.nextUrl.searchParams.get("after")?.trim() || undefined;
+ const interaction = await waitForGrokBuildInteractionChange(
+ threadId,
+ afterInteractionId,
+ request.signal,
+ );
+ return noStoreJson({ interaction: interaction ?? null });
+}
+
+export async function POST(request: NextRequest) {
+ const body = (await request.json().catch(() => ({}))) as InteractionResponseBody;
+ const threadId = body.threadId?.trim();
+ const interactionId = body.interactionId?.trim();
+ if (!threadId || !interactionId || body.response === undefined) {
+ return noStoreJson(
+ { error: "threadId, interactionId, and response are required." },
+ { status: 400 },
+ );
+ }
+
+ try {
+ if (!respondToGrokBuildInteraction(threadId, interactionId, body.response)) {
+ return noStoreJson(
+ { error: "That Grok Build interaction is no longer pending." },
+ { status: 409 },
+ );
+ }
+ return noStoreJson({ ok: true });
+ } catch (error) {
+ return noStoreJson(
+ { error: error instanceof Error ? error.message : "Invalid interaction response." },
+ { status: 400 },
+ );
+ }
+}
diff --git a/examples/harnesses/grok-build/src/app/globals.css b/examples/harnesses/grok-build/src/app/globals.css
index a836e4cda..627d9bb95 100644
--- a/examples/harnesses/grok-build/src/app/globals.css
+++ b/examples/harnesses/grok-build/src/app/globals.css
@@ -11,3 +11,475 @@ body {
position: relative;
width: 100vw;
}
+
+.grok-interaction-backdrop {
+ align-items: center;
+ backdrop-filter: blur(6px);
+ background: rgb(0 0 0 / 58%);
+ display: flex;
+ inset: 0;
+ justify-content: center;
+ padding: 24px;
+ position: fixed;
+ z-index: 100;
+}
+
+.grok-interaction-backdrop,
+.grok-interaction-backdrop * {
+ box-sizing: border-box;
+}
+
+.grok-interaction-card {
+ background: var(--openui-popover-background, white);
+ border: 1px solid var(--openui-border-interactive, rgb(0 0 0 / 12%));
+ border-radius: 18px;
+ box-shadow: 0 28px 90px rgb(0 0 0 / 34%);
+ color: var(--openui-text-neutral-primary, #18181b);
+ display: flex;
+ flex-direction: column;
+ max-height: min(820px, calc(100vh - 48px));
+ max-width: 720px;
+ overflow: hidden;
+ outline: none;
+ width: 100%;
+}
+
+.grok-interaction-heading {
+ align-items: flex-start;
+ display: flex;
+ flex: 0 0 auto;
+ gap: 16px;
+ justify-content: space-between;
+ padding: 22px 24px 18px;
+}
+
+.grok-interaction-heading h2,
+.grok-interaction-heading p {
+ margin: 0;
+}
+
+.grok-interaction-heading h2 {
+ font: var(--openui-text-heading-sm, 650 20px/1.25 Inter, sans-serif);
+ letter-spacing: -0.015em;
+}
+
+.grok-interaction-eyebrow {
+ color: var(--openui-text-neutral-secondary, rgb(0 0 0 / 55%));
+ font: var(--openui-text-label-sm-heavy, 500 14px/1.25 Inter, sans-serif);
+ margin-bottom: 5px !important;
+}
+
+.grok-interaction-close {
+ align-items: center;
+ background: transparent;
+ border: 0;
+ border-radius: 8px;
+ color: var(--openui-text-neutral-secondary, currentColor);
+ cursor: pointer;
+ display: flex;
+ font-size: 24px;
+ height: 32px;
+ justify-content: center;
+ line-height: 1;
+ width: 32px;
+}
+
+.grok-interaction-close:hover {
+ background: var(--openui-sunk, rgb(0 0 0 / 5%));
+}
+
+.grok-interaction-close:focus-visible,
+.grok-button-primary:focus-visible,
+.grok-button-secondary:focus-visible,
+.grok-question-option:focus-within {
+ outline: 2px solid var(--openui-interactive-accent-default, #2563eb);
+ outline-offset: 2px;
+}
+
+.grok-question-list {
+ display: flex;
+ flex: 1 1 auto;
+ flex-direction: column;
+ gap: 22px;
+ min-height: 0;
+ overscroll-behavior: contain;
+ overflow: auto;
+ padding: 4px 24px 28px;
+ scrollbar-gutter: stable;
+}
+
+.grok-question-list::-webkit-scrollbar,
+.grok-plan-content::-webkit-scrollbar {
+ height: 8px;
+ width: 8px;
+}
+
+.grok-question-list::-webkit-scrollbar-thumb,
+.grok-plan-content::-webkit-scrollbar-thumb {
+ background: var(--openui-border-interactive, rgb(127 127 127 / 35%));
+ border-radius: 999px;
+}
+
+.grok-question {
+ border: 0;
+ margin: 0;
+ padding: 0;
+}
+
+.grok-question legend {
+ display: flex;
+ flex-direction: column;
+ font: var(--openui-text-body-sm-heavy, 600 14px/1.5 Inter, sans-serif);
+ gap: 2px;
+ margin-bottom: 10px;
+ padding: 0;
+ width: 100%;
+}
+
+.grok-question legend small {
+ color: var(--openui-text-neutral-secondary, rgb(0 0 0 / 55%));
+ font: var(--openui-text-body-xs, 400 12px/1.5 Inter, sans-serif);
+}
+
+.grok-question-options {
+ display: grid;
+ gap: 8px;
+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
+}
+
+.grok-question-option {
+ align-items: flex-start;
+ background: var(--openui-foreground, white);
+ border: 1px solid var(--openui-border-interactive, rgb(0 0 0 / 12%));
+ border-radius: 10px;
+ cursor: pointer;
+ display: flex;
+ gap: 10px;
+ min-height: 62px;
+ padding: 12px;
+ transition:
+ background-color 120ms ease,
+ border-color 120ms ease,
+ box-shadow 120ms ease;
+}
+
+.grok-question-option:has(input:checked) {
+ background: color-mix(
+ in srgb,
+ var(--openui-interactive-accent-default, #2563eb) 10%,
+ var(--openui-foreground, white)
+ );
+ border-color: var(--openui-interactive-accent-default, #2563eb);
+ box-shadow: 0 0 0 1px var(--openui-interactive-accent-default, #2563eb);
+}
+
+.grok-question-option:hover {
+ border-color: var(--openui-border-accent-emphasis, rgb(37 99 235 / 45%));
+}
+
+.grok-question-option > input {
+ accent-color: var(--openui-interactive-accent-default, #2563eb);
+ margin: 3px 0 0;
+}
+
+.grok-question-option > span {
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ gap: 2px;
+ min-width: 0;
+}
+
+.grok-question-option strong {
+ font: var(--openui-text-label-sm-heavy, 500 14px/1.25 Inter, sans-serif);
+}
+
+.grok-question-option small {
+ color: var(--openui-text-neutral-secondary, rgb(0 0 0 / 55%));
+ font: var(--openui-text-body-xs, 400 12px/1.5 Inter, sans-serif);
+}
+
+.grok-question-other {
+ display: grid;
+ gap: 8px;
+ grid-column: 1 / -1;
+ grid-template-columns: auto minmax(0, 1fr);
+ min-height: 0;
+}
+
+.grok-question-other-choice {
+ align-items: flex-start;
+ cursor: pointer;
+ display: flex;
+ gap: 10px;
+ padding-top: 8px;
+}
+
+.grok-question-other-choice input {
+ accent-color: var(--openui-interactive-accent-default, #2563eb);
+ margin: 2px 0 0;
+}
+
+.grok-question-other-input,
+.grok-plan-feedback textarea {
+ background: var(--openui-background, #f4f4f5);
+ border: 1px solid var(--openui-border-interactive, rgb(0 0 0 / 12%));
+ border-radius: 8px;
+ color: var(--openui-text-neutral-primary, currentColor);
+ font: var(--openui-text-body-sm, 400 14px/1.5 Inter, sans-serif);
+ outline: none;
+}
+
+.grok-question-other-input {
+ padding: 9px 11px;
+ width: 100%;
+}
+
+.grok-question-other-input:focus,
+.grok-plan-feedback textarea:focus {
+ border-color: var(--openui-interactive-accent-default, #2563eb);
+ box-shadow: 0 0 0 2px var(--openui-border-accent-emphasis, rgb(37 99 235 / 30%));
+}
+
+.grok-question-preview {
+ background: var(--openui-sunk, rgb(0 0 0 / 4%));
+ border: 1px solid var(--openui-border-default, rgb(0 0 0 / 6%));
+ border-radius: 10px;
+ color: var(--openui-text-neutral-primary, currentColor);
+ margin: 8px 0 0;
+ padding: 12px;
+}
+
+.grok-question-preview > span {
+ color: var(--openui-text-neutral-secondary, rgb(0 0 0 / 55%));
+ display: block;
+ font: var(--openui-text-label-xs-heavy, 600 11px/1.4 Inter, sans-serif);
+ margin-bottom: 6px;
+ text-transform: uppercase;
+}
+
+.grok-question-preview pre {
+ font: var(--openui-text-code-sm, 400 12px/1.5 monospace);
+ margin: 0;
+ overflow: auto;
+ white-space: pre-wrap;
+}
+
+.grok-plan-card {
+ max-width: 800px;
+}
+
+.grok-plan-document {
+ border: 1px solid var(--openui-border-default, rgb(0 0 0 / 8%));
+ border-radius: 12px;
+ display: flex;
+ flex: 1 1 auto;
+ flex-direction: column;
+ margin: 0 24px;
+ min-height: 0;
+ overflow: hidden;
+}
+
+.grok-plan-document-heading {
+ align-items: center;
+ background: var(--openui-sunk, rgb(0 0 0 / 4%));
+ border-bottom: 1px solid var(--openui-border-default, rgb(0 0 0 / 8%));
+ display: flex;
+ flex: 0 0 auto;
+ justify-content: space-between;
+ padding: 10px 12px;
+}
+
+.grok-plan-document-heading span {
+ font: var(--openui-text-label-sm-heavy, 600 13px/1.4 Inter, sans-serif);
+}
+
+.grok-plan-document-heading small {
+ color: var(--openui-text-neutral-secondary, rgb(0 0 0 / 55%));
+ font: var(--openui-text-body-xs, 400 12px/1.4 Inter, sans-serif);
+}
+
+.grok-plan-content {
+ background: var(--openui-sunk, rgb(0 0 0 / 4%));
+ color: var(--openui-text-neutral-primary, currentColor);
+ flex: 1 1 auto;
+ font: var(--openui-text-code-sm, 400 12px/1.55 monospace);
+ margin: 0;
+ min-height: 160px;
+ overflow: auto;
+ padding: 14px;
+ white-space: pre-wrap;
+}
+
+.grok-plan-feedback {
+ display: flex;
+ flex-direction: column;
+ font: var(--openui-text-label-sm-heavy, 500 14px/1.25 Inter, sans-serif);
+ gap: 6px;
+ margin: 18px 24px 0;
+}
+
+.grok-plan-feedback textarea {
+ padding: 10px 12px;
+ resize: vertical;
+}
+
+.grok-interaction-actions {
+ align-items: center;
+ background: var(--openui-popover-background, white);
+ border-top: 1px solid var(--openui-border-default, rgb(0 0 0 / 8%));
+ display: flex;
+ flex: 0 0 auto;
+ flex-wrap: wrap;
+ gap: 8px;
+ justify-content: flex-end;
+ padding: 14px 24px 18px;
+}
+
+.grok-button-primary,
+.grok-button-secondary {
+ border-radius: 9px;
+ cursor: pointer;
+ font: var(--openui-text-label-sm-heavy, 500 14px/1.25 Inter, sans-serif);
+ min-height: 38px;
+ padding: 9px 14px;
+}
+
+.grok-button-primary {
+ background: var(--openui-interactive-accent-default, #2563eb);
+ border: 1px solid transparent;
+ color: var(--openui-text-accent-primary, white);
+}
+
+.grok-button-primary:hover:not(:disabled) {
+ background: var(--openui-interactive-accent-hover, #1d4ed8);
+}
+
+.grok-button-secondary {
+ background: var(--openui-foreground, white);
+ border: 1px solid var(--openui-border-interactive, rgb(0 0 0 / 12%));
+ color: var(--openui-text-neutral-primary, currentColor);
+}
+
+.grok-button-secondary:hover:not(:disabled) {
+ background: var(--openui-sunk, rgb(0 0 0 / 4%));
+}
+
+.grok-button-primary:disabled,
+.grok-button-secondary:disabled,
+.grok-interaction-close:disabled {
+ cursor: default;
+ opacity: 0.5;
+}
+
+.grok-interaction-error,
+.grok-interaction-poll-error {
+ background: var(--openui-danger-background, rgb(220 38 38 / 10%));
+ color: var(--openui-text-danger-primary, #b91c1c);
+ font: var(--openui-text-body-xs, 400 12px/1.5 Inter, sans-serif);
+ margin: 0;
+ padding: 8px 10px;
+}
+
+.grok-interaction-error {
+ border-radius: 8px;
+ margin: 0 24px 12px;
+}
+
+.grok-interaction-poll-error {
+ border-radius: 8px;
+ bottom: 16px;
+ left: 50%;
+ position: absolute;
+ transform: translateX(-50%);
+ z-index: 90;
+}
+
+@media (max-width: 640px) {
+ .grok-interaction-backdrop {
+ align-items: flex-end;
+ padding: 0;
+ }
+
+ .grok-interaction-card {
+ border-bottom-left-radius: 0;
+ border-bottom-right-radius: 0;
+ max-height: calc(100dvh - max(16px, env(safe-area-inset-top)));
+ }
+
+ .grok-interaction-heading {
+ padding: 18px 18px 14px;
+ }
+
+ .grok-interaction-heading h2 {
+ font-size: 18px;
+ }
+
+ .grok-question-list {
+ gap: 20px;
+ padding: 4px 18px 24px;
+ }
+
+ .grok-question-options {
+ grid-template-columns: 1fr;
+ }
+
+ .grok-question-other {
+ grid-column: auto;
+ }
+
+ .grok-plan-document {
+ margin: 0 18px;
+ }
+
+ .grok-plan-document-heading small {
+ display: none;
+ }
+
+ .grok-plan-feedback {
+ margin: 16px 18px 0;
+ }
+
+ .grok-interaction-error {
+ margin: 0 18px 12px;
+ }
+
+ .grok-interaction-actions {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ padding: 12px 18px calc(14px + env(safe-area-inset-bottom));
+ }
+
+ .grok-interaction-actions button {
+ width: 100%;
+ }
+
+ .grok-question-submit,
+ .grok-plan-actions .grok-button-primary {
+ grid-column: 1 / -1;
+ order: -1;
+ }
+}
+
+@media (prefers-reduced-motion: no-preference) {
+ .grok-interaction-backdrop {
+ animation: grok-backdrop-in 140ms ease-out;
+ }
+
+ .grok-interaction-card {
+ animation: grok-dialog-in 180ms cubic-bezier(0.2, 0.8, 0.2, 1);
+ }
+}
+
+@keyframes grok-backdrop-in {
+ from {
+ opacity: 0;
+ }
+}
+
+@keyframes grok-dialog-in {
+ from {
+ opacity: 0;
+ transform: translateY(8px) scale(0.985);
+ }
+}
diff --git a/examples/harnesses/grok-build/src/app/page.tsx b/examples/harnesses/grok-build/src/app/page.tsx
index 9eceafe24..c08b0a681 100644
--- a/examples/harnesses/grok-build/src/app/page.tsx
+++ b/examples/harnesses/grok-build/src/app/page.tsx
@@ -1,14 +1,21 @@
"use client";
+import { GrokBuildInteractionDialog } from "@/components/grok-build-interaction-dialog";
+import { useGrokBuildInteraction } from "@/hooks/use-grok-build-interaction";
import { useTheme } from "@/hooks/use-system-theme";
import { createGrokBuildChatProps } from "@/lib/grok-build-chat";
import { AgentInterface } from "@openuidev/react-ui";
import { openuiChatLibrary } from "@openuidev/react-ui/genui-lib";
-import { useMemo } from "react";
+import { useMemo, useState } from "react";
export default function Page() {
const mode = useTheme();
- const { llm, storage } = useMemo(() => createGrokBuildChatProps(), []);
+ const [activeThreadId, setActiveThreadId] = useState<string>();
+ const { llm, storage } = useMemo(
+ () => createGrokBuildChatProps({ onThreadChange: setActiveThreadId }),
+ [],
+ );
+ const { error, interaction, respond, submitting } = useGrokBuildInteraction(activeThreadId);
return (
<div className="app-shell">
@@ -42,6 +49,17 @@ export default function Page() {
},
]}
/>
+ {interaction ? (
+ <GrokBuildInteractionDialog
+ key={interaction.id}
+ interaction={interaction}
+ error={error}
+ submitting={submitting}
+ onRespond={respond}
+ />
+ ) : error ? (
+ <p className="grok-interaction-poll-error">{error}</p>
+ ) : null}
</div>
);
}
diff --git a/examples/harnesses/grok-build/src/components/grok-build-interaction-dialog.tsx b/examples/harnesses/grok-build/src/components/grok-build-interaction-dialog.tsx
new file mode 100644
index 000000000..fda044009
--- /dev/null
+++ b/examples/harnesses/grok-build/src/components/grok-build-interaction-dialog.tsx
@@ -0,0 +1,435 @@
+"use client";
+
+import type {
+ GrokBuildInteraction,
+ GrokBuildInteractionResponse,
+ GrokBuildQuestion,
+} from "@/lib/grok-build-interactions";
+import { useEffect, useRef, useState, type RefObject } from "react";
+
+interface GrokBuildInteractionDialogProps {
+ error?: string;
+ interaction: GrokBuildInteraction;
+ onRespond: (response: GrokBuildInteractionResponse) => Promise<void>;
+ submitting: boolean;
+}
+
+type DialogPropsWithRef = GrokBuildInteractionDialogProps & {
+ dialogRef: RefObject<HTMLDivElement | null>;
+};
+
+function QuestionDialog({
+ dialogRef,
+ error,
+ interaction,
+ onRespond,
+ submitting,
+}: DialogPropsWithRef & {
+ interaction: Extract<GrokBuildInteraction, { kind: "question" }>;
+}) {
+ const [answers, setAnswers] = useState<Record<string, string[]>>({});
+ const [notes, setNotes] = useState<Record<string, string>>({});
+
+ const setSelected = (question: GrokBuildQuestion, label: string, checked: boolean) => {
+ setAnswers((current) => {
+ if (!question.multiSelect) {
+ return { ...current, [question.question]: checked ? [label] : [] };
+ }
+ const selected = current[question.question] ?? [];
+ const next = checked
+ ? [...selected.filter((item) => item !== label), label]
+ : selected.filter((item) => item !== label);
+ return { ...current, [question.question]: next };
+ });
+ if (!question.multiSelect) {
+ setNotes((current) => ({ ...current, [question.question]: "" }));
+ }
+ };
+
+ const setOther = (question: GrokBuildQuestion, value: string) => {
+ setNotes((current) => ({ ...current, [question.question]: value }));
+ setAnswers((current) => {
+ const selected = current[question.question] ?? [];
+ const withoutOther = selected.filter((item) => item !== "Other");
+ return {
+ ...current,
+ [question.question]: value.trim()
+ ? question.multiSelect
+ ? [...withoutOther, "Other"]
+ : ["Other"]
+ : question.multiSelect
+ ? withoutOther
+ : [],
+ };
+ });
+ };
+
+ const toggleOther = (question: GrokBuildQuestion, checked: boolean) => {
+ if (!checked) {
+ setNotes((current) => ({ ...current, [question.question]: "" }));
+ setAnswers((current) => ({
+ ...current,
+ [question.question]: (current[question.question] ?? []).filter((item) => item !== "Other"),
+ }));
+ return;
+ }
+ setAnswers((current) => {
+ const selected = current[question.question] ?? [];
+ return {
+ ...current,
+ [question.question]: question.multiSelect
+ ? [...selected.filter((item) => item !== "Other"), "Other"]
+ : ["Other"],
+ };
+ });
+ };
+
+ const submittedValues = (question: GrokBuildQuestion): string[] => {
+ const selected = answers[question.question] ?? [];
+ const optionLabels = selected.filter((item) => item !== "Other");
+ const hasOther = selected.includes("Other") && Boolean(notes[question.question]?.trim());
+ if (question.multiSelect) return [...optionLabels, ...(hasOther ? ["Other"] : [])];
+ if (optionLabels.length > 0) return optionLabels.slice(0, 1);
+ return hasOther ? ["Other"] : [];
+ };
+
+ const partialAnswers = Object.fromEntries(
+ interaction.questions.flatMap((question) => {
+ const selected = submittedValues(question);
+ return selected.length > 0 ? [[question.question, selected.join(", ")]] : [];
+ }),
+ );
+ const hasAnswer = Object.keys(partialAnswers).length > 0;
+
+ const submitAnswers = () => {
+ const submittedAnswers = Object.fromEntries(
+ interaction.questions.flatMap((question) => {
+ const selected = submittedValues(question);
+ return selected.length > 0 ? [[question.question, selected]] : [];
+ }),
+ );
+ const annotations = Object.fromEntries(
+ interaction.questions.flatMap((question) => {
+ const selected = answers[question.question] ?? [];
+ const note = notes[question.question]?.trim();
+ return selected.includes("Other") && note ? [[question.question, { notes: note }]] : [];
+ }),
+ );
+ return onRespond({
+ outcome: "accepted",
+ answers: submittedAnswers,
+ ...(Object.keys(annotations).length > 0 ? { annotations } : {}),
+ });
+ };
+
+ return (
+ <div
+ className="grok-interaction-card"
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="grok-question-title"
+ ref={dialogRef}
+ tabIndex={-1}
+ >
+ <div className="grok-interaction-heading">
+ <div>
+ <p className="grok-interaction-eyebrow">Grok Build needs your input</p>
+ <h2 id="grok-question-title">Answer a few questions</h2>
+ </div>
+ <button
+ className="grok-interaction-close"
+ type="button"
+ disabled={submitting}
+ onClick={() => void onRespond({ outcome: "cancelled" })}
+ aria-label="Dismiss questions"
+ >
+ <span aria-hidden="true">×</span>
+ </button>
+ </div>
+
+ <div className="grok-question-list">
+ {interaction.questions.map((question, questionIndex) => {
+ const selected = answers[question.question] ?? [];
+ const preview =
+ !question.multiSelect && selected[0] !== "Other"
+ ? question.options.find((option) => option.label === selected[0])?.preview
+ : undefined;
+ return (
+ <fieldset className="grok-question" key={`${question.question}-${questionIndex}`}>
+ <legend>
+ <span>{question.question}</span>
+ <small>
+ Question {questionIndex + 1} of {interaction.questions.length}
+ {question.multiSelect ? " · Select all that apply" : " · Select one"}
+ </small>
+ </legend>
+ <div className="grok-question-options">
+ {question.options.map((option) => {
+ const inputId = `grok-question-${questionIndex}-${option.label}`;
+ return (
+ <label className="grok-question-option" htmlFor={inputId} key={option.label}>
+ <input
+ id={inputId}
+ type={question.multiSelect ? "checkbox" : "radio"}
+ name={`grok-question-${questionIndex}`}
+ checked={selected.includes(option.label)}
+ disabled={submitting}
+ onChange={(event) =>
+ setSelected(question, option.label, event.target.checked)
+ }
+ />
+ <span>
+ <strong>{option.label}</strong>
+ {option.description ? <small>{option.description}</small> : null}
+ </span>
+ </label>
+ );
+ })}
+ <div className="grok-question-option grok-question-other">
+ <label
+ className="grok-question-other-choice"
+ htmlFor={`grok-question-${questionIndex}-other`}
+ >
+ <input
+ id={`grok-question-${questionIndex}-other`}
+ type={question.multiSelect ? "checkbox" : "radio"}
+ name={`grok-question-${questionIndex}`}
+ checked={selected.includes("Other")}
+ disabled={submitting}
+ onChange={(event) => toggleOther(question, event.target.checked)}
+ />
+ <strong>Other</strong>
+ </label>
+ <input
+ className="grok-question-other-input"
+ type="text"
+ value={notes[question.question] ?? ""}
+ disabled={submitting}
+ onChange={(event) => setOther(question, event.target.value)}
+ placeholder="Type a custom answer"
+ aria-label={`Other answer for ${question.question}`}
+ />
+ </div>
+ </div>
+ {preview ? (
+ <div className="grok-question-preview">
+ <span>Selected option preview</span>
+ <pre>{preview}</pre>
+ </div>
+ ) : null}
+ </fieldset>
+ );
+ })}
+ </div>
+
+ {error ? (
+ <p className="grok-interaction-error" role="alert">
+ {error}
+ </p>
+ ) : null}
+ <div
+ className={`grok-interaction-actions${
+ interaction.mode === "plan" ? " grok-question-plan-actions" : ""
+ }`}
+ >
+ {interaction.mode === "plan" ? (
+ <>
+ <button
+ className="grok-button-secondary"
+ type="button"
+ disabled={submitting}
+ onClick={() =>
+ void onRespond({ outcome: "chat_about_this", partial_answers: partialAnswers })
+ }
+ >
+ Chat about this
+ </button>
+ <button
+ className="grok-button-secondary"
+ type="button"
+ disabled={submitting}
+ onClick={() =>
+ void onRespond({ outcome: "skip_interview", partial_answers: partialAnswers })
+ }
+ >
+ Skip interview
+ </button>
+ </>
+ ) : null}
+ <button
+ className="grok-button-primary grok-question-submit"
+ type="button"
+ disabled={submitting || !hasAnswer}
+ onClick={() => void submitAnswers()}
+ >
+ {submitting ? "Submitting…" : "Continue"}
+ </button>
+ </div>
+ </div>
+ );
+}
+
+function PlanDialog({
+ dialogRef,
+ error,
+ interaction,
+ onRespond,
+ submitting,
+}: DialogPropsWithRef & {
+ interaction: Extract<GrokBuildInteraction, { kind: "plan" }>;
+}) {
+ const [feedback, setFeedback] = useState("");
+
+ return (
+ <div
+ className="grok-interaction-card grok-plan-card"
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="grok-plan-title"
+ ref={dialogRef}
+ tabIndex={-1}
+ >
+ <div className="grok-interaction-heading">
+ <div>
+ <p className="grok-interaction-eyebrow">Plan ready for review</p>
+ <h2 id="grok-plan-title">Approve or revise Grok&apos;s plan</h2>
+ </div>
+ <button
+ className="grok-interaction-close"
+ type="button"
+ disabled={submitting}
+ onClick={() => void onRespond({ outcome: "abandoned" })}
+ aria-label="Abandon plan"
+ >
+ <span aria-hidden="true">×</span>
+ </button>
+ </div>
+
+ <section className="grok-plan-document" aria-label="Proposed plan">
+ <div className="grok-plan-document-heading">
+ <span>Proposed plan</span>
+ <small>Review before Grok continues</small>
+ </div>
+ <pre className="grok-plan-content">
+ {interaction.planContent?.trim() || "Grok Build did not provide plan content."}
+ </pre>
+ </section>
+ <label className="grok-plan-feedback">
+ <span>Requested changes</span>
+ <textarea
+ value={feedback}
+ disabled={submitting}
+ onChange={(event) => setFeedback(event.target.value)}
+ placeholder="Describe what Grok should change in the plan…"
+ rows={3}
+ />
+ </label>
+
+ {error ? (
+ <p className="grok-interaction-error" role="alert">
+ {error}
+ </p>
+ ) : null}
+ <div className="grok-interaction-actions grok-plan-actions">
+ <button
+ className="grok-button-secondary"
+ type="button"
+ disabled={submitting}
+ onClick={() => void onRespond({ outcome: "abandoned" })}
+ >
+ Abandon
+ </button>
+ <button
+ className="grok-button-secondary"
+ type="button"
+ disabled={submitting || !feedback.trim()}
+ onClick={() => void onRespond({ outcome: "cancelled", feedback: feedback.trim() })}
+ >
+ Request changes
+ </button>
+ <button
+ className="grok-button-primary"
+ type="button"
+ disabled={submitting}
+ onClick={() => void onRespond({ outcome: "approved" })}
+ >
+ {submitting ? "Submitting…" : "Approve plan"}
+ </button>
+ </div>
+ </div>
+ );
+}
+
+export function GrokBuildInteractionDialog(props: GrokBuildInteractionDialogProps) {
+ const { interaction, onRespond, submitting } = props;
+ const dialogRef = useRef<HTMLDivElement>(null);
+ const submittingRef = useRef(submitting);
+
+ useEffect(() => {
+ submittingRef.current = submitting;
+ }, [submitting]);
+
+ useEffect(() => {
+ const previousFocus =
+ document.activeElement instanceof HTMLElement ? document.activeElement : null;
+ dialogRef.current?.focus({ preventScroll: true });
+
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "Escape" && !submittingRef.current) {
+ void onRespond(
+ interaction.kind === "question" ? { outcome: "cancelled" } : { outcome: "abandoned" },
+ );
+ return;
+ }
+ if (event.key !== "Tab" || !dialogRef.current) return;
+
+ const focusable = [
+ ...dialogRef.current.querySelectorAll<HTMLElement>(
+ 'button:not(:disabled), input:not(:disabled), textarea:not(:disabled), [href], [tabindex]:not([tabindex="-1"])',
+ ),
+ ].filter((element) => element.getClientRects().length > 0);
+ if (focusable.length === 0) {
+ event.preventDefault();
+ dialogRef.current.focus();
+ return;
+ }
+ const first = focusable[0];
+ const last = focusable[focusable.length - 1];
+ if (
+ event.shiftKey &&
+ (document.activeElement === first || document.activeElement === dialogRef.current)
+ ) {
+ event.preventDefault();
+ last.focus();
+ } else if (!event.shiftKey && document.activeElement === last) {
+ event.preventDefault();
+ first.focus();
+ }
+ };
+ window.addEventListener("keydown", onKeyDown);
+ return () => {
+ window.removeEventListener("keydown", onKeyDown);
+ previousFocus?.focus({ preventScroll: true });
+ };
+ }, [interaction.kind, onRespond]);
+
+ const dismiss = () =>
+ onRespond(
+ interaction.kind === "question" ? { outcome: "cancelled" } : { outcome: "abandoned" },
+ );
+
+ return (
+ <div
+ className="grok-interaction-backdrop"
+ onMouseDown={(event) => {
+ if (event.target === event.currentTarget && !submitting) void dismiss();
+ }}
+ >
+ {interaction.kind === "question" ? (
+ <QuestionDialog {...props} dialogRef={dialogRef} interaction={interaction} />
+ ) : (
+ <PlanDialog {...props} dialogRef={dialogRef} interaction={interaction} />
+ )}
+ </div>
+ );
+}
diff --git a/examples/harnesses/grok-build/src/hooks/use-grok-build-interaction.ts b/examples/harnesses/grok-build/src/hooks/use-grok-build-interaction.ts
new file mode 100644
index 000000000..38666f1d3
--- /dev/null
+++ b/examples/harnesses/grok-build/src/hooks/use-grok-build-interaction.ts
@@ -0,0 +1,101 @@
+"use client";
+
+import type {
+ GrokBuildInteraction,
+ GrokBuildInteractionResponse,
+} from "@/lib/grok-build-interactions";
+import { useCallback, useEffect, useState } from "react";
+
+const POLL_RETRY_MS = 1_000;
+
+interface InteractionPayload {
+ interaction?: GrokBuildInteraction | null;
+}
+
+export function useGrokBuildInteraction(threadId: string | undefined) {
+ const [interaction, setInteraction] = useState<GrokBuildInteraction>();
+ const [error, setError] = useState<string>();
+ const [submitting, setSubmitting] = useState(false);
+
+ useEffect(() => {
+ if (!threadId) return;
+
+ let disposed = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let controller: AbortController | undefined;
+ let observedInteractionId: string | undefined;
+
+ const poll = async () => {
+ controller = new AbortController();
+ let retryDelay = 0;
+ try {
+ const query = new URLSearchParams({ threadId });
+ if (observedInteractionId) query.set("after", observedInteractionId);
+ const response = await fetch(`/api/interactions?${query}`, {
+ cache: "no-store",
+ signal: controller.signal,
+ });
+ if (!response.ok) throw new Error(`Interaction poll failed (${response.status}).`);
+ const payload = (await response.json()) as InteractionPayload;
+ if (!disposed) {
+ const nextInteraction = payload.interaction ?? undefined;
+ observedInteractionId = nextInteraction?.id;
+ setInteraction(nextInteraction);
+ setError(undefined);
+ }
+ } catch (pollError) {
+ if (!disposed && !(pollError instanceof DOMException && pollError.name === "AbortError")) {
+ setError(pollError instanceof Error ? pollError.message : "Could not load interaction.");
+ retryDelay = POLL_RETRY_MS;
+ }
+ } finally {
+ if (!disposed) timer = setTimeout(poll, retryDelay);
+ }
+ };
+
+ void poll();
+ return () => {
+ disposed = true;
+ controller?.abort();
+ if (timer) clearTimeout(timer);
+ };
+ }, [threadId]);
+
+ const respond = useCallback(
+ async (responseValue: GrokBuildInteractionResponse) => {
+ if (!threadId || !interaction) return;
+ setSubmitting(true);
+ setError(undefined);
+ try {
+ const response = await fetch("/api/interactions", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ threadId,
+ interactionId: interaction.id,
+ response: responseValue,
+ }),
+ });
+ const payload = (await response.json().catch(() => ({}))) as { error?: string };
+ if (!response.ok) {
+ throw new Error(payload.error ?? `Interaction response failed (${response.status}).`);
+ }
+ setInteraction(undefined);
+ } catch (responseError) {
+ setError(
+ responseError instanceof Error ? responseError.message : "Could not submit response.",
+ );
+ } finally {
+ setSubmitting(false);
+ }
+ },
+ [interaction, threadId],
+ );
+
+ return {
+ error: threadId ? error : undefined,
+ interaction: threadId && interaction?.sessionId === threadId ? interaction : undefined,
+ respond,
+ submitting,
+ };
+}
diff --git a/examples/harnesses/grok-build/src/lib/grok-build-acp.ts b/examples/harnesses/grok-build/src/lib/grok-build-acp.ts
index b9369e499..4043ad3f2 100644
--- a/examples/harnesses/grok-build/src/lib/grok-build-acp.ts
+++ b/examples/harnesses/grok-build/src/lib/grok-build-acp.ts
@@ -14,6 +14,10 @@ import { spawn } from "node:child_process";
import { createHash } from "node:crypto";
import { Readable, Writable } from "node:stream";
import { systemPrompt } from "../library";
+import {
+ cancelGrokBuildInteractions,
+ requestGrokBuildInteraction,
+} from "./grok-build-interactions";
const OPENUI_RULES = systemPrompt;
const OPENUI_RULES_HASH = createHash("sha256").update(OPENUI_RULES).digest("hex");
@@ -45,10 +49,7 @@ interface GrokBuildTurnCompleted {
usage?: Record<string, unknown>;
}
-export type GrokBuildSessionUpdate =
- | SessionUpdate
- | GrokBuildRetryState
- | GrokBuildTurnCompleted;
+export type GrokBuildSessionUpdate = SessionUpdate | GrokBuildRetryState | GrokBuildTurnCompleted;
type UpdateListener = (update: GrokBuildSessionUpdate) => void;
@@ -67,10 +68,7 @@ export function decodeGrokSessionNotification(
const sessionId = params.sessionId;
const update = recordValue(params.update);
const kind = update?.sessionUpdate;
- if (
- typeof sessionId !== "string" ||
- (kind !== "retry_state" && kind !== "turn_completed")
- ) {
+ if (typeof sessionId !== "string" || (kind !== "retry_state" && kind !== "turn_completed")) {
return undefined;
}
return { sessionId, update: update as unknown as GrokBuildSessionUpdate };
@@ -203,6 +201,7 @@ class GrokBuildACPClient {
this.child.on("error", (error) => {
this.processError = error;
});
+ this.child.on("exit", () => this.cancelPendingInteractions());
this.child.stderr?.setEncoding("utf8");
this.child.stderr?.on("data", (chunk: string) => {
this.stderrTail = `${this.stderrTail}${chunk}`.slice(-12_000);
@@ -219,7 +218,7 @@ class GrokBuildACPClient {
const client: Client = {
requestPermission: (request) => this.requestPermission(request),
sessionUpdate: (notification) => this.sessionUpdate(notification),
- extMethod: (method) => this.extensionRequest(method),
+ extMethod: (method, params) => this.extensionRequest(method, params),
extNotification: (method, params) => this.extensionNotification(method, params),
};
this.connection = new ClientSideConnection(() => client, stream);
@@ -290,9 +289,15 @@ class GrokBuildACPClient {
}
dispose(): void {
+ this.cancelPendingInteractions();
if (this.child.exitCode === null) this.child.kill("SIGTERM");
}
+ private cancelPendingInteractions(): void {
+ const sessionIds = new Set([...this.residentSessions, ...this.openingSessions.keys()]);
+ for (const sessionId of sessionIds) cancelGrokBuildInteractions(sessionId);
+ }
+
private connectionClosedError(label: string): Error {
const cause = this.processError?.message
? `: ${this.processError.message}`
@@ -347,17 +352,15 @@ class GrokBuildACPClient {
return { outcome: { outcome: "cancelled" } };
}
- private async extensionRequest(method: string): Promise<Record<string, unknown>> {
- // Grok's conversational questions and plan approval are interactive ACP
- // extension requests, independent of normal tool permissions. AgentInterface
- // does not expose their response UI, so answer immediately and explicitly;
- // leaving either request pending would hang the prompt turn.
- if (method === "_x.ai/ask_user_question" || method === "x.ai/ask_user_question") {
- return { outcome: "cancelled" };
- }
- if (method === "_x.ai/exit_plan_mode" || method === "x.ai/exit_plan_mode") {
- return { outcome: "cancelled" };
- }
+ private async extensionRequest(
+ method: string,
+ params: Record<string, unknown>,
+ ): Promise<Record<string, unknown>> {
+ // These blocking reverse-requests are answered through the web harness's
+ // interaction route. The browser polls while the main AG-UI stream remains
+ // open, then its response resolves this ACP method and resumes the turn.
+ const interaction = requestGrokBuildInteraction(method, params);
+ if (interaction) return interaction;
throw RequestError.methodNotFound(method);
}
@@ -464,31 +467,34 @@ class GrokBuildACPClient {
sessionId: string;
signal: AbortSignal;
}): Promise<{ stopReason?: string }> {
- await this.ensureSession(sessionId, hasHistory);
- if (this.activeThreads.has(sessionId)) throw new GrokBuildBusyError();
if (signal.aborted) throw new DOMException("The request was aborted.", "AbortError");
-
- this.activeThreads.add(sessionId);
let terminalError: string | undefined;
- const unsubscribe = this.subscribe(sessionId, (update) => {
- if (update.sessionUpdate === "retry_state" && update.type === "failed") {
- terminalError = update.message || update.reason || terminalError;
- } else if (
- update.sessionUpdate === "turn_completed" &&
- update.stop_reason === "error"
- ) {
- terminalError = update.agent_result || terminalError;
- }
- onUpdate(update);
- });
const cancel = () => {
+ cancelGrokBuildInteractions(sessionId);
void this.request("Cancelling the Grok Build turn", () =>
this.connection.cancel({ sessionId }),
).catch(() => undefined);
};
signal.addEventListener("abort", cancel, { once: true });
+ let unsubscribe: (() => void) | undefined;
+ let active = false;
try {
+ await this.ensureSession(sessionId, hasHistory);
+ if (this.activeThreads.has(sessionId)) throw new GrokBuildBusyError();
+ if (signal.aborted) throw new DOMException("The request was aborted.", "AbortError");
+
+ this.activeThreads.add(sessionId);
+ active = true;
+ unsubscribe = this.subscribe(sessionId, (update) => {
+ if (update.sessionUpdate === "retry_state" && update.type === "failed") {
+ terminalError = update.message || update.reason || terminalError;
+ } else if (update.sessionUpdate === "turn_completed" && update.stop_reason === "error") {
+ terminalError = update.agent_result || terminalError;
+ }
+ onUpdate(update);
+ });
+
const response = await this.request("Running the Grok Build turn", () =>
this.connection.prompt({
sessionId,
@@ -507,12 +513,12 @@ class GrokBuildACPClient {
}
return { stopReason };
} catch (error) {
- if (error instanceof GrokBuildTurnError) throw error;
+ if (error instanceof GrokBuildTurnError || error instanceof GrokBuildBusyError) throw error;
throw new GrokBuildTurnError(terminalError ?? formatGrokBuildError(error), error);
} finally {
signal.removeEventListener("abort", cancel);
- unsubscribe();
- this.activeThreads.delete(sessionId);
+ unsubscribe?.();
+ if (active) this.activeThreads.delete(sessionId);
}
}
}
diff --git a/examples/harnesses/grok-build/src/lib/grok-build-chat.ts b/examples/harnesses/grok-build/src/lib/grok-build-chat.ts
index c0aba2f02..ec4c44999 100644
--- a/examples/harnesses/grok-build/src/lib/grok-build-chat.ts
+++ b/examples/harnesses/grok-build/src/lib/grok-build-chat.ts
@@ -43,11 +43,20 @@ async function persistAssistantFromStream(
* Returns the two independent adapters AgentInterface needs: an AG-UI-backed
* LLM transport and a localStorage-backed thread store.
*/
-export function createGrokBuildChatProps(
- storage: KVStorage = getClientStorage(),
- store: ThreadStore = createThreadStore(storage),
-): { llm: ChatLLM; storage: ChatStorage } {
+export interface CreateGrokBuildChatOptions {
+ onThreadChange?: (threadId: string) => void;
+ storage?: KVStorage;
+ store?: ThreadStore;
+}
+
+export function createGrokBuildChatProps(options: CreateGrokBuildChatOptions = {}): {
+ llm: ChatLLM;
+ storage: ChatStorage;
+} {
+ const storage = options.storage ?? getClientStorage();
+ const store = options.store ?? createThreadStore(storage);
const send: ChatLLM["send"] = async ({ messages, threadId, signal }): Promise<Response> => {
+ options.onThreadChange?.(threadId);
store.saveMessages(threadId, messages);
const response = await fetch("/api/chat", {
@@ -75,8 +84,15 @@ export function createGrokBuildChatProps(
storage: {
thread: {
listThreads: () => store.fetchThreadList(),
- createThread: (firstMessage) => store.createThread(firstMessage),
- getMessages: (threadId) => store.loadThread(threadId),
+ createThread: async (firstMessage) => {
+ const thread = await store.createThread(firstMessage);
+ options.onThreadChange?.(thread.id);
+ return thread;
+ },
+ getMessages: (threadId) => {
+ options.onThreadChange?.(threadId);
+ return store.loadThread(threadId);
+ },
updateThread: (thread) => store.updateThread(thread),
deleteThread: (threadId) => store.deleteThread(threadId),
},
diff --git a/examples/harnesses/grok-build/src/lib/grok-build-interactions.test.ts b/examples/harnesses/grok-build/src/lib/grok-build-interactions.test.ts
new file mode 100644
index 000000000..646b7e295
--- /dev/null
+++ b/examples/harnesses/grok-build/src/lib/grok-build-interactions.test.ts
@@ -0,0 +1,193 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { GrokBuildInteractionBroker, parseGrokBuildInteraction } from "./grok-build-interactions";
+
+const sessionId = "0198f9e5-f4fb-7b64-91f0-0cab13d00d01";
+
+function questionParams(mode: "default" | "plan" = "default") {
+ return {
+ sessionId,
+ toolCallId: "tool-question-1",
+ mode,
+ questions: [
+ {
+ question: "Which database?",
+ multiSelect: false,
+ options: [
+ {
+ label: "Postgres (Recommended)",
+ description: "Relational and durable",
+ preview: "CREATE TABLE users (...);",
+ },
+ { label: "Redis", description: "Fast in-memory storage" },
+ ],
+ },
+ ],
+ };
+}
+
+describe("GrokBuildInteractionBroker", () => {
+ let broker = new GrokBuildInteractionBroker(60_000);
+
+ afterEach(() => {
+ broker.cancelAll();
+ broker = new GrokBuildInteractionBroker(60_000);
+ });
+
+ it("parses wrapped ask-user requests and preserves question metadata", () => {
+ const parsed = parseGrokBuildInteraction("_x.ai/ask_user_question", {
+ method: "x.ai/ask_user_question",
+ params: questionParams("plan"),
+ });
+
+ expect(parsed).toMatchObject({
+ kind: "question",
+ sessionId,
+ toolCallId: "tool-question-1",
+ mode: "plan",
+ questions: [
+ {
+ question: "Which database?",
+ multiSelect: false,
+ options: [
+ {
+ label: "Postgres (Recommended)",
+ description: "Relational and durable",
+ preview: "CREATE TABLE users (...);",
+ },
+ {
+ label: "Redis",
+ description: "Fast in-memory storage",
+ },
+ ],
+ },
+ ],
+ });
+ });
+
+ it("waits for and sanitizes an accepted question response", async () => {
+ const result = broker.request("x.ai/ask_user_question", questionParams());
+ const interaction = broker.current(sessionId);
+ expect(interaction?.kind).toBe("question");
+
+ expect(
+ broker.respond(sessionId, interaction!.id, {
+ outcome: "accepted",
+ answers: {
+ "Which database?": ["Postgres (Recommended)", "not-an-option"],
+ "Injected question": ["bad"],
+ },
+ annotations: {
+ "Which database?": { notes: "ignored", preview: "untrusted preview" },
+ },
+ }),
+ ).toBe(true);
+
+ await expect(result).resolves.toEqual({
+ outcome: "accepted",
+ answers: { "Which database?": ["Postgres (Recommended)"] },
+ annotations: { "Which database?": { preview: "CREATE TABLE users (...);" } },
+ });
+ expect(broker.current(sessionId)).toBeUndefined();
+ });
+
+ it("supports plan review feedback", async () => {
+ const result = broker.request("x.ai/exit_plan_mode", {
+ sessionId,
+ toolCallId: "tool-plan-1",
+ planContent: "# Plan\n\n1. Add tests",
+ });
+ const interaction = broker.current(sessionId);
+ expect(interaction).toMatchObject({
+ kind: "plan",
+ planContent: "# Plan\n\n1. Add tests",
+ });
+
+ expect(
+ broker.respond(sessionId, interaction!.id, {
+ outcome: "cancelled",
+ feedback: "Cover the error path too.",
+ }),
+ ).toBe(true);
+ await expect(result).resolves.toEqual({
+ outcome: "cancelled",
+ feedback: "Cover the error path too.",
+ });
+ });
+
+ it("requires free-form text and keeps it beside multi-select options", async () => {
+ const result = broker.request("x.ai/ask_user_question", {
+ ...questionParams(),
+ questions: [{ ...questionParams().questions[0], multiSelect: true }],
+ });
+ const interaction = broker.current(sessionId)!;
+
+ expect(
+ broker.respond(sessionId, interaction.id, {
+ outcome: "accepted",
+ answers: { "Which database?": ["Redis", "Other"] },
+ annotations: { "Which database?": { notes: "Use Redis for the cache." } },
+ }),
+ ).toBe(true);
+ await expect(result).resolves.toEqual({
+ outcome: "accepted",
+ answers: { "Which database?": ["Redis"] },
+ annotations: { "Which database?": { notes: "Use Redis for the cache." } },
+ });
+
+ const emptyOther = broker.request("x.ai/ask_user_question", questionParams());
+ const nextInteraction = broker.current(sessionId)!;
+ expect(() =>
+ broker.respond(sessionId, nextInteraction.id, {
+ outcome: "accepted",
+ answers: { "Which database?": ["Other"] },
+ }),
+ ).toThrow("Answer at least one Grok Build question");
+ broker.cancelSession(sessionId);
+ await expect(emptyOther).resolves.toEqual({ outcome: "cancelled" });
+ });
+
+ it("uses safe fallback outcomes when a session is cancelled", async () => {
+ const question = broker.request("x.ai/ask_user_question", questionParams());
+ broker.cancelSession(sessionId);
+ await expect(question).resolves.toEqual({ outcome: "cancelled" });
+
+ const plan = broker.request("x.ai/exit_plan_mode", {
+ sessionId,
+ toolCallId: "tool-plan-2",
+ planContent: "# Plan",
+ });
+ broker.cancelSession(sessionId);
+ await expect(plan).resolves.toEqual({ outcome: "abandoned" });
+ });
+
+ it("rejects plan-only question outcomes outside plan mode", () => {
+ broker.request("x.ai/ask_user_question", questionParams());
+ const interaction = broker.current(sessionId);
+ expect(() =>
+ broker.respond(sessionId, interaction!.id, {
+ outcome: "skip_interview",
+ partial_answers: {},
+ }),
+ ).toThrow("only valid for a plan-mode question");
+ });
+
+ it("long-polls until an interaction changes", async () => {
+ const appeared = broker.waitForChange(sessionId, undefined, { timeoutMs: 1_000 });
+ const response = broker.request("x.ai/ask_user_question", questionParams());
+ const interaction = await appeared;
+ expect(interaction).toMatchObject({ kind: "question", sessionId });
+
+ const cleared = broker.waitForChange(sessionId, interaction!.id, { timeoutMs: 1_000 });
+ expect(
+ broker.respond(sessionId, interaction!.id, {
+ outcome: "accepted",
+ answers: { "Which database?": ["Redis"] },
+ }),
+ ).toBe(true);
+ await expect(cleared).resolves.toBeUndefined();
+ await expect(response).resolves.toEqual({
+ outcome: "accepted",
+ answers: { "Which database?": ["Redis"] },
+ });
+ });
+});
diff --git a/examples/harnesses/grok-build/src/lib/grok-build-interactions.ts b/examples/harnesses/grok-build/src/lib/grok-build-interactions.ts
new file mode 100644
index 000000000..87c9450fb
--- /dev/null
+++ b/examples/harnesses/grok-build/src/lib/grok-build-interactions.ts
@@ -0,0 +1,447 @@
+const ASK_USER_METHOD = "x.ai/ask_user_question";
+const EXIT_PLAN_METHOD = "x.ai/exit_plan_mode";
+const DEFAULT_INTERACTION_TIMEOUT_MS = 30 * 60 * 1000;
+
+type UnknownRecord = Record<string, unknown>;
+
+export interface GrokBuildQuestionOption {
+ description: string;
+ label: string;
+ preview?: string;
+}
+
+export interface GrokBuildQuestion {
+ multiSelect: boolean;
+ options: GrokBuildQuestionOption[];
+ question: string;
+}
+
+interface GrokBuildInteractionBase {
+ createdAt: number;
+ id: string;
+ sessionId: string;
+ toolCallId: string;
+}
+
+export interface GrokBuildQuestionInteraction extends GrokBuildInteractionBase {
+ kind: "question";
+ mode: "default" | "plan";
+ questions: GrokBuildQuestion[];
+}
+
+export interface GrokBuildPlanInteraction extends GrokBuildInteractionBase {
+ kind: "plan";
+ planContent?: string;
+}
+
+export type GrokBuildInteraction = GrokBuildQuestionInteraction | GrokBuildPlanInteraction;
+type GrokBuildInteractionDraft =
+ | Omit<GrokBuildQuestionInteraction, "createdAt" | "id">
+ | Omit<GrokBuildPlanInteraction, "createdAt" | "id">;
+
+export interface GrokBuildQuestionAnnotation {
+ notes?: string;
+ preview?: string;
+}
+
+export type GrokBuildQuestionResponse =
+ | {
+ annotations?: Record<string, GrokBuildQuestionAnnotation>;
+ answers: Record<string, string[]>;
+ outcome: "accepted";
+ }
+ | { outcome: "chat_about_this"; partial_answers?: Record<string, string> }
+ | { outcome: "skip_interview"; partial_answers?: Record<string, string> }
+ | { outcome: "cancelled" };
+
+export type GrokBuildPlanResponse =
+ { outcome: "approved" } | { outcome: "cancelled"; feedback?: string } | { outcome: "abandoned" };
+
+export type GrokBuildInteractionResponse = GrokBuildQuestionResponse | GrokBuildPlanResponse;
+
+interface PendingInteraction {
+ interaction: GrokBuildInteraction;
+ resolve: (response: UnknownRecord) => void;
+ timer: ReturnType<typeof setTimeout>;
+}
+
+interface InteractionWaiter {
+ afterInteractionId?: string;
+ onAbort?: () => void;
+ resolve: (interaction: GrokBuildInteraction | undefined) => void;
+ signal?: AbortSignal;
+ timer: ReturnType<typeof setTimeout>;
+}
+
+function recordValue(value: unknown): UnknownRecord | undefined {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? (value as UnknownRecord)
+ : undefined;
+}
+
+function requiredString(value: unknown, field: string): string {
+ if (typeof value !== "string" || !value.trim()) {
+ throw new Error(`Grok Build interaction is missing ${field}.`);
+ }
+ return value;
+}
+
+function optionalString(value: unknown): string | undefined {
+ return typeof value === "string" && value.trim() ? value : undefined;
+}
+
+function unwrapExtensionRequest(
+ method: string,
+ params: UnknownRecord,
+): { method: string; params: UnknownRecord } {
+ const wrappedMethod = typeof params.method === "string" ? params.method : undefined;
+ const wrappedParams = recordValue(params.params);
+ if (wrappedMethod && wrappedParams) {
+ return { method: wrappedMethod.replace(/^_/, ""), params: wrappedParams };
+ }
+ return { method: method.replace(/^_/, ""), params };
+}
+
+function parseQuestion(value: unknown): GrokBuildQuestion | undefined {
+ const record = recordValue(value);
+ if (!record || typeof record.question !== "string" || !record.question.trim()) return undefined;
+
+ const options = Array.isArray(record.options)
+ ? record.options.flatMap((candidate): GrokBuildQuestionOption[] => {
+ const option = recordValue(candidate);
+ if (!option || typeof option.label !== "string" || !option.label.trim()) return [];
+ return [
+ {
+ label: option.label,
+ description: typeof option.description === "string" ? option.description : "",
+ ...(optionalString(option.preview) ? { preview: optionalString(option.preview) } : {}),
+ },
+ ];
+ })
+ : [];
+
+ if (options.length === 0) return undefined;
+ return {
+ question: record.question,
+ options,
+ multiSelect: record.multiSelect === true || record.multi_select === true,
+ };
+}
+
+export function parseGrokBuildInteraction(
+ method: string,
+ params: UnknownRecord,
+): GrokBuildInteractionDraft | undefined {
+ const unwrapped = unwrapExtensionRequest(method, params);
+ if (unwrapped.method !== ASK_USER_METHOD && unwrapped.method !== EXIT_PLAN_METHOD) {
+ return undefined;
+ }
+
+ const sessionId = requiredString(unwrapped.params.sessionId, "sessionId");
+ const toolCallId = requiredString(unwrapped.params.toolCallId, "toolCallId");
+
+ if (unwrapped.method === ASK_USER_METHOD) {
+ const questions = Array.isArray(unwrapped.params.questions)
+ ? unwrapped.params.questions.flatMap((value) => {
+ const question = parseQuestion(value);
+ return question ? [question] : [];
+ })
+ : [];
+ if (questions.length === 0) {
+ throw new Error("Grok Build ask-user request did not contain any valid questions.");
+ }
+ return {
+ kind: "question",
+ sessionId,
+ toolCallId,
+ questions,
+ mode: unwrapped.params.mode === "plan" ? "plan" : "default",
+ };
+ }
+
+ return {
+ kind: "plan",
+ sessionId,
+ toolCallId,
+ ...(optionalString(unwrapped.params.planContent)
+ ? { planContent: optionalString(unwrapped.params.planContent) }
+ : {}),
+ };
+}
+
+function sanitizeStringMap(value: unknown, allowedKeys: Set<string>): Record<string, string> {
+ const record = recordValue(value);
+ if (!record) return {};
+ return Object.fromEntries(
+ Object.entries(record).flatMap(([key, candidate]) =>
+ allowedKeys.has(key) && typeof candidate === "string" && candidate.trim()
+ ? [[key, candidate]]
+ : [],
+ ),
+ );
+}
+
+function sanitizeQuestionResponse(
+ interaction: GrokBuildQuestionInteraction,
+ value: unknown,
+): UnknownRecord {
+ const response = recordValue(value);
+ if (!response) throw new Error("Invalid Grok Build question response.");
+ const outcome = response.outcome;
+ if (outcome === "cancelled") return { outcome };
+
+ const questionNames = new Set(interaction.questions.map((question) => question.question));
+ if (outcome === "chat_about_this" || outcome === "skip_interview") {
+ if (interaction.mode !== "plan") {
+ throw new Error(`${outcome} is only valid for a plan-mode question.`);
+ }
+ return {
+ outcome,
+ partial_answers: sanitizeStringMap(response.partial_answers, questionNames),
+ };
+ }
+
+ if (outcome !== "accepted") throw new Error("Invalid Grok Build question response.");
+ const submittedAnswers = recordValue(response.answers);
+ const submittedAnnotations = recordValue(response.annotations);
+ const answers: Record<string, string[]> = {};
+ const annotations: Record<string, GrokBuildQuestionAnnotation> = {};
+
+ for (const question of interaction.questions) {
+ const submitted = submittedAnswers?.[question.question];
+ const values = Array.isArray(submitted)
+ ? submitted.filter((item): item is string => typeof item === "string")
+ : typeof submitted === "string"
+ ? [submitted]
+ : [];
+ const allowedLabels = new Set([...question.options.map((option) => option.label), "Other"]);
+ const unique = [...new Set(values.filter((label) => allowedLabels.has(label)))];
+ const submittedAnnotation = recordValue(submittedAnnotations?.[question.question]);
+ const notes = unique.includes("Other") ? optionalString(submittedAnnotation?.notes) : undefined;
+ const optionLabels = unique.filter((label) => label !== "Other");
+ const selected = question.multiSelect
+ ? optionLabels.length > 0
+ ? optionLabels
+ : notes
+ ? ["Other"]
+ : []
+ : unique[0] === "Other"
+ ? notes
+ ? ["Other"]
+ : []
+ : unique.slice(0, 1);
+ if (selected.length === 0) continue;
+ answers[question.question] = selected;
+
+ const preview =
+ !question.multiSelect && selected[0] !== "Other"
+ ? question.options.find((option) => option.label === selected[0])?.preview
+ : undefined;
+ if (preview || notes)
+ annotations[question.question] = {
+ ...(preview ? { preview } : {}),
+ ...(notes ? { notes } : {}),
+ };
+ }
+
+ if (Object.keys(answers).length === 0) {
+ throw new Error("Answer at least one Grok Build question before submitting.");
+ }
+ return {
+ outcome,
+ answers,
+ ...(Object.keys(annotations).length > 0 ? { annotations } : {}),
+ };
+}
+
+function sanitizePlanResponse(value: unknown): UnknownRecord {
+ const response = recordValue(value);
+ if (!response) throw new Error("Invalid Grok Build plan response.");
+ const outcome = response.outcome;
+ if (outcome === "approved" || outcome === "abandoned") return { outcome };
+ if (outcome === "cancelled") {
+ const feedback = optionalString(response.feedback);
+ return { outcome, ...(feedback ? { feedback } : {}) };
+ }
+ throw new Error("Invalid Grok Build plan response.");
+}
+
+function fallbackResponse(interaction: GrokBuildInteraction): UnknownRecord {
+ return interaction.kind === "question" ? { outcome: "cancelled" } : { outcome: "abandoned" };
+}
+
+export class GrokBuildInteractionBroker {
+ private readonly pendingById = new Map<string, PendingInteraction>();
+ private readonly pendingIdBySession = new Map<string, string>();
+ private readonly waitersBySession = new Map<string, Set<InteractionWaiter>>();
+
+ constructor(private readonly timeoutMs = DEFAULT_INTERACTION_TIMEOUT_MS) {}
+
+ current(sessionId: string): GrokBuildInteraction | undefined {
+ const id = this.pendingIdBySession.get(sessionId);
+ return id ? this.pendingById.get(id)?.interaction : undefined;
+ }
+
+ waitForChange(
+ sessionId: string,
+ afterInteractionId?: string,
+ options: { signal?: AbortSignal; timeoutMs?: number } = {},
+ ): Promise<GrokBuildInteraction | undefined> {
+ const current = this.current(sessionId);
+ if (current?.id !== afterInteractionId || (afterInteractionId && !current)) {
+ return Promise.resolve(current);
+ }
+ if (options.signal?.aborted) return Promise.resolve(current);
+
+ return new Promise((resolve) => {
+ const waiter = {} as InteractionWaiter;
+ const settle = (interaction: GrokBuildInteraction | undefined) => {
+ clearTimeout(waiter.timer);
+ if (waiter.signal && waiter.onAbort) {
+ waiter.signal.removeEventListener("abort", waiter.onAbort);
+ }
+ const waiters = this.waitersBySession.get(sessionId);
+ waiters?.delete(waiter);
+ if (waiters?.size === 0) this.waitersBySession.delete(sessionId);
+ resolve(interaction);
+ };
+ waiter.afterInteractionId = afterInteractionId;
+ waiter.resolve = resolve;
+ waiter.signal = options.signal;
+ waiter.onAbort = () => settle(this.current(sessionId));
+ waiter.timer = setTimeout(
+ () => settle(this.current(sessionId)),
+ options.timeoutMs ?? 25_000,
+ );
+ (waiter.timer as ReturnType<typeof setTimeout> & { unref?: () => void }).unref?.();
+ this.waitersBySession.set(
+ sessionId,
+ (this.waitersBySession.get(sessionId) ?? new Set()).add(waiter),
+ );
+ options.signal?.addEventListener("abort", waiter.onAbort, { once: true });
+ });
+ }
+
+ request(method: string, params: UnknownRecord): Promise<UnknownRecord> | undefined {
+ const parsed = parseGrokBuildInteraction(method, params);
+ if (!parsed) return undefined;
+ this.cancelSession(parsed.sessionId);
+
+ const interaction: GrokBuildInteraction = {
+ ...parsed,
+ id: crypto.randomUUID(),
+ createdAt: Date.now(),
+ } as GrokBuildInteraction;
+
+ return new Promise<UnknownRecord>((resolve) => {
+ const timer = setTimeout(
+ () => this.settle(interaction.id, fallbackResponse(interaction)),
+ this.timeoutMs,
+ );
+ (timer as ReturnType<typeof setTimeout> & { unref?: () => void }).unref?.();
+ this.pendingById.set(interaction.id, { interaction, resolve, timer });
+ this.pendingIdBySession.set(interaction.sessionId, interaction.id);
+ this.notifyWaiters(interaction.sessionId);
+ });
+ }
+
+ respond(sessionId: string, interactionId: string, value: unknown): boolean {
+ const pending = this.pendingById.get(interactionId);
+ if (!pending || pending.interaction.sessionId !== sessionId) return false;
+ const response =
+ pending.interaction.kind === "question"
+ ? sanitizeQuestionResponse(pending.interaction, value)
+ : sanitizePlanResponse(value);
+ this.settle(interactionId, response);
+ return true;
+ }
+
+ cancelSession(sessionId: string): void {
+ const id = this.pendingIdBySession.get(sessionId);
+ const pending = id ? this.pendingById.get(id) : undefined;
+ if (pending) this.settle(pending.interaction.id, fallbackResponse(pending.interaction));
+ }
+
+ cancelAll(): void {
+ for (const pending of [...this.pendingById.values()]) {
+ this.settle(pending.interaction.id, fallbackResponse(pending.interaction));
+ }
+ }
+
+ private settle(interactionId: string, response: UnknownRecord): void {
+ const pending = this.pendingById.get(interactionId);
+ if (!pending) return;
+ clearTimeout(pending.timer);
+ this.pendingById.delete(interactionId);
+ if (this.pendingIdBySession.get(pending.interaction.sessionId) === interactionId) {
+ this.pendingIdBySession.delete(pending.interaction.sessionId);
+ }
+ pending.resolve(response);
+ this.notifyWaiters(pending.interaction.sessionId);
+ }
+
+ private notifyWaiters(sessionId: string): void {
+ const current = this.current(sessionId);
+ for (const waiter of [...(this.waitersBySession.get(sessionId) ?? [])]) {
+ if (current?.id !== waiter.afterInteractionId || (waiter.afterInteractionId && !current)) {
+ clearTimeout(waiter.timer);
+ if (waiter.signal && waiter.onAbort) {
+ waiter.signal.removeEventListener("abort", waiter.onAbort);
+ }
+ this.waitersBySession.get(sessionId)?.delete(waiter);
+ waiter.resolve(current);
+ }
+ }
+ if (this.waitersBySession.get(sessionId)?.size === 0) {
+ this.waitersBySession.delete(sessionId);
+ }
+ }
+}
+
+const globalStore = globalThis as unknown as {
+ __openuiGrokBuildInteractions?: GrokBuildInteractionBroker;
+};
+
+function broker(): GrokBuildInteractionBroker {
+ const existing = globalStore.__openuiGrokBuildInteractions;
+ if (existing && typeof existing.waitForChange === "function") return existing;
+ existing?.cancelAll();
+ const created = new GrokBuildInteractionBroker();
+ globalStore.__openuiGrokBuildInteractions = created;
+ return created;
+}
+
+export function requestGrokBuildInteraction(
+ method: string,
+ params: UnknownRecord,
+): Promise<UnknownRecord> | undefined {
+ return broker().request(method, params);
+}
+
+export function getGrokBuildInteraction(sessionId: string): GrokBuildInteraction | undefined {
+ return broker().current(sessionId);
+}
+
+export function waitForGrokBuildInteractionChange(
+ sessionId: string,
+ afterInteractionId?: string,
+ signal?: AbortSignal,
+): Promise<GrokBuildInteraction | undefined> {
+ return broker().waitForChange(sessionId, afterInteractionId, { signal });
+}
+
+export function respondToGrokBuildInteraction(
+ sessionId: string,
+ interactionId: string,
+ response: unknown,
+): boolean {
+ return broker().respond(sessionId, interactionId, response);
+}
+
+export function cancelGrokBuildInteractions(sessionId: string): void {
+ broker().cancelSession(sessionId);
+}
+
+export function cancelAllGrokBuildInteractions(): void {
+ broker().cancelAll();
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9c1404a3a..c8b284c38 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -463,8 +463,8 @@ importers:
specifier: ^0.0.53
version: 0.0.53
'@agentclientprotocol/sdk':
- specifier: 0.10.0
- version: 0.10.0([email protected])
+ specifier: 1.3.0
+ version: 1.3.0([email protected])
'@openuidev/lang-core':
specifier: workspace:*
version: link:../../../packages/lang-core
@@ -2346,8 +2346,8 @@ packages:
resolution: {integrity: sha512-pPENOZt0P6ibH8sCTgq05wLYXi5t3P9B5r/1bWYehXjUxtyOdnukSlWM++SsCIwUXsQdm/b3aBgGjEeTF7RenA==}
- '@agentclientprotocol/[email protected]':
- resolution: {integrity: sha512-+Bwmf8Uli480h4ONjANxVP6tnACqHOaCiLJslgwOJHJvjDFzhAHZX4aL/bPKpOPc3LU1RgkPnJ98rCdPBnakaQ==}
+ '@agentclientprotocol/[email protected]':
+ resolution: {integrity: sha512-i3h/efaeuMUFAO1HSfo97QZQnnvMd7wWBYtBsdL6UMZg3a78sk3Ffya5Xu7C7tYsXomXoDXJBAzQF2PcFKAhIQ==}
peerDependencies:
zod: ^3.25.0 || ^4.0.0
@@ -18885,7 +18885,7 @@ snapshots:
'@bufbuild/protobuf': 2.13.0
'@protobuf-ts/protoc': 2.11.1
- '@agentclientprotocol/[email protected]([email protected])':
+ '@agentclientprotocol/[email protected]([email protected])':
dependencies:
zod: 4.4.3