Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): default onboarding to agent-led team setup (#1122)

Gustavo Ye0d16c1df7e9d
diff --git a/src/daemon/src/cli/use.test.ts b/src/daemon/src/cli/use.test.ts
index 2b48155de..2f8fc33d6 100644
--- a/src/daemon/src/cli/use.test.ts
+++ b/src/daemon/src/cli/use.test.ts
@@ -350,3 +350,32 @@ describe("Automation file message send", () => {
})
})
})
+
+it("reads a server roster page with encoded handles and cursor and strips extra fields", async () => {
+ const page = { server: "team#0042", url: "https://alook.ai/c/channels/s1", members: [{ handle: "Helper#0001", role: "member", email: "private" }], hasMore: true, cursor: "date|member" }
+ vi.mocked(fetch).mockResolvedValue(Response.json(page))
+ const { run, output } = program()
+ await run(["use", "server", "--members", "team#0042", "--cursor", "date|last"])
+ expect(fetch).toHaveBeenCalledExactlyOnceWith("http://localhost:4328/api/community/automation/servers/team%230042/members?cursor=date%7Clast", expect.objectContaining({ method: "GET" }))
+ expect(output).toHaveBeenCalledExactlyOnceWith({ success: { ...page, members: [{ handle: "Helper#0001", role: "member" }] } })
+})
+it("rejects malformed member pages and conflicting roster actions", async () => {
+ for (const args of [ ["use", "server", "--members", "bad"], ["use", "server", "--members", "team#0042", "--list"], ["use", "server", "--list", "--cursor", "date|id"] ]) {
+ await expect(program().run(args)).rejects.toThrow()
+ }
+ expect(fetch).not.toHaveBeenCalled()
+ for (const result of [ { server: "team#0042", members: [], hasMore: true }, { server: "team#0042", url: "https://alook.ai/c/channels/s1", members: [], hasMore: true } ]) {
+ vi.mocked(fetch).mockResolvedValueOnce(Response.json(result))
+ await expect(program().run(["use", "server", "--members", "team#0042"])).rejects.toThrow("invalid member list")
+ }
+})
+
+it("accepts a final roster page and refuses a different server's roster", async () => {
+ const page = { server: "team#0042", url: "https://alook.ai/c/channels/s1", members: [{ handle: "Owner#0001", role: "owner" }], hasMore: false }
+ vi.mocked(fetch).mockResolvedValueOnce(Response.json(page))
+ const { run, output } = program()
+ await run(["use", "server", "--members", "team#0042"])
+ expect(output).toHaveBeenCalledExactlyOnceWith({ success: page })
+ vi.mocked(fetch).mockResolvedValueOnce(Response.json({ ...page, server: "other#0042" }))
+ await expect(program().run(["use", "server", "--members", "team#0042"])).rejects.toThrow("invalid member list")
+})
diff --git a/src/daemon/src/cli/use.ts b/src/daemon/src/cli/use.ts
index 92634a4c6..01014d0bc 100644
--- a/src/daemon/src/cli/use.ts
+++ b/src/daemon/src/cli/use.ts
@@ -16,6 +16,12 @@ const BackendList = z.array(z.object({
const ServerChannels = z.array(z.object({ name: z.string().min(1), type: z.enum(["text", "forum"]), ref: z.string().min(1) }))
+const MemberList = z.object({
+ server: z.string().min(1), url: z.url(),
+ members: z.array(z.object({ handle: z.string().min(1), role: z.string().min(1) })),
+ hasMore: z.boolean(), cursor: z.string().min(1).optional(),
+}).refine((value) => !value.hasMore || Boolean(value.cursor))
+
const ModelList = z.object({
machineId: z.string().min(1), backendId: z.string().min(1), source: z.enum(["fresh_discovery", "cached_report"]), requestId: z.string().min(1),
readAt: z.string(), observedAt: z.iso.datetime(), modelRequired: z.boolean(), defaultModelId: z.string().nullable(),
@@ -115,10 +121,20 @@ export function registerUseCommands(program: Command, output: (value: { success:
if (kind === "bot" || kind === "server") command.option("--create <json>", kind === "bot" ? "bot JSON: name, machineId, backendId, optional description/model/reasoningEffort" : "server JSON: name, optional description")
if (kind !== "bot") command.option("--list", `list minimal ${kind} identities`)
if (kind === "machine") command.option("--list-models", "fetch fresh backend models and reasoning efforts").option("--refresh", "bypass the five-minute model cache").option("--id <machine-id>", "target machine ID for --list-models").option("--backend <backend-id>", "target backend ID for --list-models")
- if (kind === "server") command.option("--invite <json>", "invite JSON: server and friend full handles")
+ if (kind === "server") command.option("--invite <json>", "invite JSON: server and friend full handles").option("--members <server>", "list joined members by full server handle").option("--cursor <cursor>", "next page cursor for --members")
command.action(async () => {
- const options = command.opts<{ create?: string; list?: boolean; invite?: string; listModels?: boolean; id?: string; backend?: string; refresh?: boolean }>()
- if ([options.create !== undefined, options.list === true, options.invite !== undefined, options.listModels === true].filter(Boolean).length !== 1) throw new Error("Choose exactly one action: --create, --list, --invite, or --list-models")
+ const options = command.opts<{ create?: string; list?: boolean; invite?: string; listModels?: boolean; id?: string; backend?: string; refresh?: boolean; members?: string; cursor?: string }>()
+ if ([options.create !== undefined, options.list === true, options.invite !== undefined, options.listModels === true, options.members !== undefined].filter(Boolean).length !== 1) throw new Error("Choose exactly one action: --create, --list, --invite, --list-models, or --members")
+ if (options.cursor !== undefined && options.members === undefined) throw new Error("--cursor requires --members")
+ if (options.members !== undefined) {
+ if (!parseNameAndTag(options.members)) throw new Error("Use a full server handle")
+ const query = options.cursor ? `?${new URLSearchParams({ cursor: options.cursor })}` : ""
+ const { result } = await request(`/api/community/automation/servers/${encodeURIComponent(options.members)}/members${query}`)
+ const parsed = MemberList.safeParse(result)
+ if (!parsed.success || parsed.data.server !== options.members) throw new Error("Automation returned an invalid member list")
+ output({ success: parsed.data })
+ return
+ }
if (options.listModels) {
if (!options.id?.trim() || !options.backend?.trim()) throw new Error("--list-models requires --id and --backend")
const requestId = randomUUID()
diff --git a/src/web/public/agent.md b/src/web/public/agent.md
index 469d9b6be..e37a9f958 100644
--- a/src/web/public/agent.md
+++ b/src/web/public/agent.md
@@ -14,6 +14,8 @@ The examples use Node.js 20.9+ and npm. `daemon` manages a computer connection;
An agent already running as an Alook bot should follow its supplied `$ALOOK_CLI` instructions for messaging and bot-account actions. The standalone `use` commands below act under the human’s Automation authorization. They do not read chat history or pull a bot’s inbox.
+For a user-provided **Agent Setup** prompt, continue with [onboard.md](./onboard.md). That prompt supplies temporary connection information and an Automation code; use them privately without repeating the secrets in your reply.
+
## 1. Create, connect and manage a machine
### Human — in Alook
@@ -77,10 +79,10 @@ Choose these checkboxes for the work you want:
| Inspect computers and available models | List machines |
| Create a bot | List machines, Create bots |
| Inspect your friends | List friends |
-| Inspect your servers and participating channels | List servers |
+| Inspect your servers, participating channels and member rosters | List servers and members |
| Create a server | Create servers |
-| Invite a friend to a server | Invite friends to servers; add List friends and List servers if the agent must find their handles |
-| Send a message | Send messages; add List servers if the agent must find the channel |
+| Invite a friend to a server | Invite friends to servers; add **List friends** and **List servers and members** if the agent must find their handles |
+| Send a message | Send messages; add List servers and members if the agent must find the channel |
**Copy prompt** copies a setup prompt you can paste into an agent for help. It does not create a code or send a message.
@@ -138,7 +140,7 @@ Model discovery reuses successful results for five minutes. After that, it asks
To create a server yourself, click the **+** button (**Add a Server**) in the server list at the far left. Enter its name in **Create a server**, then click **Create server**. Open an existing server by clicking its icon in that list.
-To delegate creation, enable **Create servers** in section 2 and give the agent the name and purpose. Enable **List servers** if the task also needs existing server or channel references. Keep it off when the task does not need that information.
+To delegate creation, enable **Create servers** in section 2 and give the agent the name and purpose. Enable **List servers and members** if the task also needs existing server or channel references. Keep it off when the task does not need that information.
### Agent — with the CLI
@@ -160,7 +162,7 @@ Each listed server has a `channels` array with `name`, `type` (`text` or `forum`
Open the server, then click **Invite to server** beside its name above the channel list. In **Invite friends to …**, find the friend and click **Invite**. Alook sends the invitation through a DM. **Invited** means the invitation was sent; the recipient still chooses whether to join.
-To delegate, enable **Invite friends to servers** in section 2. Give the agent the server and recipient’s full handles, including `#NNNN`. If you want the agent to find them, also enable **List servers** and **List friends**. You must belong to the server; the recipient must be your friend or your own bot.
+To delegate, enable **Invite friends to servers** in section 2. Give the agent the server and recipient’s full handles, including `#NNNN`. If you want the agent to find them, also enable **List servers and members** and **List friends**. You must belong to the server; the recipient must be your friend or your own bot.
### Agent — with the CLI
@@ -175,13 +177,15 @@ npx --yes @alook/daemon@latest use server --invite \
Use full returned handles. Friends include `is_my_bot`, true only for the code owner’s own bots. Send only the requested invitation. Report that it was sent; do not report that the recipient has joined.
+To verify who has joined, use `use server --members 'demo#0042'` with `server.read`. The result contains `server`, `url`, `members` (full handle and role), `hasMore`, and an optional `cursor`. Follow every page with `--cursor '<returned-cursor>'` before concluding that all expected accounts are present. An invitation result alone does not prove membership.
+
## 6. Send a message
### Human — in Alook
To send as yourself, open the channel or DM, write in the message box at the bottom, then click **Send message**.
-To delegate a send, enable **Send messages** in section 2; it starts disabled. Specify the destination, text and sender: yourself or one of your bots. Enable **List servers** if the agent needs to find a channel reference. Make sure the selected sender can access the destination; your channel list does not prove that your bot has access.
+To delegate a send, enable **Send messages** in section 2; it starts disabled. Specify the destination, text and sender: yourself or one of your bots. Enable **List servers and members** if the agent needs to find a channel reference. Make sure the selected sender can access the destination; your channel list does not prove that your bot has access.
Automation sends do not run a bot’s local PII filters. If the task depends on that local filtering pipeline, use the bot’s normal local CLI workflow instead.
diff --git a/src/web/public/onboard.md b/src/web/public/onboard.md
new file mode 100644
index 000000000..a07c2e207
--- /dev/null
+++ b/src/web/public/onboard.md
@@ -0,0 +1,13 @@
+# Set up my Alook team
+
+Read [agent.md](./agent.md) for commands and authorization. Use the backend, connection information and one-hour access code from the user's prompt. Keep the credentials private and use this site's origin for Automation calls.
+
+1. **Connect the computer.** Run the supplied daemon command, or check the supplied machine ID. Confirm the machine is online and the selected backend is available.
+
+2. **Agree on the team.** Based on the user's recent work and available project context, propose how to run that work in Alook with people and bots. Confirm the goal, responsibilities, server and first task with the user. Keep the team to at most **three bots**, including any you reuse.
+
+3. **Set up the server.** Create or reuse the agreed bots and server, then invite the bots. Check `use server --members '<server#NNNN>'` and follow any pagination to confirm all expected bots have joined.
+
+4. **Start the work.** Send the agreed first task to a server text channel with `use message --send --as me`. Identify yourself as the user's agent, explain their goal, and mention the bots with their assignments. Give the user the server UI link.
+
+After setup, expire the temporary code with `use expire` and leave the daemon running. If a step is blocked, tell the user what remains.
diff --git a/src/web/src/app/api/community/automation/servers/[id]/members/route.ts b/src/web/src/app/api/community/automation/servers/[id]/members/route.ts
new file mode 100644
index 000000000..d4fa2d158
--- /dev/null
+++ b/src/web/src/app/api/community/automation/servers/[id]/members/route.ts
@@ -0,0 +1,4 @@
+import { withAuth } from "@/lib/middleware/auth-policy"
+import { automationPolicy } from "@/lib/automation"
+import { readAutomationMembers } from "@/lib/community/automation-read.server"
+export const GET = withAuth(automationPolicy("server.read"), readAutomationMembers)
diff --git a/src/web/src/app/c/channels/layout.route-memory.dom.test.ts b/src/web/src/app/c/channels/layout.route-memory.dom.test.ts
index 4b65832d1..2710a1312 100644
--- a/src/web/src/app/c/channels/layout.route-memory.dom.test.ts
+++ b/src/web/src/app/c/channels/layout.route-memory.dom.test.ts
@@ -64,6 +64,8 @@ vi.mock("@/lib/perf/switch-mark", () => ({ markSwitch: vi.fn() }))
vi.mock("@/components/ui/dialog", () => ({
Dialog: ({ children }: { children: React.ReactNode }) => children,
DialogContent: ({ children }: { children: React.ReactNode }) => children,
+ DialogHeader: ({ children }: { children: React.ReactNode }) => children,
+ DialogFooter: ({ children }: { children: React.ReactNode }) => children,
}))
vi.mock("@/components/community/channels/use-channel-tree", () => ({
useChannelTree: () => [],
diff --git a/src/web/src/components/community/machines/pair-machine-sheet.dom.test.ts b/src/web/src/components/community/machines/pair-machine-sheet.dom.test.ts
index fe433a0a6..b1258a58b 100644
--- a/src/web/src/components/community/machines/pair-machine-sheet.dom.test.ts
+++ b/src/web/src/components/community/machines/pair-machine-sheet.dom.test.ts
@@ -51,7 +51,7 @@ vi.mock("@/components/community/shell/community-sheet", () => ({
),
}))
-import { PairMachineSheet, PairMachineSteps } from "./pair-machine-sheet"
+import { buildPairCommand, PairMachineSheet, PairMachineSteps } from "./pair-machine-sheet"
import { tid } from "@/lib/community/testids"
describe("PairMachineSheet desktop daemon integration", () => {
@@ -281,8 +281,25 @@ describe("PairMachineSheet desktop daemon integration", () => {
}))
const command = (await renderer.findByTestId(tid.machinePairCommand)).textContent ?? ""
- expect(command).toContain("pnpm daemon start --machine-key cmt_local_token")
+ expect(command).toContain("npx --yes @alook/daemon@latest daemon start --machine-key cmt_local_token")
expect(command).toContain("--server-url http://localhost:3000")
expect(command).toContain("--ws-url ws://localhost:8788/api/ws/community-daemon")
})
})
+
+
+describe("portable pairing commands", () => {
+ it.each([false, true])("uses an installable CLI for start and reconnect (local=%s)", (local) => {
+ mocks.isLocalServiceEnvironment.mockReturnValue(local)
+ vi.stubGlobal("location", { origin: "http://localhost:3235" })
+ const endpoints = local
+ ? " --server-url http://localhost:3235 --ws-url ws://localhost:8788/api/ws/community-daemon"
+ : ""
+ expect(buildPairCommand("test-key")).toBe(
+ `npx --yes @alook/daemon@latest daemon start --machine-key test-key${endpoints}`,
+ )
+ expect(buildPairCommand("test-key", "test-machine")).toBe(
+ `npx --yes @alook/daemon@latest daemon reconnect --id test-machine --machine-key test-key${endpoints}`,
+ )
+ })
+})
diff --git a/src/web/src/components/community/machines/pair-machine-sheet.tsx b/src/web/src/components/community/machines/pair-machine-sheet.tsx
index 4942c8229..e3423ac45 100644
--- a/src/web/src/components/community/machines/pair-machine-sheet.tsx
+++ b/src/web/src/components/community/machines/pair-machine-sheet.tsx
@@ -23,9 +23,7 @@ import { MachinePairMessageDiagram } from "./machine-pair-message-diagram"
// client-only effect — safe to touch `location` in the local branch.
export function buildPairCommand(machineKey: string, machineId?: string): string {
const isLocal = isLocalServiceEnvironment()
- const bin = isLocal
- ? "pnpm daemon"
- : "npx --yes @alook/daemon@latest daemon"
+ const bin = "npx --yes @alook/daemon@latest daemon"
const action = machineId
? `reconnect --id ${machineId} --machine-key ${machineKey}`
: `start --machine-key ${machineKey}`
diff --git a/src/web/src/components/community/onboarding/community-onboarding-form.navigation.dom.test.ts b/src/web/src/components/community/onboarding/community-onboarding-form.navigation.dom.test.ts
index cbebb8091..c6d962786 100644
--- a/src/web/src/components/community/onboarding/community-onboarding-form.navigation.dom.test.ts
+++ b/src/web/src/components/community/onboarding/community-onboarding-form.navigation.dom.test.ts
@@ -52,13 +52,19 @@ vi.mock("./initialize-community-onboarding", () => ({
initializeCommunityOnboarding: (...args: unknown[]) => mocks.initialize(...args),
}))
vi.mock("./onboarding-machine-dialog", () => ({
- OnboardingMachineDialog: ({ onChooseAnotherHarness, onConnected }: {
+ OnboardingMachineDialog: ({ onChooseAnotherHarness, onConnected, onExit }: {
+ onExit?: () => void
onChooseAnotherHarness: () => void
onConnected: (id: string) => void
}) => createElement("div", {}, createElement("button", {
"data-testid": "recover-harness",
onClick: onChooseAnotherHarness,
- }), createElement("button", { onClick: () => onConnected("machine-1") }, "Machine connected")),
+ }), createElement("button", { onClick: () => onConnected("machine-1") }, "Machine connected"), createElement("button", { onClick: onExit }, "Exit manual")),
+}))
+vi.mock("./onboarding-agent-dialog", () => ({
+ OnboardingAgentDialog: ({ onExit }: { onExit: () => void }) => createElement("div", {},
+ createElement("p", {}, "Agent Setup"),
+ createElement("button", { onClick: onExit }, "Exit agent")),
}))
vi.mock("./onboarding-select-dialog", () => ({
OnboardingSelectDialog: ({ value, onValueChange, onSubmit }: {
@@ -113,6 +119,34 @@ describe("CommunityOnboardingForm room navigation", () => {
})
})
+ it("defaults to Agent Setup and supports Manual and exit without creating a team", async () => {
+ mocks.state = { status: "active", stage: "harness" }
+ render(createElement(CommunityOnboardingForm))
+ fireEvent.click(screen.getByRole("button", { name: "Finish setup" }))
+ expect(screen.getByText("Agent Setup")).toBeInTheDocument()
+ expect(mocks.initialize).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole("button", { name: "Manual" }))
+ expect(screen.getByRole("button", { name: "Machine connected" })).toBeInTheDocument()
+ fireEvent.click(screen.getByRole("button", { name: "Exit manual" }))
+ expect(owner.runtime.ui.get().onboardingState).toBeNull()
+ expect(mocks.initialize).not.toHaveBeenCalled()
+ })
+
+ it.each(["machine", "model", "identity"])("keeps outer mode controls available from manual %s", (stage) => {
+ mocks.state = { status: "active", stage, harness: "opencode", setupMode: "manual", machineId: "machine-1" }
+ render(createElement(CommunityOnboardingForm))
+ const agent = screen.getByTestId("onboarding-mode-agent")
+ expect(agent).toBeEnabled()
+ fireEvent.click(agent)
+ expect(screen.getByText("Agent Setup")).toBeInTheDocument()
+ expect(screen.getByTestId("onboarding-mode-agent")).toBe(agent)
+ fireEvent.click(screen.getByTestId("onboarding-mode-manual"))
+ expect(screen.getByRole("button", { name: "Machine connected" })).toBeInTheDocument()
+ fireEvent.click(screen.getByRole("button", { name: "Exit setup" }))
+ expect(owner.runtime.ui.get().onboardingState).toBeNull()
+ expect(mocks.initialize).not.toHaveBeenCalled()
+ })
+
it("completes only after the shell commits the public-channel pathname", async () => {
const rendered = render(createElement(CommunityOnboardingForm))
diff --git a/src/web/src/components/community/onboarding/community-onboarding-form.tsx b/src/web/src/components/community/onboarding/community-onboarding-form.tsx
index f7873e039..a6dd49585 100644
--- a/src/web/src/components/community/onboarding/community-onboarding-form.tsx
+++ b/src/web/src/components/community/onboarding/community-onboarding-form.tsx
@@ -12,8 +12,14 @@ import { writeCommunityProfilePatches } from "@/lib/community/profile-seed"
import { communityKeys } from "@/lib/query-keys"
import { usePathname } from "next/navigation"
-import { advanceCommunityOnboarding, completeCommunityOnboarding, recoverCommunityOnboardingHarness, skipCommunityOnboarding, useCommunityOnboarding, readCommunityOnboardingState, updateCommunityOnboardingInitialization } from "@/lib/community-onboarding"
+import { finishCommunityOnboardingAgentSetup, switchCommunityOnboardingSetup, advanceCommunityOnboarding, completeCommunityOnboarding, recoverCommunityOnboardingHarness, skipCommunityOnboarding, useCommunityOnboarding, readCommunityOnboardingState, updateCommunityOnboardingInitialization } from "@/lib/community-onboarding"
+import { Button } from "@/components/ui/button"
+import { X } from "lucide-react"
+import { Dialog as SetupDialog } from "@base-ui/react/dialog"
+import { AppEdgeFade, appBackdropClassName } from "@/components/ui/app-edge-fade"
+import { OnboardingSurface } from "./onboarding-surface"
+import { OnboardingAgentDialog } from "./onboarding-agent-dialog"
import { OnboardingMachineDialog } from "./onboarding-machine-dialog"
import {
ONBOARDING_HARNESSES,
@@ -33,7 +39,7 @@ function harnessLabel(value?: string) {
return ONBOARDING_HARNESSES.find((option) => option.value === value)?.label ?? "your harness"
}
-export function CommunityOnboardingForm() {
+function CommunityOnboardingSteps() {
const communityRuntime = useCommunityRuntime()
const pathname = usePathname()
const currentUser = useCurrentUser()
@@ -150,8 +156,9 @@ export function CommunityOnboardingForm() {
return (
<OnboardingSelectDialog
open
- onOpenChange={() => undefined}
- step={{ current: 1, total: totalSteps }}
+ onOpenChange={(open) => { if (!open) skipCommunityOnboarding(communityRuntime) }}
+ step={{ current: 1, total: 2 }}
+ dismissible
stepLabel="Your harness"
title="Which harness do you already use?"
description="Pick the setup that already runs your bots."
@@ -160,7 +167,7 @@ export function CommunityOnboardingForm() {
onValueChange={setHarness}
submitLabel="Continue"
onSubmit={(value) => {
- advanceCommunityOnboarding(communityRuntime, "harness", "machine", { harness: value })
+ advanceCommunityOnboarding(communityRuntime, "harness", "machine", { harness: value, setupMode: "agent" })
}}
testId={tid.onboardingHarnessDialog}
optionTestId={tid.onboardingHarnessOption}
@@ -168,6 +175,16 @@ export function CommunityOnboardingForm() {
)
}
+ if (state.stage === "machine" && state.setupMode === "agent") {
+ return <OnboardingAgentDialog
+ harness={state.harness ?? ""}
+ harnessLabel={harnessLabel(state.harness)}
+ onConnected={() => finishCommunityOnboardingAgentSetup(communityRuntime)}
+ onChooseAgent={() => recoverCommunityOnboardingHarness(communityRuntime)}
+ onExit={() => skipCommunityOnboarding(communityRuntime)}
+ />
+ }
+
if (state.stage === "machine") {
return (
<OnboardingMachineDialog
@@ -175,6 +192,7 @@ export function CommunityOnboardingForm() {
harness={state.harness ?? ""}
harnessLabel={harnessLabel(state.harness)}
totalSteps={totalSteps}
+ onExit={() => skipCommunityOnboarding(communityRuntime)}
onConnected={(machineId) => {
advanceCommunityOnboarding(communityRuntime, "machine", requiredModel ? "model" : "identity", { machineId, model: null })
}}
@@ -190,16 +208,17 @@ export function CommunityOnboardingForm() {
}
if (state.stage === "model") {
- return <OnboardingModelDialog runtime={selectedRuntime ?? { id: state.harness! }} model={model} onModelChange={setModel} onContinue={() => advanceCommunityOnboarding(communityRuntime, "model", "identity", { model })} />
+ return <OnboardingModelDialog onExit={() => skipCommunityOnboarding(communityRuntime)} runtime={selectedRuntime ?? { id: state.harness! }} model={model} onModelChange={setModel} onContinue={() => advanceCommunityOnboarding(communityRuntime, "model", "identity", { model })} />
}
if (state.stage === "identity") {
return (
<OnboardingSelectDialog
open
- onOpenChange={() => undefined}
+ onOpenChange={(open) => { if (!open) skipCommunityOnboarding(communityRuntime) }}
step={{ current: totalSteps, total: totalSteps }}
stepLabel="About you"
+ dismissible
title="Which best describes you?"
description="We’ll shape the room around your work."
options={[...ONBOARDING_IDENTITIES]}
@@ -227,6 +246,7 @@ export function CommunityOnboardingForm() {
if (state.stage === "initializing") {
return (
<OnboardingStatusDialog
+ onExit={() => skipCommunityOnboarding(communityRuntime)}
totalSteps={totalSteps}
status={initializationStatus === "idle" ? "loading" : initializationStatus}
currentStep={initializationStep}
@@ -258,3 +278,34 @@ export function CommunityOnboardingForm() {
return null
}
+
+export function CommunityOnboardingForm() {
+ const runtime = useCommunityRuntime()
+ const state = useCommunityOnboarding()
+ if (!state) return null
+ const selected = Boolean(state.harness)
+ const mode = state.setupMode === "agent" ? "agent" : "manual"
+ const switching = selected && ["machine", "model", "identity"].includes(state.stage)
+ return <SetupDialog.Root open onOpenChange={(open) => { if (!open) skipCommunityOnboarding(runtime) }}>
+ <SetupDialog.Portal>
+ <SetupDialog.Backdrop className={`fixed inset-0 z-50 ${appBackdropClassName}`}><AppEdgeFade /></SetupDialog.Backdrop>
+ <SetupDialog.Popup aria-label="Set up Alook" data-testid="onboarding-surface" className="fixed top-1/2 left-1/2 z-50 flex max-h-[calc(100dvh-2rem)] w-[calc(100%-2rem)] max-w-xl -translate-x-1/2 -translate-y-1/2 flex-col gap-1 text-foreground outline-none">
+ <OnboardingSurface>
+ <header className="flex shrink-0 items-center justify-between gap-4 px-2">
+ <nav aria-label="Setup method" className="flex gap-4">
+ {selected ? (["agent", "manual"] as const).map((value) => <button
+ key={value} type="button" data-testid={`onboarding-mode-${value}`} aria-pressed={mode === value}
+ disabled={!switching} onClick={() => { if (mode !== value) switchCommunityOnboardingSetup(runtime, value) }}
+ className={`inline-flex min-h-11 items-center bg-transparent px-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed ${mode === value ? "text-foreground" : "text-muted-foreground hover:text-foreground"}`}
+ ><span className={`border-b-2 pb-1 ${mode === value ? "border-foreground" : "border-transparent"}`}>{value === "agent" ? "Agent" : "Manual"}</span></button>) : <span className="text-sm text-muted-foreground">Set up Alook</span>}
+ </nav>
+ <Button type="button" variant="ghost" size="icon" aria-label="Exit setup" title="Exit setup" className="size-11 text-foreground" onClick={() => skipCommunityOnboarding(runtime)}><X aria-hidden className="size-4" /></Button>
+ </header>
+ <div className="min-h-0 overflow-y-auto thin-scrollbar rounded-xl bg-popover text-popover-foreground shadow-(--e2)">
+ <CommunityOnboardingSteps />
+ </div>
+ </OnboardingSurface>
+ </SetupDialog.Popup>
+ </SetupDialog.Portal>
+ </SetupDialog.Root>
+}
diff --git a/src/web/src/components/community/onboarding/onboarding-agent-dialog.dom.test.tsx b/src/web/src/components/community/onboarding/onboarding-agent-dialog.dom.test.tsx
new file mode 100644
index 000000000..c88e24e39
--- /dev/null
+++ b/src/web/src/components/community/onboarding/onboarding-agent-dialog.dom.test.tsx
@@ -0,0 +1,141 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { act, fireEvent, screen, waitFor, render as renderDom } from "@/test/react-dom-harness"
+import { renderCommunity as render } from "@/test/community-owner-harness"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import type { CommunityMachineSummary } from "@alook/shared"
+const mocks = vi.hoisted(() => ({
+ request: vi.fn(), refetch: vi.fn(), copy: vi.fn(),
+ machines: [] as CommunityMachineSummary[],
+}))
+vi.mock("@/lib/api/client", () => ({ apiFetch: mocks.request }))
+vi.mock("@/hooks/community/use-machines", () => ({
+ useMachines: () => ({ machines: mocks.machines, isSuccess: true, refetch: mocks.refetch }),
+}))
+vi.mock("../machines/pair-machine-sheet", () => ({ buildPairCommand: (key: string, id?: string) => id ? `reconnect ${id} ${key}` : `pair ${key}` }))
+import { OnboardingAgentDialog } from "./onboarding-agent-dialog"
+const pair = () => ({ tokenId: "fixture-pair", expiresAt: new Date(Date.now() + 900_000).toISOString() })
+const code = () => ({ secret: "fixture-code", accessCode: { id: "code-1", name: "onboard", expiresAt: new Date(Date.now() + 3_600_000).toISOString() } })
+const props = () => ({ harness: "codex", harnessLabel: "Codex", onConnected: vi.fn(), onChooseAgent: vi.fn(), onExit: vi.fn() })
+beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.machines = []
+ mocks.request.mockImplementation(async (path: string) => path.endsWith("/pair") || path.endsWith("/reconnect") ? pair() : code())
+ Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText: mocks.copy.mockResolvedValue(undefined) } })
+})
+describe("Agent Setup", () => {
+ it("prepares only pairing and one-hour authorization, and copies the complete handoff", async () => {
+ render(<OnboardingAgentDialog {...props()} />)
+ await waitFor(() => expect(screen.getByRole("button", { name: "Copy prompt" })).toBeEnabled())
+ expect(mocks.request).toHaveBeenCalledTimes(2)
+ const call = mocks.request.mock.calls.find(([path]) => path.includes("access-codes"))!
+ expect(JSON.parse(call[1].body)).toEqual({
+ name: "onboard", expiresIn: "1h",
+ permissions: ["bot.create", "server.create", "server.invite", "message.send", "machine.read", "friend.read", "server.read"].map((permission) => ({ permission, limit: permission === "bot.create" ? 3 : 64, period: "hour" })),
+ })
+ fireEvent.click(screen.getByRole("button", { name: "Copy prompt" }))
+ await waitFor(() => expect(mocks.copy).toHaveBeenCalledOnce())
+ expect(mocks.copy.mock.calls[0][0]).toContain(`Follow ${location.origin}/onboard.md`)
+ expect(mocks.copy.mock.calls[0][0]).toContain("/onboard.md")
+ expect(mocks.copy.mock.calls[0][0]).toContain("pair fixture-pair")
+ expect(mocks.copy.mock.calls[0][0]).toContain("fixture-code")
+ expect(mocks.copy.mock.calls[0][0]).not.toContain("confirm the requirements with me")
+ expect(mocks.copy.mock.calls[0][0]).not.toContain("no more than 3 bots")
+ })
+ it("waits for copy before ending setup with an already-online machine", async () => {
+ mocks.machines = [{ id: "machine-1", hostname: "Work Mac", status: "online", availableRuntimes: [{ id: "codex", status: "healthy" }] } as CommunityMachineSummary]
+ const input = props()
+ render(<OnboardingAgentDialog {...input} />)
+ await waitFor(() => expect(screen.getByRole("button", { name: "Copy prompt" })).toBeEnabled())
+ expect(mocks.request).toHaveBeenCalledTimes(1)
+ expect((screen.getByLabelText("Prompt for Codex") as HTMLTextAreaElement).value).toContain("Connected machine ID: machine-1")
+ expect(input.onConnected).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole("button", { name: "Copy prompt" }))
+ await waitFor(() => expect(input.onConnected).toHaveBeenCalledOnce())
+ })
+ it("reuses an unexpired pair key after an access-code failure", async () => {
+ mocks.request.mockImplementationOnce(async () => pair()).mockRejectedValueOnce(new Error("network"))
+ render(<OnboardingAgentDialog {...props()} />)
+ await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent("Couldn’t prepare"))
+ fireEvent.click(screen.getByRole("button", { name: "Try again" }))
+ await waitFor(() => expect(screen.getByRole("button", { name: "Copy prompt" })).toBeEnabled())
+ expect(mocks.request.mock.calls.filter(([path]) => path.endsWith("/pair"))).toHaveLength(1)
+ })
+ it("retires pending generation when changing agent", async () => {
+ let resolvePair!: (value: ReturnType<typeof pair>) => void
+ mocks.request.mockImplementationOnce(() => new Promise((resolve) => { resolvePair = resolve }))
+ const input = props()
+ render(<OnboardingAgentDialog {...input} />)
+ await waitFor(() => expect(mocks.request).toHaveBeenCalledOnce())
+ fireEvent.click(screen.getByRole("button", { name: "Change agent" }))
+ expect(input.onChooseAgent).toHaveBeenCalledOnce()
+ await act(async () => resolvePair(pair()))
+ expect(mocks.request).toHaveBeenCalledOnce()
+ expect(screen.queryByLabelText("Prompt for Codex")).not.toBeInTheDocument()
+ })
+ it("hides the previous account credentials immediately when the owner changes", async () => {
+ const first = await createCommunityQueryOwner("first")
+ const second = await createCommunityQueryOwner("second")
+ const input = props()
+ const view = renderDom(<CommunityTestProvider client={first.client} registry={first.registry} userId="first" retainOwner><OnboardingAgentDialog {...input} /></CommunityTestProvider>)
+ await waitFor(() => expect(screen.getByRole("button", { name: "Copy prompt" })).toBeEnabled())
+ mocks.request.mockReturnValue(new Promise(() => undefined))
+ view.rerender(<CommunityTestProvider client={second.client} registry={second.registry} userId="second" retainOwner><OnboardingAgentDialog {...input} /></CommunityTestProvider>)
+ expect(screen.queryByLabelText("Prompt for Codex")).not.toBeInTheDocument()
+ expect(screen.queryByRole("button", { name: "Copy prompt" })).not.toBeInTheDocument()
+ expect(mocks.copy).not.toHaveBeenCalled()
+ })
+ it("starts fresh credentials while the previous owner pair request is pending", async () => {
+ const first = await createCommunityQueryOwner("first")
+ const second = await createCommunityQueryOwner("second")
+ let finishOld!: (value: ReturnType<typeof pair>) => void
+ mocks.request.mockImplementationOnce(() => new Promise((resolve) => { finishOld = resolve }))
+ const input = props()
+ const view = renderDom(<CommunityTestProvider client={first.client} registry={first.registry} userId="first" retainOwner><OnboardingAgentDialog {...input} /></CommunityTestProvider>)
+ await waitFor(() => expect(mocks.request).toHaveBeenCalledOnce())
+ view.rerender(<CommunityTestProvider client={second.client} registry={second.registry} userId="second" retainOwner><OnboardingAgentDialog {...input} /></CommunityTestProvider>)
+ await waitFor(() => expect(screen.getByRole("button", { name: "Copy prompt" })).toBeEnabled())
+ expect(mocks.request).toHaveBeenCalledTimes(3)
+ await act(async () => finishOld({ ...pair(), tokenId: "old-owner-pair" }))
+ expect((screen.getByLabelText("Prompt for Codex") as HTMLTextAreaElement).value).not.toContain("old-owner-pair")
+ expect(mocks.request).toHaveBeenCalledTimes(3)
+ })
+ it("disables copying when credentials expire", async () => {
+ mocks.request.mockImplementation(async (path: string) => path.endsWith("/pair") ? { ...pair(), expiresAt: new Date(Date.now() - 1000).toISOString() } : code())
+ render(<OnboardingAgentDialog {...props()} />)
+ await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent("expired"))
+ expect(screen.queryByRole("button", { name: "Copy prompt" })).not.toBeInTheDocument()
+ expect(screen.queryByLabelText("Prompt for Codex")).not.toBeInTheDocument()
+ })
+ it("recovers when an online machine goes offline and reuses its valid code", async () => {
+ mocks.machines = [{ id: "machine-1", status: "online", availableRuntimes: [{ id: "codex", status: "healthy" }] } as CommunityMachineSummary]
+ const input = props()
+ const view = render(<OnboardingAgentDialog {...input} />)
+ await waitFor(() => expect(screen.getByRole("button", { name: "Copy prompt" })).toBeEnabled())
+ mocks.machines = [{ ...mocks.machines[0], status: "offline" } as CommunityMachineSummary]
+ view.rerender(<OnboardingAgentDialog {...input} />)
+ expect(screen.getByRole("alert")).toHaveTextContent("went offline")
+ fireEvent.click(screen.getByRole("button", { name: "Try again" }))
+ await waitFor(() => expect(screen.getByRole("button", { name: "Copy prompt" })).toBeEnabled())
+ expect(mocks.request.mock.calls.filter(([path]) => path.includes("access-codes"))).toHaveLength(1)
+ expect(mocks.request.mock.calls.some(([path]) => path === "/api/community/machines/machine-1/reconnect")).toBe(true)
+ expect((screen.getByLabelText("Prompt for Codex") as HTMLInputElement).value).toContain("reconnect machine-1 fixture-pair")
+ fireEvent.click(screen.getByRole("button", { name: "Copy prompt" }))
+ await waitFor(() => expect(screen.getByTestId("onboarding-agent-waiting")).toBeInTheDocument())
+ expect(input.onConnected).not.toHaveBeenCalled()
+ mocks.machines = [{ id: "machine-1", status: "online", availableRuntimes: [{ id: "codex", status: "healthy" }] } as CommunityMachineSummary]
+ view.rerender(<OnboardingAgentDialog {...input} />)
+ await waitFor(() => expect(input.onConnected).toHaveBeenCalledOnce())
+ })
+ it("stays on the copy page when the clipboard fails", async () => {
+ mocks.copy.mockRejectedValue(new Error("clipboard"))
+ const input = props()
+ render(<OnboardingAgentDialog {...input} />)
+ await waitFor(() => expect(screen.getByRole("button", { name: "Copy prompt" })).toBeEnabled())
+ fireEvent.click(screen.getByRole("button", { name: "Copy prompt" }))
+ await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent("Copy failed"))
+ expect(screen.queryByTestId("onboarding-agent-waiting")).not.toBeInTheDocument()
+ expect(input.onConnected).not.toHaveBeenCalled()
+ })
+
+})
diff --git a/src/web/src/components/community/onboarding/onboarding-agent-dialog.tsx b/src/web/src/components/community/onboarding/onboarding-agent-dialog.tsx
new file mode 100644
index 000000000..f9e8e069b
--- /dev/null
+++ b/src/web/src/components/community/onboarding/onboarding-agent-dialog.tsx
@@ -0,0 +1,149 @@
+"use client"
+
+import { useCallback, useEffect, useRef } from "react"
+import { useAtom, useCreateAtom } from "@tanstack/react-store"
+import { useMutation } from "@tanstack/react-query"
+import { AUTOMATION_READ_PERMISSIONS, AUTOMATION_WRITE_PERMISSIONS, isPresenceOnline, type AutomationAccessCodeCreateResponse } from "@alook/shared"
+import { Copy, RefreshCw, Loader2 } from "lucide-react"
+import { Button } from "@/components/ui/button"
+import { Input } from "@/components/ui/input"
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "./onboarding-surface"
+import { Skeleton } from "@/components/ui/skeleton"
+import { ProviderLogo } from "@/components/provider-logo"
+import { useMachines } from "@/hooks/community/use-machines"
+import { useCommunityMutationOrigin } from "@/hooks/community/community-origin"
+import { useCommunityViewSource } from "@/hooks/community/use-community-view-source"
+import { buildPairCommand } from "../machines/pair-machine-sheet"
+
+type Pair = { tokenId: string; expiresAt: string; machineId?: string }
+type Setup = { signal?: AbortSignal; pair?: Pair; code?: AutomationAccessCodeCreateResponse }
+function buildOnboardingAgentPrompt(input: { baseUrl: string; harness: string; command?: string; machineId?: string; secret: string }) {
+ return [
+ `Follow ${input.baseUrl}/onboard.md to set up my Alook team.`,
+ `Selected agent: ${input.harness}`,
+ input.command ? `Daemon connection command: ${input.command}` : `Connected machine ID: ${input.machineId}`,
+ `Onboard access code (valid for one hour): ${input.secret}`,
+ ].join("\n")
+}
+
+export function OnboardingAgentDialog({ harness, harnessLabel, onChooseAgent, onExit, onConnected }: {
+ harness: string; harnessLabel: string; onChooseAgent: () => void; onExit: () => void; onConnected: () => void
+}) {
+ const origin = useCommunityMutationOrigin()
+ const source = useCommunityViewSource(`onboarding-agent:${harness}`)
+ const { machines, isSuccess, isError, refetch } = useMachines({ refetchInterval: 2000 })
+ const machine = machines.find((item) => isPresenceOnline(item.status) && item.availableRuntimes?.some((runtime) => runtime.id === harness && runtime.status !== "unhealthy"))
+ const reconnectMachine = machines.find((item) => !isPresenceOnline(item.status) && item.availableRuntimes?.some((runtime) => runtime.id === harness))
+ const [storedSetup, setSetup] = useAtom(useCreateAtom<Setup>({}))
+ const setup = storedSetup.signal === source.signal ? storedSetup : {}
+ const [now, setNow] = useAtom(useCreateAtom(0))
+ const [copied, setCopied] = useAtom(useCreateAtom<"idle" | "copied" | "error">("idle"))
+ const [copiedSignal, setCopiedSignal] = useAtom(useCreateAtom<AbortSignal | null>(null))
+ const waiting = copied === "copied" && copiedSignal === source.signal
+ const waitingStatus = useRef<HTMLDivElement>(null)
+ useEffect(() => { if (waiting) waitingStatus.current?.focus() }, [waiting])
+ const started = useCreateAtom<AbortSignal | null>(null)
+ const lock = useCreateAtom<AbortSignal | null>(null)
+ const mutation = useMutation({
+ mutationKey: ["community", "onboarding-agent", harness], gcTime: 0, retry: false,
+ meta: { observabilityAction: "automation.access_code.create" },
+ mutationFn: async ({ assert, token }: { assert: ReturnType<typeof source.capture>; token: ReturnType<typeof origin.begin>["token"] }) => {
+ assert()
+ if (!machine && (!setup.pair || Date.parse(setup.pair.expiresAt) <= Date.now())) {
+ const endpoint = reconnectMachine ? `/api/community/machines/${reconnectMachine.id}/reconnect` : "/api/community/machines/pair"
+ const pair = await origin.request<Pair>(token, endpoint, { method: "POST", signal: assert.signal, assertActive: assert })
+ assert()
+ setSetup((current) => ({ ...(current.signal === assert.signal ? current : {}), signal: assert.signal, pair: { ...pair, machineId: reconnectMachine?.id } }))
+ }
+ if (!setup.code?.accessCode.expiresAt || Date.parse(setup.code.accessCode.expiresAt) <= Date.now()) {
+ const code = await origin.request<AutomationAccessCodeCreateResponse>(token, "/api/community/automation/access-codes", {
+ method: "POST", signal: assert.signal, assertActive: assert,
+ body: JSON.stringify({ name: "onboard", expiresIn: "1h", permissions: [...AUTOMATION_WRITE_PERMISSIONS, ...AUTOMATION_READ_PERMISSIONS].map((permission) => ({ permission, limit: permission === "bot.create" ? 3 : 64, period: "hour" })) }),
+ })
+ assert()
+ setSetup((current) => ({ ...(current.signal === assert.signal ? current : {}), signal: assert.signal, code }))
+ }
+ assert()
+ setNow(Date.now())
+ setCopied("idle")
+ },
+ })
+ const mutate = mutation.mutateAsync
+ const generate = useCallback(async () => {
+ if (lock.get() === source.signal) return
+ const assert = source.capture()
+ assert()
+ lock.set(assert.signal)
+ try { await mutate({ assert, token: origin.begin().token }) }
+ catch {}
+ finally { if (lock.get() === assert.signal) lock.set(null) }
+ }, [lock, source, origin, mutate])
+ useEffect(() => {
+ if (!isSuccess || started.get() === source.signal) return
+ started.set(source.signal)
+ void generate()
+ }, [isSuccess, started, source.signal, generate])
+ useEffect(() => {
+ const refresh = () => setNow(Date.now())
+ refresh()
+ const timer = setInterval(refresh, 1000)
+ window.addEventListener("focus", refresh)
+ return () => { clearInterval(timer); window.removeEventListener("focus", refresh) }
+ }, [setNow])
+ const current = mutation.variables?.assert.signal === source.signal
+ const pending = current && mutation.isPending
+ const failed = current && mutation.isError && !(mutation.error instanceof DOMException && mutation.error.name === "AbortError")
+ useEffect(() => {
+ if (!waiting || !machine) return
+ source.retire()
+ setSetup({})
+ onConnected()
+ }, [waiting, machine, source, setSetup, onConnected])
+ const needsConnection = Boolean(isSuccess && setup.code && !machine && !setup.pair && !pending)
+ const codeExpired = Boolean(setup.code && Date.parse(setup.code.accessCode.expiresAt ?? "") <= now)
+ const pairExpired = Boolean(!machine && setup.pair && Date.parse(setup.pair.expiresAt) <= now)
+ const ready = Boolean(setup.code && (machine || setup.pair) && !codeExpired && !pairExpired && !pending)
+ const prompt = ready && setup.code ? buildOnboardingAgentPrompt({
+ baseUrl: location.origin, harness: harnessLabel, secret: setup.code.secret,
+ ...(machine ? { machineId: machine.id } : { command: buildPairCommand(setup.pair!.tokenId, setup.pair!.machineId) }),
+ }) : ""
+ const exit = () => { source.retire(); setSetup({}); onExit() }
+ const leave = (action: () => void) => { source.retire(); setSetup({}); action() }
+ const handleCopy = useCallback(async () => {
+ if (!prompt) return
+ const assert = source.capture()
+ try {
+ assert()
+ if (Date.parse(setup.code!.accessCode.expiresAt!) <= Date.now() || (!machine && Date.parse(setup.pair!.expiresAt) <= Date.now())) { setNow(Date.now()); return }
+ await navigator.clipboard.writeText(prompt)
+ assert()
+ setCopiedSignal(assert.signal)
+ setCopied("copied")
+ } catch { try { assert(); setCopied("error") } catch {} }
+ }, [prompt, source, setup.code, setup.pair, machine, setNow, setCopiedSignal, setCopied])
+ return <Dialog open onOpenChange={(open) => { if (!open) exit() }}>
+ <DialogContent data-testid="onboarding-agent-dialog" className="border-0 p-6 shadow-none ring-0 sm:max-w-xl">
+ <div className="space-y-6 p-4 sm:p-6">
+ <div className="flex gap-1.5" role="progressbar" aria-label="Setup progress" aria-valuemin={0} aria-valuemax={2} aria-valuenow={2} aria-valuetext="Step 2 of 2">
+ <span className="h-1.5 flex-1 rounded-full bg-(--te)" /><span className="h-1.5 flex-1 rounded-full bg-(--ti)" />
+ </div>
+ <DialogHeader className="gap-3 text-left">
+ <ProviderLogo provider={harness} className="size-8" />
+ <DialogTitle className="text-2xl font-semibold tracking-tight">{waiting ? "Waiting for your computer" : `Continue in ${harnessLabel}`}</DialogTitle>
+ <DialogDescription>{waiting ? `Paste the copied prompt into ${harnessLabel}. Setup will close when your computer connects.` : `Copy this prompt and paste it into ${harnessLabel}.`}</DialogDescription>
+ </DialogHeader>
+ {waiting && !codeExpired && !pairExpired ? <div ref={waitingStatus} tabIndex={-1} data-testid="onboarding-agent-waiting" role="status" className="outline-none flex items-center gap-3 text-sm text-muted-foreground"><Loader2 aria-hidden className="size-4 animate-spin motion-reduce:animate-none" />Waiting for connection…</div> : <div className="space-y-3">
+ {ready ? <div className="relative">
+ <Input aria-label={`Prompt for ${harnessLabel}`} data-testid="onboarding-agent-prompt" readOnly value={prompt.replace(/\n+/g, " ")} spellCheck={false} autoComplete="off" className="h-11 truncate pr-12 text-sm" />
+ <Button type="button" variant="ghost" size="icon" aria-label="Copy prompt" title="Copy prompt" className="absolute top-0 right-0 size-11 rounded-l-none" onClick={handleCopy}><Copy aria-hidden className="size-4" /></Button>
+ </div> : failed || isError || codeExpired || pairExpired || needsConnection ? <div className="space-y-3">
+ <p role="alert" className="text-sm text-destructive">{codeExpired || pairExpired ? "Setup credentials expired. Refresh to continue." : needsConnection ? "Your computer went offline. Prepare a new connection to continue." : "Couldn’t prepare Agent Setup. Try again, or use Manual."}</p>
+ <Button type="button" variant="outline" className="h-11" disabled={pending} onClick={() => { if (isError) void refetch(); else void generate() }}><RefreshCw aria-hidden className="size-4" />Try again</Button>
+ </div> : <div role="status" aria-label="Preparing Agent Setup"><Skeleton className="h-11 w-full" /></div>}
+ {copied === "error" ? <p role="alert" className="text-sm text-destructive">Copy failed. Try again, or select the prompt and copy it.</p> : null}
+ </div>}
+ <Button type="button" variant="ghost" className="h-11 px-0 text-muted-foreground hover:bg-transparent hover:text-foreground" onClick={() => leave(onChooseAgent)}>Change agent</Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+}
diff --git a/src/web/src/components/community/onboarding/onboarding-machine-dialog.tsx b/src/web/src/components/community/onboarding/onboarding-machine-dialog.tsx
index 835fa9dd3..d7f532fe1 100644
--- a/src/web/src/components/community/onboarding/onboarding-machine-dialog.tsx
+++ b/src/web/src/components/community/onboarding/onboarding-machine-dialog.tsx
@@ -22,7 +22,7 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
-} from "@/components/ui/dialog"
+} from "./onboarding-surface"
import { useJoinServer } from "@/hooks/community/mutations/servers"
import { useMachines } from "@/hooks/community/use-machines"
import { tid } from "@/lib/community/testids"
@@ -35,6 +35,8 @@ export function OnboardingMachineDialog({
onConnected,
onChooseAnotherHarness,
onManageMachines,
+ onExit,
+ onAgentSetup,
previewConnectedMachine,
previewCommand,
}: {
@@ -45,6 +47,8 @@ export function OnboardingMachineDialog({
onConnected: (machineId: string) => void
onChooseAnotherHarness: () => void
onManageMachines: () => void
+ onExit?: () => void
+ onAgentSetup?: () => void
previewConnectedMachine?: { id: string; hostname: string }
previewCommand?: string
}) {
@@ -168,14 +172,14 @@ export function OnboardingMachineDialog({
}
return (
- <Dialog open={open}>
+ <Dialog open={open} onOpenChange={(nextOpen) => { if (!nextOpen) onExit?.() }}>
<DialogContent
data-testid={tid.onboardingMachineDialog}
- showCloseButton={false}
+ showCloseButton={Boolean(onExit)}
className="max-h-[calc(100dvh-2rem)] gap-0 overflow-y-auto border-0 p-0 shadow-(--e2) ring-0 thin-scrollbar sm:max-w-lg"
>
<DialogHeader className="gap-4 px-4 pt-4 pb-4 sm:px-6 sm:pt-6 sm:pb-6">
- <div className="flex gap-1" aria-label={`Step 2 of ${totalSteps}`}>
+ <div className="flex gap-1 pr-8" aria-label={`Step 2 of ${totalSteps}`}>
{Array.from({ length: totalSteps }, (_, index) => index + 1).map((step) => (
<span
key={step}
@@ -275,6 +279,7 @@ export function OnboardingMachineDialog({
</div>
<DialogFooter className="m-0 rounded-b-xl border-0 bg-transparent px-4 py-4 sm:px-6">
+ {onAgentSetup ? <Button type="button" variant="ghost" className="text-foreground h-11 sm:h-9" onClick={onAgentSetup}>Agent Setup</Button> : null}
{unavailableMachine ? (
<>
<Button
diff --git a/src/web/src/components/community/onboarding/onboarding-model-dialog.tsx b/src/web/src/components/community/onboarding/onboarding-model-dialog.tsx
index d7e9c94f3..81b9fbf02 100644
--- a/src/web/src/components/community/onboarding/onboarding-model-dialog.tsx
+++ b/src/web/src/components/community/onboarding/onboarding-model-dialog.tsx
@@ -3,25 +3,27 @@
import type { CommunityMachineRuntime } from "@alook/shared"
import { Button } from "@/components/ui/button"
import { ProviderLogo } from "@/components/provider-logo"
-import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "./onboarding-surface"
import { ModelField } from "../bots/model-field"
import { validateBotModel } from "../bots/bot-form-validation"
import { ONBOARDING_HARNESSES } from "./onboarding-form-options"
-export function OnboardingModelDialog({ runtime, model, onModelChange, onContinue }: {
+export function OnboardingModelDialog({ runtime, model, onModelChange, onContinue, onExit, onAgentSetup }: {
runtime: Pick<CommunityMachineRuntime, "id" | "reasoning">
model: string | null
onModelChange: (model: string | null) => void
+ onExit?: () => void
+ onAgentSetup?: () => void
onContinue: () => void
}) {
const error = validateBotModel(model, runtime.id)
const backendLabel = ONBOARDING_HARNESSES.find((option) => option.value === runtime.id)?.label ?? runtime.id
return (
- <Dialog open>
- <DialogContent showCloseButton={false} className="max-h-[calc(100dvh-2rem)] gap-0 overflow-y-auto border-0 p-0 shadow-(--e2) ring-0 thin-scrollbar sm:max-w-md">
+ <Dialog open onOpenChange={(open) => { if (!open) onExit?.() }}>
+ <DialogContent showCloseButton={Boolean(onExit)} className="max-h-[calc(100dvh-2rem)] gap-0 overflow-y-auto border-0 p-0 shadow-(--e2) ring-0 thin-scrollbar sm:max-w-md">
<form onSubmit={(event) => { event.preventDefault(); if (!error) onContinue() }}>
<DialogHeader className="gap-4 px-4 pt-4 pb-4 sm:px-6 sm:pt-6 sm:pb-6">
- <div className="flex gap-1.5" aria-label="Step 3 of 4">
+ <div className="flex gap-1.5 pr-8" aria-label="Step 3 of 4">
{[1, 2, 3, 4].map((step) => <span key={step} className={step <= 3 ? "h-1.5 flex-1 rounded-full bg-primary" : "h-1.5 flex-1 rounded-full bg-muted"} />)}
</div>
<DialogTitle className="flex flex-wrap items-center gap-x-2 text-2xl leading-tight font-semibold tracking-tight">
@@ -34,6 +36,7 @@ export function OnboardingModelDialog({ runtime, model, onModelChange, onContinu
<ModelField runtime={runtime} value={model} onChange={onModelChange} error={model ? error : undefined} />
</div>
<DialogFooter className="m-0 rounded-none border-0 bg-transparent px-4 py-4 sm:px-6">
+ {onAgentSetup ? <Button type="button" variant="ghost" className="text-foreground h-11 sm:h-9" onClick={onAgentSetup}>Agent Setup</Button> : null}
<Button type="submit" className="h-11 min-h-11 w-full sm:h-9 sm:min-h-9 sm:w-auto" disabled={Boolean(error)}>Continue</Button>
</DialogFooter>
</form>
diff --git a/src/web/src/components/community/onboarding/onboarding-preview-flow.test.ts b/src/web/src/components/community/onboarding/onboarding-preview-flow.test.ts
index fb8dc662f..a33649e82 100644
--- a/src/web/src/components/community/onboarding/onboarding-preview-flow.test.ts
+++ b/src/web/src/components/community/onboarding/onboarding-preview-flow.test.ts
@@ -81,7 +81,7 @@ describe("onboarding preview flow", () => {
]) {
const source = readFileSync(resolve(directory, filename), "utf8")
- expect(source).not.toMatch(/\b(?:Guide|Builder|agents?)\b/)
+ expect(source).not.toMatch(/\b(?:Guide|Builder)\b/)
}
expect(previewSource).toMatch(/\bbots?\b/)
diff --git a/src/web/src/components/community/onboarding/onboarding-select-dialog.contract.test.ts b/src/web/src/components/community/onboarding/onboarding-select-dialog.contract.test.ts
index 7cfe03976..384f2033e 100644
--- a/src/web/src/components/community/onboarding/onboarding-select-dialog.contract.test.ts
+++ b/src/web/src/components/community/onboarding/onboarding-select-dialog.contract.test.ts
@@ -10,7 +10,7 @@ const source = readFileSync(
describe("OnboardingSelectDialog contract", () => {
it("builds on the shared shadcn dialog, field, and radio primitives", () => {
- expect(source).toContain('from "@/components/ui/dialog"')
+ expect(source).toContain('from "./onboarding-surface"')
expect(source).toContain('from "@/components/ui/field"')
expect(source).toContain('from "@/components/ui/radio-group"')
expect(source).toContain('from "@/components/provider-logo"')
diff --git a/src/web/src/components/community/onboarding/onboarding-select-dialog.tsx b/src/web/src/components/community/onboarding/onboarding-select-dialog.tsx
index 596bb1d28..a16dddbc0 100644
--- a/src/web/src/components/community/onboarding/onboarding-select-dialog.tsx
+++ b/src/web/src/components/community/onboarding/onboarding-select-dialog.tsx
@@ -23,7 +23,7 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
-} from "@/components/ui/dialog"
+} from "./onboarding-surface"
import {
Field,
FieldContent,
@@ -166,7 +166,7 @@ export function OnboardingSelectDialog({
<form onSubmit={handleSubmit}>
<DialogHeader className="gap-4 px-4 pt-4 pb-4 sm:px-6 sm:pt-6 sm:pb-6">
{step ? (
- <div className="flex gap-1.5" aria-label={`Step ${step.current} of ${step.total}`}>
+ <div className="flex gap-1.5 pr-8" aria-label={`Step ${step.current} of ${step.total}`}>
{Array.from({ length: step.total }, (_, index) => (
<span
key={index}
diff --git a/src/web/src/components/community/onboarding/onboarding-status-dialog.tsx b/src/web/src/components/community/onboarding/onboarding-status-dialog.tsx
index e504c576b..ab9880ee9 100644
--- a/src/web/src/components/community/onboarding/onboarding-status-dialog.tsx
+++ b/src/web/src/components/community/onboarding/onboarding-status-dialog.tsx
@@ -13,7 +13,7 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
-} from "@/components/ui/dialog"
+} from "./onboarding-surface"
import { tid } from "@/lib/community/testids"
import { avatarInitial } from "@/lib/community/avatar"
import { useCanonicalCommunityProfile, useCanonicalCommunityServer } from "@/lib/community-db/projections"
@@ -33,6 +33,7 @@ export function OnboardingStatusDialog({
detail,
onRetry,
onContinue,
+ onExit,
}: {
status: "loading" | "error" | "success"
totalSteps?: number
@@ -41,6 +42,7 @@ export function OnboardingStatusDialog({
detail: string
onRetry: () => void
onContinue: () => void
+ onExit?: () => void
}) {
const currentStepIndex = ONBOARDING_INITIALIZATION_STEPS.indexOf(currentStep)
const server = useCanonicalCommunityServer(checkpoint.serverId)
@@ -51,15 +53,15 @@ export function OnboardingStatusDialog({
)
return (
- <Dialog open>
+ <Dialog open onOpenChange={(open) => { if (!open) onExit?.() }}>
<DialogContent
data-testid={tid.onboardingInitializeStatus}
- showCloseButton={false}
+ showCloseButton={Boolean(onExit)}
className="gap-0 overflow-hidden border-0 p-0 shadow-(--e2) ring-0 sm:max-w-md"
aria-busy={status === "loading"}
>
<DialogHeader className="gap-4 px-4 pt-4 pb-4 sm:px-6 sm:pt-6 sm:pb-6">
- <div className="flex gap-1" aria-label={`Step ${totalSteps} of ${totalSteps}`}>
+ <div className="flex gap-1 pr-8" aria-label={`Step ${totalSteps} of ${totalSteps}`}>
{Array.from({ length: totalSteps }, (_, index) => <span key={index} className={["h-1 flex-1 rounded-full bg-(--te)", "h-1 flex-1 rounded-full bg-(--ti)", "h-1 flex-1 rounded-full bg-(--tc)"][index % 3]} />)}
</div>
<div className="flex flex-col gap-2">
diff --git a/src/web/src/components/community/onboarding/onboarding-surface.tsx b/src/web/src/components/community/onboarding/onboarding-surface.tsx
new file mode 100644
index 000000000..c079c73d0
--- /dev/null
+++ b/src/web/src/components/community/onboarding/onboarding-surface.tsx
@@ -0,0 +1,28 @@
+"use client"
+
+import { createContext, useContext, type ComponentProps, type ReactNode } from "react"
+import * as Modal from "@/components/ui/dialog"
+import { cn } from "@/lib/utils"
+
+const InlineOnboarding = createContext(false)
+export function OnboardingSurface({ children }: { children: ReactNode }) {
+ return <InlineOnboarding.Provider value>{children}</InlineOnboarding.Provider>
+}
+export function Dialog(props: ComponentProps<typeof Modal.Dialog>) {
+ const inline = useContext(InlineOnboarding)
+ return inline ? <>{props.children}</> : <Modal.Dialog {...props} />
+}
+export function DialogContent(props: ComponentProps<typeof Modal.DialogContent>) {
+ const inline = useContext(InlineOnboarding)
+ return inline ? <section data-testid={(props as { "data-testid"?: string })["data-testid"]} aria-busy={props["aria-busy"]} className="w-full min-w-0">{props.children}</section> : <Modal.DialogContent {...props} />
+}
+export function DialogTitle(props: ComponentProps<typeof Modal.DialogTitle>) {
+ const inline = useContext(InlineOnboarding)
+ return inline ? <h2 className={cn("text-lg font-semibold text-foreground", props.className)}>{props.children}</h2> : <Modal.DialogTitle {...props} />
+}
+export function DialogDescription(props: ComponentProps<typeof Modal.DialogDescription>) {
+ const inline = useContext(InlineOnboarding)
+ return inline ? <p className={cn("text-sm text-muted-foreground", props.className)}>{props.children}</p> : <Modal.DialogDescription {...props} />
+}
+export const DialogHeader = Modal.DialogHeader
+export const DialogFooter = Modal.DialogFooter
diff --git a/src/web/src/components/community/settings/automation-settings.dom.test.tsx b/src/web/src/components/community/settings/automation-settings.dom.test.tsx
index 946f640bf..d9b3facd3 100644
--- a/src/web/src/components/community/settings/automation-settings.dom.test.tsx
+++ b/src/web/src/components/community/settings/automation-settings.dom.test.tsx
@@ -19,7 +19,7 @@ describe("Automation form", () => {
const user = setupUser(), save = vi.fn().mockResolvedValue(undefined)
render(<AutomationCodeForm pending={false} onCancel={() => {}} onSave={save} />)
await user.type(screen.getByRole("textbox", { name: "Name" }), "Deploy")
- for (const name of ["List machines", "List friends", "List servers"]) await user.click(screen.getByRole("checkbox", { name }))
+ for (const name of ["List machines", "List friends", "List servers and members"]) await user.click(screen.getByRole("checkbox", { name }))
await user.click(screen.getByRole("button", { name: "Create access code" }))
expect(save).not.toHaveBeenCalled()
expect(screen.getByRole("alert")).toHaveTextContent("at least one permission")
@@ -37,7 +37,7 @@ describe("Automation form", () => {
expect(screen.getByRole("group", { name: /^Read$/ })).toBeInTheDocument()
expect(screen.getByRole("group", { name: /^Write$/ })).toBeInTheDocument()
expect(screen.getAllByRole("checkbox")).toHaveLength(7)
- for (const name of ["List machines", "List friends", "List servers"]) expect(screen.getByRole("checkbox", { name })).toBeChecked()
+ for (const name of ["List machines", "List friends", "List servers and members"]) expect(screen.getByRole("checkbox", { name })).toBeChecked()
for (const name of ["Create bots", "Create servers", "Invite friends to servers", "Send messages"]) expect(screen.getByRole("checkbox", { name })).not.toBeChecked()
await user.type(screen.getByRole("textbox", { name: "Name" }), "Invitations")
await user.click(screen.getByRole("checkbox", { name: "Invite friends to servers" }))
@@ -56,7 +56,7 @@ describe("Automation form", () => {
const user = setupUser(), save = vi.fn().mockResolvedValue(undefined)
render(<AutomationCodeForm pending={false} onCancel={() => {}} onSave={save} />)
await user.type(screen.getByRole("textbox", { name: "Name" }), "Messages")
- for (const name of ["List machines", "List friends", "List servers"]) await user.click(screen.getByRole("checkbox", { name }))
+ for (const name of ["List machines", "List friends", "List servers and members"]) await user.click(screen.getByRole("checkbox", { name }))
await user.click(screen.getByRole("checkbox", { name: "Send messages" }))
await user.click(screen.getByRole("button", { name: "Advanced" }))
await user.clear(screen.getByRole("spinbutton", { name: "Send messages request limit" }))
diff --git a/src/web/src/components/community/settings/automation-settings.tsx b/src/web/src/components/community/settings/automation-settings.tsx
index 88a19482b..b11121821 100644
--- a/src/web/src/components/community/settings/automation-settings.tsx
+++ b/src/web/src/components/community/settings/automation-settings.tsx
@@ -28,7 +28,7 @@ const permissionOptions = [
{ permission: "message.send", label: "Send messages", group: "Write" },
{ permission: "machine.read", label: "List machines", group: "Read" },
{ permission: "friend.read", label: "List friends", group: "Read" },
- { permission: "server.read", label: "List servers", group: "Read" },
+ { permission: "server.read", label: "List servers and members", group: "Read" },
] as const
const permissionColors: Record<"Read" | "Write", CSSProperties & { "--forum-tag-hue": number }> = {
Read: { "--forum-tag-hue": 145 },
diff --git a/src/web/src/lib/automation-routes.test.ts b/src/web/src/lib/automation-routes.test.ts
index b91d85a97..f4b2a145c 100644
--- a/src/web/src/lib/automation-routes.test.ts
+++ b/src/web/src/lib/automation-routes.test.ts
@@ -8,7 +8,7 @@ vi.mock("@/lib/middleware/auth", () => ({ humanAuthPolicy: { resolve: () => { th
vi.mock("@alook/shared", async (original) => ({ ...await original<typeof import("@alook/shared")>(), queries: { automation: { authenticateAccessCode: mocks.authenticate } } }))
vi.mock("@/lib/community/create-bot.server", () => ({ createBotForUser: mocks.action }))
vi.mock("@/lib/community/create-server.server", () => ({ createServerForUser: mocks.action }))
-vi.mock("@/lib/community/automation-read.server", () => ({ readAutomationMachines: mocks.action, readAutomationFriends: mocks.action, readAutomationServers: mocks.action }))
+vi.mock("@/lib/community/automation-read.server", () => ({ readAutomationMachines: mocks.action, readAutomationFriends: mocks.action, readAutomationServers: mocks.action, readAutomationMembers: mocks.action }))
vi.mock("@/lib/community/automation-invite.server", () => ({ inviteAutomationFriend: mocks.action }))
vi.mock("@/lib/community/automation-message.server", () => ({ sendAutomationMessage: mocks.action }))
import { POST as createBot } from "@/app/api/community/automation/bots/route"
@@ -17,7 +17,8 @@ import { GET as machines } from "@/app/api/community/automation/machines/route"
import { GET as friends } from "@/app/api/community/automation/friends/route"
import { POST as invite } from "@/app/api/community/automation/servers/[id]/invites/route"
import { POST as send } from "@/app/api/community/automation/messages/route"
-const routes = [[createBot, "bot.create"], [createServer, "server.create"], [servers, "server.read"], [machines, "machine.read"], [friends, "friend.read"], [invite, "server.invite"], [send, "message.send"]] as const
+import { GET as members } from "@/app/api/community/automation/servers/[id]/members/route"
+const routes = [[createBot, "bot.create"], [createServer, "server.create"], [servers, "server.read"], [members, "server.read"], [machines, "machine.read"], [friends, "friend.read"], [invite, "server.invite"], [send, "message.send"]] as const
const secret = "aac_" + "a".repeat(64)
const req = (token = secret) => new NextRequest("http://localhost/api/community/automation/test", { headers: { Authorization: `Bearer ${token}`, cookie: "session=present" } })
beforeEach(() => {
diff --git a/src/web/src/lib/community-onboarding.test.ts b/src/web/src/lib/community-onboarding.test.ts
index d2699b94c..d97bf4bdc 100644
--- a/src/web/src/lib/community-onboarding.test.ts
+++ b/src/web/src/lib/community-onboarding.test.ts
@@ -21,6 +21,8 @@ import { QueryClient } from "@tanstack/react-query";
import { createCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections";
import {
+ finishCommunityOnboardingAgentSetup,
+ switchCommunityOnboardingSetup,
advanceCommunityOnboarding,
completeCommunityOnboarding,
readCommunityOnboardingState,
@@ -41,12 +43,41 @@ describe("community onboarding journey", () => {
vi.clearAllMocks();
});
+ it("finishes an agent handoff without counting it as skipped or a completed team", () => {
+ startCommunityOnboarding(runtime());
+ finishCommunityOnboardingAgentSetup(runtime());
+ expect(readCommunityOnboardingState(runtime())?.stage).toBe("harness");
+ advanceCommunityOnboarding(runtime(), "harness", "machine", { harness: "codex", setupMode: "manual" });
+ finishCommunityOnboardingAgentSetup(runtime());
+ expect(readCommunityOnboardingState(runtime())?.stage).toBe("machine");
+ switchCommunityOnboardingSetup(runtime(), "agent");
+ finishCommunityOnboardingAgentSetup(runtime());
+ expect(readCommunityOnboardingState(runtime())).toBeNull();
+ expect(analytics.skipped).not.toHaveBeenCalled();
+ expect(analytics.product).not.toHaveBeenCalled();
+ });
+
afterEach(() => {
void registry.cleanup();
registry.queryClient.clear();
vi.unstubAllGlobals();
});
+ it("switches setup methods before creation and preserves manual choices", () => {
+ startCommunityOnboarding(runtime());
+ advanceCommunityOnboarding(runtime(), "harness", "machine", { harness: "codex", setupMode: "agent" });
+ switchCommunityOnboardingSetup(runtime(), "manual");
+ expect(readCommunityOnboardingState(runtime())).toMatchObject({ stage: "machine", setupMode: "manual" });
+ advanceCommunityOnboarding(runtime(), "machine", "identity", { machineId: "machine-1", model: "model-1" });
+ switchCommunityOnboardingSetup(runtime(), "agent");
+ expect(readCommunityOnboardingState(runtime())).toMatchObject({ stage: "machine", setupMode: "agent", machineId: "machine-1", model: "model-1" });
+ advanceCommunityOnboarding(runtime(), "machine", "initializing");
+ switchCommunityOnboardingSetup(runtime(), "manual");
+ expect(readCommunityOnboardingState(runtime())).toMatchObject({ stage: "initializing", setupMode: "agent" });
+ skipCommunityOnboarding(runtime());
+ expect(readCommunityOnboardingState(runtime())).toBeNull();
+ });
+
it("starts once per explicit owner and never shares another account journey", () => {
expect(readCommunityOnboardingState(runtime())).toBeNull();
expect(startCommunityOnboarding(runtime())).toEqual({ status: "active", stage: "harness" });
diff --git a/src/web/src/lib/community-onboarding.ts b/src/web/src/lib/community-onboarding.ts
index 6071bb404..dab18cf6a 100644
--- a/src/web/src/lib/community-onboarding.ts
+++ b/src/web/src/lib/community-onboarding.ts
@@ -14,6 +14,7 @@ import {
} from "@/lib/analytics";
type JourneyResources = {
+ setupMode?: "agent" | "manual";
harness?: string;
machineId?: string;
model?: string | null;
@@ -84,6 +85,12 @@ export function updateCommunityOnboardingInitialization(runtime: CommunityRuntim
return publish(runtime, { ...current, initialization: update(current.initialization ?? { checkpoint: {}, step: "creating-bots", result: null, pendingDestination: null }) });
}
+export function switchCommunityOnboardingSetup(runtime: CommunityRuntime, setupMode: "agent" | "manual") {
+ const current = readCommunityOnboardingState(runtime);
+ if (!current?.harness || !["machine", "model", "identity"].includes(current.stage)) return current;
+ return publish(runtime, { ...current, stage: "machine", setupMode });
+}
+
export function recoverCommunityOnboardingHarness(runtime: CommunityRuntime) {
const currentState = readCommunityOnboardingState(runtime);
if (currentState?.status !== "active" || currentState.stage !== "machine") {
@@ -122,6 +129,14 @@ export function completeCommunityOnboarding(runtime: CommunityRuntime, pathname?
return null;
}
+export function finishCommunityOnboardingAgentSetup(runtime: CommunityRuntime) {
+ const state = readCommunityOnboardingState(runtime);
+ if (state?.stage !== "machine" || state.setupMode !== "agent") return state;
+ publish(runtime, null);
+ trackCommunityOnboardingStageCompleted("machine");
+ return null;
+}
+
export function skipCommunityOnboarding(runtime: CommunityRuntime) {
const currentState = readCommunityOnboardingState(runtime);
if (!currentState) return null;
diff --git a/src/web/src/lib/community/automation-members.sql.test.ts b/src/web/src/lib/community/automation-members.sql.test.ts
new file mode 100644
index 000000000..1e7f897f1
--- /dev/null
+++ b/src/web/src/lib/community/automation-members.sql.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+import { createCommunitySqliteDb } from "@/test/community-sqlite-db"
+const state = vi.hoisted(() => ({ db: null as unknown }))
+vi.mock("@/lib/db", () => ({ getPrimaryDb: () => state.db }))
+import { readAutomationMembers } from "./automation-read.server"
+const fixtures: ReturnType<typeof createCommunitySqliteDb>[] = []
+afterEach(() => { for (const fixture of fixtures.splice(0)) fixture.sqlite.close() })
+it("verifies persisted membership across pages without counting invited or deleted accounts", async () => {
+ const fixture = createCommunitySqliteDb()
+ fixtures.push(fixture)
+ state.db = fixture.db
+ const stamp = "2026-10-31T00:00:00.000Z"
+ const user = fixture.sqlite.prepare('INSERT INTO user (id,email,name,discriminator,"avatarVersion","createdAt","updatedAt","deletedAt") VALUES (?,?,?,?,0,?,?,?)')
+ user.run("owner", "owner@test", "Owner", "0001", stamp, stamp, null)
+ user.run("outsider", "outsider@test", "Outsider", "0001", stamp, stamp, null)
+ user.run("invited", "invited@test", "Invited", "0001", stamp, stamp, null)
+ user.run("deleted", "deleted@test", "Deleted", "0001", stamp, stamp, stamp)
+ fixture.sqlite.prepare("INSERT INTO community_server (id,name,discriminator,description,owner_id) VALUES ('server','team','0042','','owner')").run()
+ const member = fixture.sqlite.prepare("INSERT INTO community_server_member (id,server_id,user_id,role,joined_at) VALUES (?,'server',?,'member',?)")
+ member.run("member-owner", "owner", stamp)
+ member.run("member-deleted", "deleted", stamp)
+ for (let index = 0; index < 101; index++) {
+ const id = `bot-${index.toString().padStart(3, "0")}`
+ user.run(id, `${id}@test`, id, "0001", stamp, stamp, null)
+ member.run(`member-${id}`, id, stamp)
+ }
+ const ctx = { env: { DB: {} } as Env, userId: "owner", params: { id: "team#0042" }, beforeCreate: vi.fn(async (): Promise<Response | null> => null) }
+ const first = await (await readAutomationMembers(new NextRequest("https://test/api/members"), ctx)).json()
+ expect(first.members).toHaveLength(100)
+ expect(first.hasMore).toBe(true)
+ const second = await (await readAutomationMembers(new NextRequest(`https://test/api/members?${new URLSearchParams({ cursor: first.cursor })}`), ctx)).json()
+ expect(second.hasMore).toBe(false)
+ const handles = [...first.members, ...second.members].map((value: { handle: string }) => value.handle)
+ expect(new Set(handles).size).toBe(102)
+ expect(handles).toContain("Owner#0001")
+ expect(handles).not.toContain("Invited#0001")
+ expect(handles).not.toContain("Deleted#0001")
+ expect((await readAutomationMembers(new NextRequest("https://test/api/members"), { ...ctx, userId: "outsider" })).status).toBe(404)
+})
diff --git a/src/web/src/lib/community/automation-members.test.ts b/src/web/src/lib/community/automation-members.test.ts
new file mode 100644
index 000000000..73a58c570
--- /dev/null
+++ b/src/web/src/lib/community/automation-members.test.ts
@@ -0,0 +1,46 @@
+import { beforeEach, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+const mocks = vi.hoisted(() => ({ server: vi.fn(), members: vi.fn() }))
+vi.mock("@alook/shared", async (original) => ({ ...await original<typeof import("@alook/shared")>(), queries: {
+ communityServer: { resolveServerByNameForMember: mocks.server },
+ communityMember: { listMembersPaginated: mocks.members },
+} }))
+vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({ primary: true }) }))
+import { readAutomationMembers } from "./automation-read.server"
+const request = (query = "") => new NextRequest(`https://alook.test/api/community/automation/servers/team%230042/members${query}`)
+const context = () => ({ env: { DB: {} } as Env, userId: "owner", params: { id: "team#0042" }, beforeCreate: vi.fn(async (): Promise<Response | null> => null) })
+beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.server.mockResolvedValue([{ id: "server", name: "team", discriminator: "0042" }])
+ mocks.members.mockResolvedValue({ members: [{ userName: "Helper", discriminator: "0001", role: "member", userId: "private", email: "[email protected]" }], hasMore: true, cursor: { joinedAt: "2026-10-31", id: "last-member" } })
+})
+it("scopes server lookup to the code owner before reading a bounded roster and strips private fields", async () => {
+ const ctx = context()
+ const response = await readAutomationMembers(request(), ctx)
+ expect(response.status).toBe(200)
+ expect(await response.json()).toEqual({ server: "team#0042", url: "https://alook.test/c/channels/server", members: [{ handle: "Helper#0001", role: "member" }], hasMore: true, cursor: "2026-10-31|last-member" })
+ expect(mocks.server).toHaveBeenCalledExactlyOnceWith({ primary: true }, "owner", "team#0042")
+ expect(mocks.members).toHaveBeenCalledExactlyOnceWith({ primary: true }, "server", { cursor: undefined, limit: 100 })
+ expect(ctx.beforeCreate).toHaveBeenCalledOnce()
+})
+it("reads the next page and reports the end without an invented cursor", async () => {
+ mocks.members.mockResolvedValue({ members: [], hasMore: false, cursor: null })
+ expect(await (await readAutomationMembers(request("?cursor=2026-10-31%7Clast-member"), context())).json()).toEqual({ server: "team#0042", url: "https://alook.test/c/channels/server", members: [], hasMore: false })
+ expect(mocks.members.mock.lastCall?.[2]).toEqual({ cursor: { joinedAt: "2026-10-31", id: "last-member" }, limit: 100 })
+})
+it("does not expose a nonmember server or read its members", async () => {
+ mocks.server.mockResolvedValue([])
+ const response = await readAutomationMembers(request(), context())
+ expect(response.status).toBe(404)
+ expect(mocks.members).not.toHaveBeenCalled()
+})
+it("rejects malformed input before quota and rejects exhausted quota before resource queries", async () => {
+ const ctx = context()
+ expect((await readAutomationMembers(request(), { ...ctx, params: { id: "bad" } })).status).toBe(400)
+ expect((await readAutomationMembers(request("?cursor=bad"), ctx)).status).toBe(400)
+ expect(ctx.beforeCreate).not.toHaveBeenCalled()
+ ctx.beforeCreate.mockResolvedValue(Response.json({ error: "limited" }, { status: 429 }))
+ expect((await readAutomationMembers(request(), ctx)).status).toBe(429)
+ expect(mocks.server).not.toHaveBeenCalled()
+ expect(mocks.members).not.toHaveBeenCalled()
+})
diff --git a/src/web/src/lib/community/automation-read.server.ts b/src/web/src/lib/community/automation-read.server.ts
index 914fb9f72..0a5278a09 100644
--- a/src/web/src/lib/community/automation-read.server.ts
+++ b/src/web/src/lib/community/automation-read.server.ts
@@ -1,7 +1,8 @@
-import { queries, formatHandle, formatCanonicalRef } from "@alook/shared"
+import { queries, formatHandle, formatCanonicalRef, parseNameAndTag, DEFAULT_MEMBERS_PAGE_SIZE } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { writeJSON } from "@/lib/middleware/helpers"
+import { writeJSON, writeError } from "@/lib/middleware/helpers"
import type { NextRequest } from "next/server"
+import { parseMemberCursor } from "./messages"
import { projectMachineBackends } from "./machine-options.server"
type ReadContext = { env: Env; userId: string; beforeCreate: () => Promise<Response | null> }
@@ -32,3 +33,24 @@ export async function readAutomationServers(_req: NextRequest, ctx: ReadContext)
})) }
}) })
}
+
+export async function readAutomationMembers(req: NextRequest, ctx: ReadContext & { params?: Record<string, string> }) {
+ const serverRef = ctx.params?.id ?? ""
+ if (!parseNameAndTag(serverRef)) return writeError("Use a full server handle", 400)
+ const cursorParam = new URL(req.url).searchParams.get("cursor")
+ const cursor = parseMemberCursor(cursorParam)
+ if (cursorParam && !cursor) return writeError("Invalid member cursor", 400)
+ const denied = await ctx.beforeCreate()
+ if (denied) return denied
+ const db = getPrimaryDb(ctx.env.DB)
+ const [server] = await queries.communityServer.resolveServerByNameForMember(db, ctx.userId, serverRef)
+ if (!server) return writeError("Server not found", 404)
+ const page = await queries.communityMember.listMembersPaginated(db, server.id, { cursor, limit: DEFAULT_MEMBERS_PAGE_SIZE })
+ return writeJSON({
+ server: formatHandle(server.name, server.discriminator),
+ url: `${new URL(req.url).origin}/c/channels/${encodeURIComponent(server.id)}`,
+ members: page.members.map((member) => ({ handle: formatHandle(member.userName ?? "", member.discriminator ?? "0000"), role: member.role ?? "member" })),
+ hasMore: page.hasMore,
+ cursor: page.cursor ? `${page.cursor.joinedAt}|${page.cursor.id}` : undefined,
+ })
+}
diff --git a/src/web/src/lib/observability/coverage.test.ts b/src/web/src/lib/observability/coverage.test.ts
index b664c6ed9..1b7c1913f 100644
--- a/src/web/src/lib/observability/coverage.test.ts
+++ b/src/web/src/lib/observability/coverage.test.ts
@@ -43,6 +43,7 @@ it("keeps existing mutation owners inventoried and semantic variants on the whit
})
const mutationCoverage = [
+ { file: "src/web/src/components/community/onboarding/onboarding-agent-dialog.tsx", owner: "OnboardingAgentDialog", action: "automation.access_code.create" },
{ file: "src/web/src/hooks/community/use-automation.ts", owner: "useAutomation", action: "automation.access_code.command" },
{ "file": "src/web/src/hooks/community/use-bot-memberships.ts", "owner": "useBotMemberships", "action": "community.command" },
{ "file": "src/web/src/hooks/community/mutations/bot-creation.ts", "owner": "useBotCreationDecision", "action": "bot.creation.decision" },
diff --git a/src/web/src/lib/observability/coverage.ts b/src/web/src/lib/observability/coverage.ts
index a0cbff516..6e930fe65 100644
--- a/src/web/src/lib/observability/coverage.ts
+++ b/src/web/src/lib/observability/coverage.ts
@@ -47,6 +47,7 @@ export const apiRoutes = [
"/api/community/automation/machines",
"/api/community/automation/friends",
"/api/community/automation/servers/[id]/invites",
+ "/api/community/automation/servers/[id]/members",
"/api/community/automation/machines/[id]/discover-models",
"/api/community/automation/messages",
"/api/community/automation/access-codes",
diff --git a/src/web/src/test/e2e-ui/31-machine-guide-motion.spec.ts b/src/web/src/test/e2e-ui/31-machine-guide-motion.spec.ts
index c9eda67b8..29f3065ad 100644
--- a/src/web/src/test/e2e-ui/31-machine-guide-motion.spec.ts
+++ b/src/web/src/test/e2e-ui/31-machine-guide-motion.spec.ts
@@ -21,11 +21,11 @@ test("first-signup mobile starts onboarding once and retains it on desktop", asy
await expect(onboarding.getByRole("heading", { name: "Which harness do you already use?" })).toBeVisible()
await page.getByTestId(tid.onboardingHarnessOption("grok")).click()
await onboarding.getByRole("button", { name: "Continue", exact: true }).click()
- await expect(page.getByTestId(tid.onboardingMachineDialog)).toBeVisible()
+ await expect(page.getByTestId("onboarding-agent-dialog")).toBeVisible()
await page.setViewportSize({ width: 1280, height: 800 })
await expect(page).toHaveURL(/\/c\/me\/machines$/)
- await expect(page.getByTestId(tid.onboardingMachineDialog)).toBeVisible()
+ await expect(page.getByTestId("onboarding-agent-dialog")).toBeVisible()
await expect(onboarding).toHaveCount(0)
})
@@ -44,7 +44,7 @@ test("first-signup desktop opens onboarding before the empty Machines guide", as
await expect(
onboarding.getByRole("heading", { name: "Which harness do you already use?" }),
).toBeVisible()
- await expect(onboarding.getByLabel("Step 1 of 3")).toBeVisible()
+ await expect(onboarding.getByLabel("Step 1 of 2")).toBeVisible()
await expect(page.getByTestId(tid.machineFirstSignupGuide)).toHaveCount(0)
const grok = page.getByTestId(tid.onboardingHarnessOption("grok"))
@@ -54,9 +54,23 @@ test("first-signup desktop opens onboarding before the empty Machines guide", as
await grok.click()
await onboarding.getByRole("button", { name: "Continue", exact: true }).click()
+ const agentStep = page.getByTestId("onboarding-agent-dialog")
+ await expect(agentStep).toBeVisible()
+ const manualMode = page.getByTestId("onboarding-mode-manual")
+ const agentMode = page.getByTestId("onboarding-mode-agent")
+ await manualMode.click()
+
const machineStep = page.getByTestId(tid.onboardingMachineDialog)
await expect(machineStep).toBeVisible()
await expect(machineStep.getByRole("heading", { name: /Connect your Grok Build machine/ }))
.toBeVisible()
await expect(machineStep.locator('[data-provider-logo="grok"]')).toBeVisible()
+ await agentMode.focus()
+ await page.keyboard.press("Enter")
+ await expect(agentStep).toBeVisible()
+ await expect(agentMode).toHaveAttribute("aria-pressed", "true")
+ await manualMode.focus()
+ await page.keyboard.press("Enter")
+ await expect(machineStep).toBeVisible()
+ await expect(manualMode).toHaveAttribute("aria-pressed", "true")
})
diff --git a/src/web/src/test/e2e/device-code.test.ts b/src/web/src/test/e2e/device-code.test.ts
index c9eb45cb7..5816a8e61 100644
--- a/src/web/src/test/e2e/device-code.test.ts
+++ b/src/web/src/test/e2e/device-code.test.ts
@@ -43,10 +43,19 @@ describe("retired CLI connection", () => {
expect(response.status).toBe(404)
})
- it.each(["/device", "/onboard.md"])("%s no longer offers the old CLI connection", async path => {
+ it.each(["/device"])("%s no longer offers the old CLI connection", async path => {
expect((await fetch(`${appUrl}${path}`, { redirect: "manual" })).status).toBe(404)
})
+ it("serves the current agent onboarding guide", async () => {
+ const response = await fetch(`${appUrl}/onboard.md`)
+ expect(response.status).toBe(200)
+ const guide = await response.text()
+ expect(guide).toContain("[agent.md](./agent.md)")
+ expect(guide).toContain("use server --members")
+ expect(guide).not.toContain("/api/auth/device")
+ })
+
it("keeps current Cookie login while rejecting an old CLI session bearer", async () => {
const path = "/api/community/users/me/profile"
expect((await sessionRequest(path, cookie)).status).toBe(200)