Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): default bot create to first selectable machine + runtime

Gener3358371a1f51
diff --git a/src/web/src/components/community/bots/create-bot-sheet.test.ts b/src/web/src/components/community/bots/create-bot-sheet.test.ts
new file mode 100644
index 000000000..833dcdf80
--- /dev/null
+++ b/src/web/src/components/community/bots/create-bot-sheet.test.ts
@@ -0,0 +1,350 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+
+// --- Pure helper unit tests -------------------------------------------------
+
+import {
+ normalizeRuntimes,
+ firstHealthyRuntimeId,
+ firstOnlineMachineId,
+} from "./create-bot-sheet"
+import type { CommunityMachineSummary } from "@alook/shared"
+
+function machine(over: Partial<CommunityMachineSummary>): CommunityMachineSummary {
+ return {
+ id: "m1",
+ hostname: "host",
+ displayName: "",
+ platform: "darwin",
+ arch: "arm64",
+ osRelease: "",
+ daemonVersion: "0",
+ lastSeenAt: null,
+ status: "online",
+ availableRuntimes: [],
+ createdAt: "",
+ updatedAt: "",
+ ...over,
+ }
+}
+
+describe("firstOnlineMachineId", () => {
+ it("returns the first online machine id, skipping a leading offline one", () => {
+ const machines = [
+ machine({ id: "off", status: "offline" }),
+ machine({ id: "on", status: "online" }),
+ ]
+ expect(firstOnlineMachineId(machines)).toBe("on")
+ })
+
+ it("returns '' when no machine is online", () => {
+ expect(firstOnlineMachineId([machine({ id: "a", status: "offline" })])).toBe("")
+ })
+
+ it("returns '' for an empty list", () => {
+ expect(firstOnlineMachineId([])).toBe("")
+ })
+})
+
+describe("normalizeRuntimes", () => {
+ it("returns [] when availableRuntimes is missing", () => {
+ expect(normalizeRuntimes(undefined)).toEqual([])
+ // legacy summary missing the field entirely
+ const legacy = { ...machine({}) } as CommunityMachineSummary
+ delete (legacy as { availableRuntimes?: unknown }).availableRuntimes
+ expect(normalizeRuntimes(legacy)).toEqual([])
+ })
+
+ it("normalizes bare-string legacy entries to healthy", () => {
+ const m = machine({
+ availableRuntimes: ["claude"] as unknown as CommunityMachineSummary["availableRuntimes"],
+ })
+ expect(normalizeRuntimes(m)).toEqual([{ id: "claude", unhealthy: false }])
+ })
+
+ it("marks status:'unhealthy' entries unhealthy and sorts healthy-first", () => {
+ const m = machine({
+ availableRuntimes: [
+ { id: "sick", status: "unhealthy" },
+ { id: "ok", status: "healthy" },
+ ] as unknown as CommunityMachineSummary["availableRuntimes"],
+ })
+ expect(normalizeRuntimes(m)).toEqual([
+ { id: "ok", unhealthy: false },
+ { id: "sick", unhealthy: true },
+ ])
+ })
+})
+
+describe("firstHealthyRuntimeId", () => {
+ it("returns the first healthy runtime id, skipping unhealthy ones", () => {
+ expect(
+ firstHealthyRuntimeId([
+ { id: "ok", unhealthy: false },
+ { id: "sick", unhealthy: true },
+ ]),
+ ).toBe("ok")
+ })
+
+ it("returns '' when every runtime is unhealthy", () => {
+ expect(firstHealthyRuntimeId([{ id: "sick", unhealthy: true }])).toBe("")
+ })
+
+ it("returns '' for an empty list", () => {
+ expect(firstHealthyRuntimeId([])).toBe("")
+ })
+})
+
+// --- Component auto-select tests --------------------------------------------
+//
+// The Sheet is a base-ui Dialog that portals into `document`, unavailable
+// under this repo's `environment: "node"` vitest config — so mock the sheet
+// shell and heavy children to render passthrough, and mock the data/mutation
+// hooks. What we assert is the *initial `checked` state* of the machine and
+// runtime radios, which is all this change touches.
+
+const useMachinesMock = vi.fn()
+
+vi.mock("@/hooks/community/use-machines", () => ({
+ useMachines: () => useMachinesMock(),
+}))
+
+vi.mock("@/hooks/community/use-bots", () => ({
+ useCreateBot: () => ({ mutateAsync: vi.fn(), isPending: false }),
+ useUploadBotAvatar: () => ({ mutateAsync: vi.fn() }),
+}))
+
+vi.mock("@/components/ui/sheet", () => {
+ const pass = (name: string) =>
+ function Passthrough({ children }: { children?: React.ReactNode }) {
+ return React.createElement("div", { "data-mock": name }, children)
+ }
+ return {
+ Sheet: pass("sheet"),
+ SheetBody: pass("body"),
+ SheetContent: pass("content"),
+ SheetFooter: pass("footer"),
+ SheetHeader: pass("header"),
+ SheetTitle: pass("title"),
+ }
+})
+
+vi.mock("./bot-form-fields", () => ({
+ BotFormFields: () => React.createElement("div", { "data-mock": "form-fields" }),
+}))
+
+vi.mock("@/components/provider-logo", () => ({
+ ProviderLogo: () => React.createElement("span", { "data-mock": "provider-logo" }),
+}))
+
+import { CreateBotSheet } from "./create-bot-sheet"
+
+type Radio = { name: string; value: string; checked: boolean }
+
+function radios(renderer: TestRenderer.ReactTestRenderer, name: string): Radio[] {
+ return renderer.root
+ .findAll((n) => n.type === "input" && n.props.name === name)
+ .map((n) => ({ name: n.props.name, value: n.props.value, checked: !!n.props.checked }))
+}
+
+function checkedValue(renderer: TestRenderer.ReactTestRenderer, name: string): string | null {
+ return radios(renderer, name).find((r) => r.checked)?.value ?? null
+}
+
+function render(): TestRenderer.ReactTestRenderer {
+ let renderer!: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(CreateBotSheet, { open: true, onOpenChange: vi.fn() }),
+ )
+ })
+ return renderer
+}
+
+describe("CreateBotSheet — auto-select defaults", () => {
+ beforeEach(() => {
+ useMachinesMock.mockReset()
+ })
+
+ it("pre-checks the machine and runtime with one online machine + one healthy runtime", () => {
+ useMachinesMock.mockReturnValue({
+ machines: [
+ machine({
+ id: "mac",
+ status: "online",
+ availableRuntimes: [
+ { id: "claude", status: "healthy" },
+ ] as unknown as CommunityMachineSummary["availableRuntimes"],
+ }),
+ ],
+ })
+ const renderer = render()
+ expect(checkedValue(renderer, "bot-machine")).toBe("mac")
+ expect(checkedValue(renderer, "bot-runtime")).toBe("claude")
+ })
+
+ it("resolves the [] → populated async race by auto-selecting once data arrives", () => {
+ // First render: machines empty (query still loading).
+ useMachinesMock.mockReturnValue({ machines: [] })
+ const renderer = render()
+ expect(checkedValue(renderer, "bot-machine")).toBe(null)
+
+ // Data arrives a tick later — re-render the SAME instance.
+ useMachinesMock.mockReturnValue({
+ machines: [
+ machine({
+ id: "mac",
+ status: "online",
+ availableRuntimes: [
+ { id: "claude", status: "healthy" },
+ ] as unknown as CommunityMachineSummary["availableRuntimes"],
+ }),
+ ],
+ })
+ act(() => {
+ renderer.update(
+ React.createElement(CreateBotSheet, { open: true, onOpenChange: vi.fn() }),
+ )
+ })
+ expect(checkedValue(renderer, "bot-machine")).toBe("mac")
+ expect(checkedValue(renderer, "bot-runtime")).toBe("claude")
+ })
+
+ it("skips a leading offline machine and picks the first online one", () => {
+ useMachinesMock.mockReturnValue({
+ machines: [
+ machine({ id: "off", status: "offline" }),
+ machine({
+ id: "on",
+ status: "online",
+ availableRuntimes: [
+ { id: "claude", status: "healthy" },
+ ] as unknown as CommunityMachineSummary["availableRuntimes"],
+ }),
+ ],
+ })
+ const renderer = render()
+ expect(checkedValue(renderer, "bot-machine")).toBe("on")
+ })
+
+ it("selects nothing when no machine is online", () => {
+ useMachinesMock.mockReturnValue({
+ machines: [machine({ id: "off", status: "offline" })],
+ })
+ const renderer = render()
+ expect(checkedValue(renderer, "bot-machine")).toBe(null)
+ // Runtime section is hidden entirely when no machine is selected.
+ expect(radios(renderer, "bot-runtime")).toHaveLength(0)
+ })
+
+ it("pre-selects the machine but not the runtime when the only runtime is unhealthy", () => {
+ useMachinesMock.mockReturnValue({
+ machines: [
+ machine({
+ id: "mac",
+ status: "online",
+ availableRuntimes: [
+ { id: "sick", status: "unhealthy" },
+ ] as unknown as CommunityMachineSummary["availableRuntimes"],
+ }),
+ ],
+ })
+ const renderer = render()
+ expect(checkedValue(renderer, "bot-machine")).toBe("mac")
+ expect(checkedValue(renderer, "bot-runtime")).toBe(null)
+ })
+
+ it("re-defaults the runtime when the user switches to another machine", () => {
+ useMachinesMock.mockReturnValue({
+ machines: [
+ machine({
+ id: "mac",
+ status: "online",
+ availableRuntimes: [
+ { id: "claude", status: "healthy" },
+ ] as unknown as CommunityMachineSummary["availableRuntimes"],
+ }),
+ machine({
+ id: "server",
+ status: "online",
+ availableRuntimes: [
+ { id: "codex", status: "healthy" },
+ ] as unknown as CommunityMachineSummary["availableRuntimes"],
+ }),
+ ],
+ })
+ const renderer = render()
+ expect(checkedValue(renderer, "bot-machine")).toBe("mac")
+ expect(checkedValue(renderer, "bot-runtime")).toBe("claude")
+
+ // Click the second machine's radio.
+ const serverRadio = renderer.root.findAll(
+ (n) => n.type === "input" && n.props.name === "bot-machine" && n.props.value === "server",
+ )[0]
+ act(() => {
+ serverRadio.props.onChange()
+ })
+ expect(checkedValue(renderer, "bot-machine")).toBe("server")
+ expect(checkedValue(renderer, "bot-runtime")).toBe("codex")
+ })
+
+ it("does not overwrite a chosen machine when a presence refetch changes the array", () => {
+ useMachinesMock.mockReturnValue({
+ machines: [
+ machine({
+ id: "mac",
+ status: "online",
+ availableRuntimes: [
+ { id: "claude", status: "healthy" },
+ ] as unknown as CommunityMachineSummary["availableRuntimes"],
+ }),
+ machine({
+ id: "server",
+ status: "online",
+ availableRuntimes: [
+ { id: "codex", status: "healthy" },
+ ] as unknown as CommunityMachineSummary["availableRuntimes"],
+ }),
+ ],
+ })
+ const renderer = render()
+
+ // User picks the second machine explicitly.
+ const serverRadio = renderer.root.findAll(
+ (n) => n.type === "input" && n.props.name === "bot-machine" && n.props.value === "server",
+ )[0]
+ act(() => {
+ serverRadio.props.onChange()
+ })
+ expect(checkedValue(renderer, "bot-machine")).toBe("server")
+
+ // A presence tick delivers a NEW array identity (same data).
+ useMachinesMock.mockReturnValue({
+ machines: [
+ machine({
+ id: "mac",
+ status: "online",
+ availableRuntimes: [
+ { id: "claude", status: "healthy" },
+ ] as unknown as CommunityMachineSummary["availableRuntimes"],
+ }),
+ machine({
+ id: "server",
+ status: "online",
+ availableRuntimes: [
+ { id: "codex", status: "healthy" },
+ ] as unknown as CommunityMachineSummary["availableRuntimes"],
+ }),
+ ],
+ })
+ act(() => {
+ renderer.update(
+ React.createElement(CreateBotSheet, { open: true, onOpenChange: vi.fn() }),
+ )
+ })
+ // Choice stands.
+ expect(checkedValue(renderer, "bot-machine")).toBe("server")
+ expect(checkedValue(renderer, "bot-runtime")).toBe("codex")
+ })
+})
diff --git a/src/web/src/components/community/bots/create-bot-sheet.tsx b/src/web/src/components/community/bots/create-bot-sheet.tsx
index 680abfd3a..84ece7b18 100644
--- a/src/web/src/components/community/bots/create-bot-sheet.tsx
+++ b/src/web/src/components/community/bots/create-bot-sheet.tsx
@@ -3,7 +3,7 @@
import { useEffect, useMemo, useRef, useState } from "react"
import { toast } from "sonner"
import { toastApiError } from "@/lib/api/client"
-import { isPresenceOnline } from "@alook/shared"
+import { isPresenceOnline, type CommunityMachineSummary } from "@alook/shared"
import { machineName } from "@/lib/community/machine-name"
import {
Sheet,
@@ -36,6 +36,38 @@ function randomBotName(): string {
return uniqueNamesGenerator({ dictionaries: [names], length: 1, style: "capital" })
}
+type NormalizedRuntime = { id: string; unhealthy: boolean }
+
+/**
+ * Normalize a machine's runtimes into `{ id, unhealthy }`, healthy-first.
+ *
+ * A legacy CommunityMachineSummary cached client-side may still be missing
+ * availableRuntimes, or a runtime entry may still be a bare string
+ * (pre-health-status shape). Normalize both instead of hiding unhealthy
+ * runtimes outright, so the radio card can show *why* an option is disabled.
+ * Available runtimes sort first — the ones you can actually pick should never
+ * be buried below ones you can't.
+ */
+export function normalizeRuntimes(machine: CommunityMachineSummary | undefined): NormalizedRuntime[] {
+ const rt = machine?.availableRuntimes ?? []
+ const normalized = rt.map((r) =>
+ typeof r === "string"
+ ? { id: r, unhealthy: false }
+ : { id: (r as { id: string }).id, unhealthy: (r as { status?: string }).status === "unhealthy" },
+ )
+ return normalized.sort((a, b) => Number(a.unhealthy) - Number(b.unhealthy))
+}
+
+/** First healthy (selectable) runtime id, or "" if none. */
+export function firstHealthyRuntimeId(options: NormalizedRuntime[]): string {
+ return options.find((o) => !o.unhealthy)?.id ?? ""
+}
+
+/** First online (selectable) machine id, or "" if none. */
+export function firstOnlineMachineId(machines: CommunityMachineSummary[]): string {
+ return machines.find((m) => isPresenceOnline(m.status))?.id ?? ""
+}
+
export function CreateBotSheet({
open,
onOpenChange,
@@ -57,22 +89,7 @@ export function CreateBotSheet({
})
const selectedMachine = machines.find((m) => m.id === machineId)
- const runtimeOptions = useMemo(() => {
- // Nullish guard — a legacy CommunityMachineSummary cached client-side may
- // still be missing availableRuntimes, or a runtime entry may still be a
- // bare string (pre-health-status shape). Normalize both into
- // `{ id, unhealthy }` instead of hiding unhealthy runtimes outright, so
- // the radio card can show *why* an option is disabled.
- const rt = selectedMachine?.availableRuntimes ?? []
- const normalized = rt.map((r) =>
- typeof r === "string"
- ? { id: r, unhealthy: false }
- : { id: (r as { id: string }).id, unhealthy: (r as { status?: string }).status === "unhealthy" },
- )
- // Available runtimes sort first — the ones you can actually pick should
- // never be buried below ones you can't.
- return normalized.sort((a, b) => Number(a.unhealthy) - Number(b.unhealthy))
- }, [selectedMachine])
+ const runtimeOptions = useMemo(() => normalizeRuntimes(selectedMachine), [selectedMachine])
// Randomize name + avatar on client mount (not during SSR — Math.random would
// hydration-mismatch). Fires once per sheet open.
@@ -92,6 +109,23 @@ export function CreateBotSheet({
setFieldErrors({})
}, [open])
+ // Auto-select sensible defaults once machine data arrives. useMachines()
+ // loads async, so `machines` is often [] on the open transition and
+ // populates a tick later — this reacts to that. Each write is guarded on the
+ // target being "" so a presence refetch never overwrites a made choice.
+ useEffect(() => {
+ if (!open) return
+ if (machineId === "") {
+ const next = firstOnlineMachineId(machines)
+ if (next) setMachineId(next)
+ return
+ }
+ if (runtime === "") {
+ const next = firstHealthyRuntimeId(runtimeOptions)
+ if (next) setRuntime(next)
+ }
+ }, [open, machines, runtimeOptions, machineId, runtime])
+
function shuffleName() {
setName(randomBotName())
setFieldErrors((prev) => ({ ...prev, name: undefined }))
@@ -106,7 +140,8 @@ export function CreateBotSheet({
function selectMachine(id: string) {
setMachineId(id)
- setRuntime("")
+ const nextMachine = machines.find((m) => m.id === id)
+ setRuntime(firstHealthyRuntimeId(normalizeRuntimes(nextMachine)))
setFieldErrors((prev) => ({ ...prev, machineId: undefined }))
}