Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(agents): agent looks are pets only (#1109)

Ruben Lütkeb1210778cc61
diff --git a/dodaios/society/companion.py b/dodaios/society/companion.py
index 87c3ec5f05..a2ece9b04e 100644
--- a/dodaios/society/companion.py
+++ b/dodaios/society/companion.py
@@ -97,22 +97,26 @@ class CompanionAppearance(BaseModel):
followDistanceM: float = Field(default=1.0, ge=0.5, le=2.0)
+#: The built-in pets an agent can wear by default (``dodaios/ui/pets/builtin``).
+#: Gigi is left out: it is the lead's own face. Mirrors ``DEFAULT_PETS`` in
+#: ``frontend/src/components/society/companion/appearance.ts``.
+DEFAULT_PETS: tuple[str, ...] = (
+ "ember", "miso", "bolt", "brew", "mochi", "shelly", "cocoa", "dodaios",
+)
+
+
def random_companion() -> dict[str, Any]:
"""A random, valid companion look for a newly created agent.
- A new agent starts as a pixel creature; the shape underneath is what it
- shows once its creature is taken off.
+ A new agent wears a random built-in pet; the shape underneath is only
+ the fallback for a machine that lacks that pet.
"""
rng = secrets.SystemRandom()
look = CompanionAppearance(
shape=rng.choice(COMPANION_SHAPES), # type: ignore[arg-type]
color=rng.choice(COMPANION_COLORS),
eyes=rng.choice(("dots", "lines")), # type: ignore[arg-type]
- creature=CompanionCreature(
- seed=rng.randrange(100_000),
- palette=rng.choice(CREATURE_PALETTES),
- eyes=rng.choice(CREATURE_EYES),
- ),
+ pet=rng.choice(DEFAULT_PETS),
).model_dump()
return _bare(look)
diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentProfileDialog.test.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentProfileDialog.test.tsx
index 80ac46bef7..5ebd5e5a20 100644
--- a/dodaios/ui/web/frontend/src/components/society/card/AgentProfileDialog.test.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentProfileDialog.test.tsx
@@ -16,9 +16,14 @@ const knowledge = { files: [
{ path: "skills/check/SKILL.md", name: "check/SKILL.md", kind: "skills", updated_ms: 3, size: 50 },
], learned_instructions: ["Check source dates."], reviews: { pending: 0, done: 1 }, last_review: { state: "done", updated_ms: 1000 } };
+const PETS = { active: "gigi", scale: 1, bubble: true, strip_always: false, visible: true, pets: ["gigi", "cocoa"].map(id => ({
+ id, name: id, description: "", builtin: true, frame_size: 48, animations: { idle: { row: 0, frames: 1, fps: 1, loop: true } }, sheet_url: `/api/pets/${id}/sheet.png`,
+})) };
+
function setup(options: { lead?: boolean; sample?: boolean; fetcher?: typeof fetch; knowledgeFailure?: boolean } = {}) {
const fetcher = vi.fn(async (url: RequestInfo | URL, init?: RequestInit) => {
if (String(url).endsWith("/knowledge")) return json(knowledge, options.knowledgeFailure ? 500 : 200);
+ if (String(url).startsWith("/api/pets")) return json(PETS);
return options.fetcher ? options.fetcher(url, init) : json({});
});
vi.stubGlobal("fetch", fetcher);
@@ -115,14 +120,13 @@ it("opens the avatar profile without selecting the chat and leaves name-click na
it("customizes the agent's look and saves it with the character recipe kept", async () => {
const { fetcher } = setup();
fireEvent.click(screen.getAllByRole("button", { name: "society.profile_card.look" })[0]);
- // Accessories belong to the shape; an agent that never picked a look opens on its pixel creature.
- fireEvent.click(await screen.findByRole("button", { name: "society.companion.look_shape" }));
- fireEvent.click(await screen.findByRole("button", { name: "society.companion.items.suit" }));
+ // The look is a pet, picked from My Pets.
+ fireEvent.click(await screen.findByRole("button", { name: "cocoa" }));
fireEvent.click(screen.getByRole("button", { name: "society.card.save" }));
await screen.findByText("society.profile_card.saved");
const call = fetcher.mock.calls.find(([url, init]) => String(url) === "/api/society/agents/research" && init?.method === "PATCH");
const body = JSON.parse(String(call?.[1]?.body));
- expect(body.avatar.companion.accessories).toEqual({ outfit: "suit" });
+ expect(body.avatar.companion.pet).toBe("cocoa");
const { companion: _old, ...recipe } = agent.figure ?? {};
expect(body.avatar).toMatchObject(recipe);
expect(body.title).toBe("Researcher");
diff --git a/dodaios/ui/web/frontend/src/components/society/chat/MeetingChat.test.tsx b/dodaios/ui/web/frontend/src/components/society/chat/MeetingChat.test.tsx
index 1de76d9406..e43da8f5e1 100644
--- a/dodaios/ui/web/frontend/src/components/society/chat/MeetingChat.test.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/chat/MeetingChat.test.tsx
@@ -4,6 +4,8 @@ import { afterEach, expect, it, vi } from "vitest";
import { MeetingChat } from "./MeetingChat";
import type { SocietyAgent } from "../data";
+// Every agent wears a pet; these tests count their own requests, so the pets answer stays out of fetch.
+vi.mock("@/hooks/usePets", async (original) => ({ ...(await original<typeof import("@/hooks/usePets")>()), usePetById: () => null }));
vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));
afterEach(() => { cleanup(); vi.unstubAllGlobals(); });
diff --git a/dodaios/ui/web/frontend/src/components/society/companion/AccessoryPicker.tsx b/dodaios/ui/web/frontend/src/components/society/companion/AccessoryPicker.tsx
deleted file mode 100644
index a7449f8d0b..0000000000
--- a/dodaios/ui/web/frontend/src/components/society/companion/AccessoryPicker.tsx
+++ /dev/null
@@ -1,84 +0,0 @@
-import { useState } from "react";
-import { Lock } from "lucide-react";
-import "../calmSheet.css";
-import { useT } from "@/i18n";
-import { AgentSymbol } from "../AgentSymbol";
-import { ACCESSORY_IDS_BY_SLOT, OFFERED_SLOTS, randomAccessories, type AccessoryChoice, type AccessorySlot } from "./accessories";
-import { lookOpen, nextLook, useAgentLooks } from "./agentLooks";
-import type { CompanionAppearance } from "./appearance";
-import { SegmentedChoice } from "./SegmentedChoice";
-
-/** Picker order: what people change most comes first; empty slots stay hidden. */
-const PICKER_SLOTS = (["outfit", "head", "face", "mouth", "neck", "back", "held"] as AccessorySlot[])
- .filter(slot => OFFERED_SLOTS.includes(slot));
-
-/**
- * One tile per item, each showing this agent already wearing it. Looks open
- * with the agent's level; a locked tile says when it opens, and a look the
- * agent already wears stays selectable whatever its level.
- */
-export function AccessoryPicker({ value, onChange, agentId }: { value: CompanionAppearance; onChange: (next: AccessoryChoice) => void; agentId?: string }) {
- const t = useT();
- const [slot, setSlot] = useState<AccessorySlot>(PICKER_SLOTS[0] ?? "head");
- const looks = useAgentLooks(agentId);
- const worn = value.accessories;
- const wearable = (id: string) => lookOpen(looks, id) || Object.values(worn).includes(id);
- const upcoming = nextLook(looks);
- const choose = (id: string | undefined) => {
- const next = { ...worn };
- if (id) next[slot] = id; else delete next[slot];
- onChange(next);
- };
- const surprise = () => {
- const rolled = randomAccessories();
- onChange(Object.fromEntries(Object.entries(rolled).filter(([, id]) => id && wearable(id))) as AccessoryChoice);
- };
- const tile = "calm-tile relative h-[84px] w-[84px]";
- return <div data-testid="accessory-picker">
- <div className="mb-2 flex items-center justify-between gap-2">
- <span className="text-[14px] font-medium">{t("society.companion.accessories")}</span>
- <div className="flex gap-1">
- <button type="button" onClick={surprise} className="cs-chip">
- {t("society.companion.randomize")}
- </button>
- <button type="button" disabled={!Object.keys(worn).length} onClick={() => onChange({})} className="cs-chip disabled:opacity-40">
- {t("society.companion.remove_all")}
- </button>
- </div>
- </div>
- {looks.unlocks && (
- <p className="mb-3 rounded-2xl bg-secondary/50 px-4 py-2.5 text-[13px] text-muted-foreground" data-testid="look-progress">
- {upcoming
- ? t("society.companion.next_look").replace("{0}", String(looks.level)).replace("{1}", t(`society.companion.items.${upcoming.id}`)).replace("{2}", String(upcoming.level))
- : t("society.companion.all_looks_open")}
- </p>
- )}
- <div className="mb-3"><SegmentedChoice role="tablist" label={t("society.companion.accessories")} value={slot} onChange={setSlot}
- options={PICKER_SLOTS.map(id => ({ id, label: t(`society.companion.slots.${id}`) }))}
- marked={new Set(PICKER_SLOTS.filter(s => worn[s]))} /></div>
- <div className="flex flex-wrap gap-2" role="group" aria-label={t(`society.companion.slots.${slot}`)}>
- <button type="button" aria-pressed={!worn[slot]} aria-label={t("society.companion.none")} title={t("society.companion.none")} onClick={() => choose(undefined)}
- className={`${tile} text-[13px] text-muted-foreground`} data-on={!worn[slot]}>
- {t("society.companion.none")}
- </button>
- {/* Open looks first, then the rest in the order the agent will earn them. */}
- {[...ACCESSORY_IDS_BY_SLOT[slot]].sort((a, b) => (looks.unlocks?.[a] ?? 0) - (looks.unlocks?.[b] ?? 0)).map(id => {
- const name = t(`society.companion.items.${id}`);
- const active = worn[slot] === id;
- const open = wearable(id);
- const at = looks.unlocks?.[id];
- const label = open ? name : `${name} · ${t("society.companion.unlocks_at").replace("{0}", String(at))}`;
- return <button key={id} type="button" aria-pressed={active} aria-label={label} title={label} disabled={!open} onClick={() => choose(id)}
- data-locked={open ? undefined : "true"}
- className={`${tile} ${open ? "" : "cursor-not-allowed"}`} data-on={active}>
- <span className={open ? undefined : "opacity-35 grayscale"}>
- <AgentSymbol shape={value.shape} color={value.color} eyes={value.eyes} skin={value.skin} accessories={{ ...worn, [slot]: id }} size={68} />
- </span>
- {!open && <span className="absolute bottom-1 left-1/2 inline-flex -translate-x-1/2 items-center gap-0.5 rounded-full bg-background/90 px-1.5 py-0.5 text-xs font-semibold text-foreground shadow-sm">
- <Lock size={9} aria-hidden />{t("society.level.lv").replace("{0}", String(at))}
- </span>}
- </button>;
- })}
- </div>
- </div>;
-}
diff --git a/dodaios/ui/web/frontend/src/components/society/companion/AgentAppearanceDialog.test.tsx b/dodaios/ui/web/frontend/src/components/society/companion/AgentAppearanceDialog.test.tsx
index 24782ec3b1..b77834db4f 100644
--- a/dodaios/ui/web/frontend/src/components/society/companion/AgentAppearanceDialog.test.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/companion/AgentAppearanceDialog.test.tsx
@@ -10,14 +10,14 @@ vi.mock("./CompanionPreview", () => ({ CompanionPreview: () => <div data-testid=
vi.mock("../figures/AgentFigureViewer", () => ({ AgentFigureViewer: () => <div data-testid="character-preview" /> }));
afterEach(() => { cleanup(); vi.unstubAllGlobals(); });
-const PETS = { active: "gigi", scale: 1, bubble: true, strip_always: false, visible: true, pets: ["gigi", "cocoa"].map(id => ({
+const PETS = { active: "gigi", scale: 1, bubble: true, strip_always: false, visible: true, pets: ["gigi", "ember", "miso", "bolt", "brew", "mochi", "shelly", "cocoa", "dodaios"].map(id => ({
id, name: id, description: "", builtin: true, frame_size: 48, animations: { idle: { row: 0, frames: 1, fps: 1, loop: true } }, sheet_url: `/api/pets/${id}/sheet.png`,
})) };
-function setup(fail = false, legacy = false, unpicked = false) {
+function setup(fail = false, legacy = false, companion: Record<string, unknown> = { pet: "ember" }) {
const original = SAMPLE_ROSTER.find(a => a.tier !== "lead")!;
const figure = legacy ? { contract: 1 as const, archetype: "biped" as const, base: "rogue", parts: {} } : original.figure!;
- const agent = { ...original, agentId: "appearance-test", figure: { ...figure, companion: { ...defaultCompanion("test"), shape: "circle" as const, ...(unpicked ? {} : { look: "shape" as const }) } } };
+ const agent = { ...original, agentId: "appearance-test", figure: { ...figure, companion: { ...defaultCompanion("test"), shape: "circle" as const, pet: undefined, ...companion } } };
const close = vi.fn();
// The look picker reads agent levels; an unreachable level system leaves every look open.
const fetcher = vi.fn(async (url: RequestInfo | URL) => String(url).startsWith("/api/progression")
@@ -30,45 +30,62 @@ function setup(fail = false, legacy = false, unpicked = false) {
return { agent, fetcher, close, saves };
}
-it("saves companion edits without overwriting character parts or other agent fields", async () => {
+it("saves a picked pet without overwriting character parts or other agent fields", async () => {
const { agent, saves } = setup();
- fireEvent.click(screen.getByRole("button", { name: "society.companion.shapes.cloud" }));
+ fireEvent.click(await screen.findByRole("button", { name: "cocoa" }));
fireEvent.click(screen.getByRole("button", { name: "society.card.save" }));
await waitFor(() => expect(saves()).toHaveLength(1));
const [, init] = saves()[0] as unknown as [string, RequestInit];
const body = JSON.parse(init.body as string);
expect(Object.keys(body)).toEqual(["avatar"]);
- expect(body.avatar.companion.shape).toBe("cloud");
+ expect(body.avatar.companion.pet).toBe("cocoa");
expect(body.avatar.parts).toEqual(agent.figure?.parts);
expect(body.avatar.base).toBe(agent.figure?.base);
});
-it("protects an unsaved companion after a rejected save", async () => {
+it("protects an unsaved pet choice after a rejected save", async () => {
const { close } = setup(true);
- fireEvent.click(screen.getByRole("button", { name: "society.companion.shapes.cloud" }));
+ fireEvent.click(await screen.findByRole("button", { name: "cocoa" }));
fireEvent.click(screen.getByRole("button", { name: "society.card.save" }));
await screen.findByRole("alert");
- expect(screen.getByRole("button", { name: "society.companion.shapes.cloud" }).getAttribute("aria-pressed")).toBe("true");
+ expect(screen.getByRole("button", { name: "cocoa" }).getAttribute("aria-pressed")).toBe("true");
fireEvent.click(screen.getAllByRole("button", { name: "society.card.close" })[0]);
expect(close).not.toHaveBeenCalled();
expect(screen.getByText("society.profile_card.unsaved")).toBeTruthy();
});
-it("keeps the companion choice while editing the character", async () => {
+it("keeps the pet choice while editing the character", async () => {
setup();
- fireEvent.click(screen.getByRole("button", { name: "society.companion.shapes.cloud" }));
+ fireEvent.click(await screen.findByRole("button", { name: "cocoa" }));
fireEvent.click(screen.getByRole("tab", { name: "society.companion.character" }));
await screen.findByTestId("character-preview");
fireEvent.click(screen.getByRole("tab", { name: "society.companion.companion" }));
- expect(screen.getByRole("button", { name: "society.companion.shapes.cloud" }).getAttribute("aria-pressed")).toBe("true");
+ expect(screen.getByRole("button", { name: "cocoa" }).getAttribute("aria-pressed")).toBe("true");
});
-it("keeps shape customization without size or following-distance sliders", () => {
+it("offers only pets: no shapes, no pixel creatures, no colours and no sliders", async () => {
setup();
+ expect(await screen.findByRole("button", { name: "ember" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "ember" }).getAttribute("aria-pressed")).toBe("true");
+ for (const gone of ["society.companion.look_creature", "society.companion.look_shape", "society.companion.look_pet", "society.companion.shapes.cloud"]) {
+ expect(screen.queryByRole("button", { name: gone })).toBeNull();
+ }
+ expect(screen.queryByTestId("creature-picker")).toBeNull();
+ expect(screen.queryByLabelText("society.companion.custom_color")).toBeNull();
expect(screen.queryByRole("slider")).toBeNull();
- expect(screen.queryByText("society.companion.size")).toBeNull();
- expect(screen.queryByText("society.companion.distance")).toBeNull();
- expect(screen.getByRole("button", { name: "society.companion.shapes.cloud" })).toBeTruthy();
+});
+
+it("opens an agent that still wears a pixel creature on a pet, and saves no creature", async () => {
+ const { saves } = setup(false, false, { creature: { seed: 24, palette: "neon", eyes: "dot" }, look: "shape" });
+ const picker = await screen.findByTestId("companion-pet-picker");
+ await waitFor(() => expect(within(picker).getAllByRole("button", { pressed: true })).toHaveLength(1));
+ fireEvent.click(screen.getByRole("button", { name: "cocoa" }));
+ fireEvent.click(screen.getByRole("button", { name: "society.card.save" }));
+ await waitFor(() => expect(saves()).toHaveLength(1));
+ const companion = JSON.parse((saves()[0] as unknown as [string, RequestInit])[1].body as string).avatar.companion;
+ expect(companion.pet).toBe("cocoa");
+ expect(companion.creature).toBeUndefined();
+ expect(companion.look).toBeUndefined();
});
it("saves a chosen hairstyle on the recipe without dropping its colours", async () => {
@@ -84,92 +101,3 @@ it("saves a chosen hairstyle on the recipe without dropping its colours", async
expect(body.avatar.hairStyle).toBe("beanie");
expect(body.avatar.palette).toEqual(agent.figure?.palette);
});
-
-it("lets an agent wear a pet instead of its shape, and take the shape back", async () => {
- const { saves } = setup();
- fireEvent.click(screen.getByRole("button", { name: "society.companion.look_pet" }));
- fireEvent.click(await screen.findByRole("button", { name: "cocoa" }));
- expect(screen.queryByRole("button", { name: "society.companion.shapes.cloud" })).toBeNull();
- // A pet brings its own colours: no colour picker beside it.
- expect(screen.queryByLabelText("society.companion.custom_color")).toBeNull();
- fireEvent.click(screen.getByRole("button", { name: "society.card.save" }));
- await waitFor(() => expect(saves()).toHaveLength(1));
- const worn = JSON.parse((saves()[0] as unknown as [string, RequestInit])[1].body as string);
- expect(worn.avatar.companion).toMatchObject({ pet: "cocoa", shape: "circle" });
- fireEvent.click(screen.getByRole("button", { name: "society.companion.look_shape" }));
- fireEvent.click(screen.getByRole("button", { name: "society.card.save" }));
- await waitFor(() => expect(saves()).toHaveLength(2));
- const bare = JSON.parse((saves()[1] as unknown as [string, RequestInit])[1].body as string);
- expect("pet" in bare.avatar.companion).toBe(false);
-});
-
-it("saves a pixel creature with the look and brings the chosen one back after a detour over the shape", async () => {
- const { saves } = setup();
- fireEvent.click(screen.getByRole("button", { name: "society.companion.look_creature" }));
- fireEvent.click(screen.getByRole("button", { name: "society.companion.creature.palettes.neon" }));
- fireEvent.click(screen.getByRole("button", { name: "society.companion.creature.eye_kinds.visor" }));
- // Back to the shape and to the creature again: the picked one returns, the shape was never lost.
- fireEvent.click(screen.getByRole("button", { name: "society.companion.look_shape" }));
- expect(screen.queryByTestId("creature-picker")).toBeNull();
- fireEvent.click(screen.getByRole("button", { name: "society.companion.look_creature" }));
- expect(screen.getByRole("button", { name: "society.companion.creature.palettes.neon" }).getAttribute("aria-pressed")).toBe("true");
- fireEvent.click(screen.getByRole("button", { name: "society.card.save" }));
- await waitFor(() => expect(saves()).toHaveLength(1));
- const [, init] = saves()[0] as unknown as [string, RequestInit];
- const companion = JSON.parse(init.body as string).avatar.companion;
- expect(companion.creature).toMatchObject({ palette: "neon", eyes: "visor" });
- expect(Number.isInteger(companion.creature.seed)).toBe(true);
- expect(companion.shape).toBe("circle");
- expect(companion.pet).toBeUndefined();
- expect(companion.look).toBeUndefined();
-});
-
-it("stores no creature when the look goes back to the shape", async () => {
- const { saves } = setup();
- fireEvent.click(screen.getByRole("button", { name: "society.companion.look_creature" }));
- fireEvent.click(screen.getByRole("button", { name: "society.companion.look_shape" }));
- fireEvent.click(screen.getByRole("button", { name: "society.companion.shapes.cloud" }));
- fireEvent.click(screen.getByRole("button", { name: "society.card.save" }));
- await waitFor(() => expect(saves()).toHaveLength(1));
- const [, init] = saves()[0] as unknown as [string, RequestInit];
- const companion = JSON.parse(init.body as string).avatar.companion;
- expect(companion.creature).toBeUndefined();
- expect(companion.look).toBe("shape");
-});
-
-it("opens an agent that never picked a look on its pixel creature, and stores the shape once it is chosen", async () => {
- const { saves } = setup(false, false, true);
- expect(screen.getByRole("button", { name: "society.companion.look_creature" }).getAttribute("aria-pressed")).toBe("true");
- expect(screen.getByTestId("creature-picker")).toBeTruthy();
- // The creature previews on its own canvas stage; the 3D studio is for shapes and pets.
- expect(screen.getByTestId("creature-stage")).toBeTruthy();
- expect(screen.queryByTestId("preview")).toBeNull();
- fireEvent.click(screen.getByRole("button", { name: "society.companion.creature.state_names.asking" }));
- expect(screen.getByTestId("creature-stage").dataset.creatureState).toBe("asking");
- fireEvent.click(screen.getByRole("button", { name: "society.companion.look_shape" }));
- expect(screen.queryByTestId("creature-stage")).toBeNull();
- expect(await screen.findByTestId("preview")).toBeTruthy();
- fireEvent.click(screen.getByRole("button", { name: "society.card.save" }));
- await waitFor(() => expect(saves()).toHaveLength(1));
- const [, init] = saves()[0] as unknown as [string, RequestInit];
- expect(JSON.parse(init.body as string).avatar.companion.look).toBe("shape");
-});
-
-it("rolls a whole new creature at once: figure, colour world and eyes, and wears it", async () => {
- const { saves } = setup();
- fireEvent.click(screen.getByRole("button", { name: "society.companion.look_creature" }));
- const pressedWorld = () => screen.getAllByRole("button", { pressed: true }).map(button => button.getAttribute("aria-label") ?? "").find(label => label.startsWith("society.companion.creature.palettes."));
- const before = pressedWorld();
- fireEvent.click(screen.getByRole("button", { name: "society.companion.creature.roll" }));
- const rolled = pressedWorld();
- expect(rolled).toBeTruthy();
- expect(rolled).not.toBe(before);
- // The rolled figure is worn and leads the row of choices.
- const figures = within(screen.getByTestId("creature-picker")).getAllByRole("button").filter(button => (button.getAttribute("aria-label") ?? "").startsWith("society.companion.creature.number"));
- expect(figures[0].getAttribute("aria-pressed")).toBe("true");
- fireEvent.click(screen.getByRole("button", { name: "society.card.save" }));
- await waitFor(() => expect(saves()).toHaveLength(1));
- const [, init] = saves()[0] as unknown as [string, RequestInit];
- const creature = JSON.parse(init.body as string).avatar.companion.creature;
- expect("society.companion.creature.palettes." + creature.palette).toBe(rolled);
-});
diff --git a/dodaios/ui/web/frontend/src/components/society/companion/CompanionEditor.tsx b/dodaios/ui/web/frontend/src/components/society/companion/CompanionEditor.tsx
index 45ba3aed04..e60bc5fbfe 100644
--- a/dodaios/ui/web/frontend/src/components/society/companion/CompanionEditor.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/companion/CompanionEditor.tsx
@@ -1,77 +1,33 @@
import { useT } from "@/i18n";
import { Switch } from "@/components/ui/switch";
-import { AgentSymbol } from "../AgentSymbol";
-import { AccessoryPicker } from "./AccessoryPicker";
-import { COMPANION_COLORS, COMPANION_SHAPES, type CompanionAppearance } from "./appearance";
+import { type CompanionAppearance } from "./appearance";
import { CompanionMark } from "./CompanionMark";
-import { creatureFromShape, type CreatureLook, type CreatureState } from "./creature";
-import { CreaturePicker } from "./CreaturePicker";
-import { CreatureStage } from "./PixelCreature";
-import { growsCreature, useCreatureDefault } from "./creatureDefault";
-import { DesignPicker } from "./DesignPicker";
-import { SegmentedChoice } from "./SegmentedChoice";
import "../calmSheet.css";
import { PetSprite } from "@/components/pets/PetSprite";
import { usePets } from "@/hooks/usePets";
import gigiMark from "@/assets/gigi-companion-avatar.png";
-import { lazy, Suspense, useEffect, useState } from "react";
+import { lazy, Suspense } from "react";
const CompanionPreview = lazy(() => import("./CompanionPreview").then(m => ({ default: m.CompanionPreview })));
-export function CompanionEditor({ value, onChange, disabled = false, lead = false, preview3d = true, agentId }: {
+/** An agent's look is one of the pets from My Pets; shapes and pixel creatures are no longer offered. */
+export function CompanionEditor({ value, onChange, disabled = false, lead = false, preview3d = true }: {
value: CompanionAppearance; onChange: (next: CompanionAppearance) => void; disabled?: boolean; lead?: boolean;
- /** The agent whose level opens its looks; without one nothing is locked. */
+ /** Kept for callers; pets have no level-locked looks. */
agentId?: string;
/** The 3D turntable needs its own WebGL context; dialogs outside the map skip it. */
preview3d?: boolean;
}) {
const t = useT();
- // Picking a plain colour takes the design off; the design picker sends both together.
- const update = (patch: Partial<CompanionAppearance>) => onChange({ ...value, ...("color" in patch && !("skin" in patch) ? { skin: undefined } : {}), ...patch });
+ const update = (patch: Partial<CompanionAppearance>) => onChange({ ...value, ...patch });
const petsQuery = usePets();
const pets = petsQuery.data?.pets ?? [];
- const { enabled: creaturesByDefault, setEnabled: setCreaturesByDefault } = useCreatureDefault();
- // The creature last worn in this dialog comes back when the look returns to it; a first one grows from the shape.
- const [lastCreature, setLastCreature] = useState(value.creature);
- const creature = value.creature ?? lastCreature ?? creatureFromShape(value);
- const wear = (next: CreatureLook) => { setLastCreature(next); update({ pet: undefined, look: undefined, creature: next }); };
- const [mood, setMood] = useState<CreatureState>("idle");
- // The look is a shape, a pixel creature or a pet; "Pet" stays chosen even before a pet exists to pick.
- const [kind, setKind] = useState<"shape" | "creature" | "pet">(value.pet ? "pet" : value.creature || growsCreature(value, creaturesByDefault) ? "creature" : "shape");
- const choose = (next: "shape" | "creature" | "pet") => {
- setKind(next);
- // The shape, its colour and its accessories stay underneath a creature, for the way back.
- // Choosing the shape is stored: without that mark the look would grow a creature again.
- if (next === "shape") update({ pet: undefined, creature: undefined, look: "shape" });
- if (next === "creature") wear(creature);
- if (next === "pet") update({ creature: undefined, look: undefined, ...(!value.pet && pets[0] ? { pet: pets[0].id } : {}) });
- };
- // "Pet" chosen before the pets arrived: wear the first one as soon as they do.
- const firstPet = pets[0]?.id;
- useEffect(() => {
- if (kind === "pet" && !value.pet && firstPet) onChange({ ...value, pet: firstPet });
- }, [kind, value, firstPet, onChange]);
return <fieldset disabled={disabled} className="flex min-w-0 flex-col gap-5 p-4" data-testid="companion-editor">
<div className="flex items-center gap-5 rounded-[20px] bg-secondary/50 p-5">
- {lead ? <img src={gigiMark} width={88} height={88} alt="" /> : <CompanionMark appearance={value} size={88} mood={kind === "creature" ? mood : undefined} />}
- {/* A previewed state plays its sign beside the head; keep the text clear of it. */}
- {!lead && kind === "creature" && <span aria-hidden className="w-2 shrink-0" />}
+ {lead ? <img src={gigiMark} width={88} height={88} alt="" /> : <CompanionMark appearance={value} size={88} />}
<div><h3 className="text-[14px] font-medium">{t("society.companion.title")}</h3><p className="mt-1 text-[13px] leading-snug text-muted-foreground">{t("society.companion.hint")}</p></div>
</div>
- {/* A creature previews on a plain canvas, so it shows without a WebGL context; shapes and pets turn in the 3D studio. */}
- {preview3d && (!lead && kind === "creature"
- ? <CreatureStage creature={creature} state={mood} />
- : <Suspense fallback={null}><CompanionPreview appearance={value} lead={lead} /></Suspense>)}
- {/* One switch across the full width, like the access switch of the create dialog. */}
- {!lead && <div className="flex flex-col gap-2"><span className="text-[14px] font-medium">{t("society.companion.look")}</span>
- <SegmentedChoice label={t("society.companion.look")} value={kind} onChange={choose}
- options={(["creature", "shape", "pet"] as const).map(id => ({ id, label: t(`society.companion.look_${id}`) }))} />
- </div>}
- {!lead && kind !== "pet" && <label className="flex items-start justify-between gap-3 text-[14px]">
- <span>{t("society.companion.creature.by_default")}<span className="mt-0.5 block text-[13px] leading-snug text-muted-foreground">{t("society.companion.creature.by_default_hint")}</span></span>
- <Switch checked={creaturesByDefault} onCheckedChange={setCreaturesByDefault} aria-label={t("society.companion.creature.by_default")} />
- </label>}
- {!lead && kind === "creature" && <CreaturePicker value={creature} onChange={wear} mood={mood} onMood={setMood} />}
- {!lead && kind === "pet" && <div data-testid="companion-pet-picker"><span className="mb-1 block text-[14px] font-medium">{t("society.companion.pet")}</span>
+ {preview3d && <Suspense fallback={null}><CompanionPreview appearance={value} lead={lead} /></Suspense>}
+ {!lead && <div data-testid="companion-pet-picker"><span className="mb-1 block text-[14px] font-medium">{t("society.companion.pet")}</span>
<p className="mb-2 text-[13px] text-muted-foreground">{pets.length || petsQuery.isLoading ? t("society.companion.pet_hint") : t("society.companion.no_pets")}</p>
<div className="flex flex-wrap gap-2">{pets.map(pet => <button key={pet.id} type="button" title={pet.name}
aria-label={pet.name} aria-pressed={value.pet === pet.id} onClick={() => update({ pet: pet.id })}
@@ -79,30 +35,6 @@ export function CompanionEditor({ value, onChange, disabled = false, lead = fals
<PetSprite pet={pet} state={value.pet === pet.id ? "success" : "idle"} px={44} />
</button>)}</div>
</div>}
- {!lead && kind === "shape" && <><div><span className="mb-2 block text-[14px] font-medium">{t("society.companion.shape")}</span>
- <div className="flex flex-wrap gap-2">{COMPANION_SHAPES.map(shape => <button key={shape} type="button"
- aria-label={t(`society.companion.shapes.${shape}`)} aria-pressed={value.shape === shape}
- title={t(`society.companion.shapes.${shape}`)}
- onClick={() => update({ shape })} className="calm-tile h-16 w-16" data-on={value.shape === shape}>
- <AgentSymbol shape={shape} color={value.color} eyes={value.eyes} accessories={value.accessories} skin={value.skin} size={52} />
- </button>)}</div>
- </div>
- <div className="flex flex-col gap-2"><span className="text-[14px] font-medium">{t("society.companion.eyes")}</span>
- {/* Plain toggles: a popup menu inside a modal dialog can strand its pointer lock. */}
- <SegmentedChoice label={t("society.companion.eyes")} value={value.eyes} onChange={eyes => update({ eyes })}
- options={(["dots", "lines"] as const).map(id => ({ id, label: t(`society.companion.${id}`) }))} />
- </div>
- <AccessoryPicker value={value} onChange={accessories => update({ accessories })} agentId={agentId} />
- </>}
- {/* A shape is painted in the agent's colour; a pet brings its own colours. */}
- {!lead && kind === "shape" && <div><span className="mb-2 block text-[14px] font-medium">{t("society.companion.color")}</span>
- {/* Two rows across the full width: the swatches scale with the dialog instead of leaving a gap on the right. */}
- <div className="grid w-full grid-cols-12 items-center gap-2">{COMPANION_COLORS.map(color => <button key={color} type="button" aria-label={`${t("society.companion.color")} ${color}`} aria-pressed={value.color === color}
- onClick={() => update({ color })} className={`aspect-square w-full rounded-full shadow-[inset_0_0_0_1px_hsl(var(--border)/0.6)] ring-offset-2 ring-offset-popover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${value.color === color ? "ring-2 ring-foreground" : ""}`} style={{ background: color }} />)}
- <input type="color" aria-label={t("society.companion.custom_color")} value={value.color} onChange={e => update({ color: e.target.value })} className="aspect-square h-auto w-full rounded-full border-0 bg-transparent p-0" />
- </div>
- </div>}
- {!lead && kind === "shape" && <DesignPicker skin={value.skin} color={value.color} onChange={(skin, color) => update({ skin, color })} />}
<label className="flex items-center justify-between gap-3 text-[14px]">{t("society.companion.visible")}
<Switch checked={value.enabled} onCheckedChange={enabled => update({ enabled })} aria-label={t("society.companion.visible")} />
</label>
diff --git a/dodaios/ui/web/frontend/src/components/society/companion/CompanionMark.test.tsx b/dodaios/ui/web/frontend/src/components/society/companion/CompanionMark.test.tsx
index a8256af5fe..56d69ffaf8 100644
--- a/dodaios/ui/web/frontend/src/components/society/companion/CompanionMark.test.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/companion/CompanionMark.test.tsx
@@ -18,7 +18,7 @@ function pet(id: string): Pet {
}
const PETS: PetsState = { active: "gigi", scale: 1, bubble: true, strip_always: false, visible: true, pets: [pet("gigi"), pet("cocoa")] };
-const look = (patch: Partial<CompanionAppearance> = {}): CompanionAppearance => ({ ...defaultCompanion("agent"), shape: "drop", ...patch });
+const look = (patch: Partial<CompanionAppearance> = {}): CompanionAppearance => ({ ...defaultCompanion("agent"), shape: "drop", pet: undefined, ...patch });
/** A client already holding the pets answer (or none yet), so nothing is fetched. */
function renderWith(ui: React.ReactElement, state: PetsState | null = PETS) {
diff --git a/dodaios/ui/web/frontend/src/components/society/companion/CreaturePicker.tsx b/dodaios/ui/web/frontend/src/components/society/companion/CreaturePicker.tsx
deleted file mode 100644
index 7c23c76215..0000000000
--- a/dodaios/ui/web/frontend/src/components/society/companion/CreaturePicker.tsx
+++ /dev/null
@@ -1,70 +0,0 @@
-import { useState } from "react";
-import { useT } from "@/i18n";
-import {
- CREATURE_EYES, CREATURE_PALETTES, CREATURE_SEED_MAX, CREATURE_STATES, randomCreature, type CreatureLook, type CreatureState,
-} from "./creature";
-import { PixelCreature } from "./PixelCreature";
-import { SegmentedChoice } from "./SegmentedChoice";
-import "../calmSheet.css";
-
-const CHOICES = 8;
-const rollSeed = () => Math.floor(Math.random() * (CREATURE_SEED_MAX + 1));
-
-/**
- * Everything a pixel creature has to choose: one of eight rolled figures, a
- * colour world and an eye kind. "Roll again" rolls all three at once and
- * wears the result, so one click gives a whole new creature; the rows below
- * fine-tune it. The state row only previews what the creature acts out; it
- * is never saved.
- */
-export function CreaturePicker({ value, onChange, mood, onMood }: {
- value: CreatureLook; onChange: (next: CreatureLook) => void;
- mood: CreatureState; onMood: (mood: CreatureState) => void;
-}) {
- const t = useT();
- // The worn figure leads the first row, so opening the dialog never loses it.
- const [seeds, setSeeds] = useState(() => [value.seed, ...Array.from({ length: CHOICES - 1 }, rollSeed)]);
- const roll = () => {
- // Always another colour world, so a roll is never mistaken for a reshuffle of the same figure.
- let next = randomCreature();
- for (let tries = 0; next.palette === value.palette && tries < 8; tries++) next = randomCreature();
- setSeeds([next.seed, ...Array.from({ length: CHOICES - 1 }, rollSeed)]);
- onChange(next);
- };
- return <div className="flex flex-col gap-5" data-testid="creature-picker">
- <div>
- <div className="mb-2 flex items-center justify-between gap-3">
- <span className="text-[14px] font-medium">{t("society.companion.creature.figure")}</span>
- <button type="button" onClick={roll} className="cs-btn" data-variant="soft" data-size="sm">
- {t("society.companion.creature.roll")}
- </button>
- </div>
- <div className="flex flex-wrap gap-2">{seeds.map((seed, index) => <button key={`${index}-${seed}`} type="button"
- aria-label={t("society.companion.creature.number").replace("{0}", String(seed))} aria-pressed={value.seed === seed} onClick={() => onChange({ ...value, seed })}
- className="calm-tile h-14 w-14" data-on={value.seed === seed}>
- <PixelCreature creature={{ ...value, seed }} size={40} />
- </button>)}</div>
- </div>
- <div>
- <span className="mb-2 block text-[14px] font-medium">{t("society.companion.creature.palette")}</span>
- <div className="flex flex-wrap gap-2">{CREATURE_PALETTES.map(palette => <button key={palette.id} type="button"
- aria-label={t(`society.companion.creature.palettes.${palette.id}`)} title={t(`society.companion.creature.palettes.${palette.id}`)}
- aria-pressed={value.palette === palette.id} onClick={() => onChange({ ...value, palette: palette.id })}
- className={`h-9 w-9 rounded-full shadow-[inset_0_0_0_1px_hsl(var(--border)/0.6)] ring-offset-2 ring-offset-popover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${value.palette === palette.id ? "ring-2 ring-foreground" : ""}`}
- style={{ background: `linear-gradient(180deg, ${palette.colors.join(", ")})` }} />)}</div>
- </div>
- <div className="flex flex-col gap-2"><span className="text-[14px] font-medium">{t("society.companion.eyes")}</span>
- <SegmentedChoice label={t("society.companion.eyes")} value={value.eyes} onChange={eyes => onChange({ ...value, eyes })}
- options={CREATURE_EYES.map(id => ({ id, label: t(`society.companion.creature.eye_kinds.${id}`) }))} />
- </div>
- <div>
- <span className="mb-1 block text-[14px] font-medium">{t("society.companion.creature.states")}</span>
- <p className="mb-2 text-[13px] text-muted-foreground">{t("society.companion.creature.states_hint")}</p>
- <div className="flex flex-wrap gap-1" role="group" aria-label={t("society.companion.creature.states")}>
- {CREATURE_STATES.map(state => <button key={state} type="button" aria-pressed={mood === state} onClick={() => onMood(state)} className="cs-chip">
- {t(`society.companion.creature.state_names.${state}`)}
- </button>)}
- </div>
- </div>
- </div>;
-}
diff --git a/dodaios/ui/web/frontend/src/components/society/companion/DesignPicker.tsx b/dodaios/ui/web/frontend/src/components/society/companion/DesignPicker.tsx
deleted file mode 100644
index bbdfdd29c7..0000000000
--- a/dodaios/ui/web/frontend/src/components/society/companion/DesignPicker.tsx
+++ /dev/null
@@ -1,170 +0,0 @@
-/**
- * Designs in the look dialog: ready-made gradients with effects (Galaxy,
- * Aurora, Holo …), the person's saved designs, and an editor for their own:
- * up to four colours, linear or radial, a direction and an effect. Designs
- * come in from a design code, a CSS gradient, hex colours or a picture, and go
- * out as a design code or into "My designs" for any agent to wear.
- */
-import { useRef, useState } from "react";
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { Check, Copy, ImageUp, Import, Minus, Plus, Save, X } from "lucide-react";
-import { useT } from "@/i18n";
-import {
- encodeDesignCode, parseDesignImport, sameSkin, skinBlend, skinCss, skinFromImage,
- SKIN_EFFECTS, SKIN_PATTERNS, SKIN_PRESETS, type CompanionSkin,
-} from "./skins";
-
-export interface SavedDesign { id: string; skin: CompanionSkin; created: number }
-
-const DESIGNS_KEY = ["society", "designs"] as const;
-
-async function fetchDesigns(): Promise<SavedDesign[]> {
- const res = await fetch("/api/society/designs", { cache: "no-store" });
- // A backend from before saved designs: nothing saved yet.
- if (res.status === 404) return [];
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- return ((await res.json()) as { designs: SavedDesign[] }).designs;
-}
-
-const chip = (on: boolean) => `rounded-full border px-2.5 py-1 text-xs ${on ? "border-transparent bg-primary text-primary-foreground" : "border-border bg-background text-foreground hover:bg-secondary"}`;
-const tile = (on: boolean) => `relative aspect-square w-full rounded-full border border-border ring-offset-2 ring-offset-popover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${on ? "ring-2 ring-foreground" : ""}`;
-
-/** A lighter or darker twin of a colour, to start a design from the plain one. */
-function shade(color: string, amount: number): string {
- const n = parseInt(color.slice(1), 16);
- const mix = (v: number) => Math.round(amount > 0 ? v + (255 - v) * amount : v * (1 + amount));
- return `#${[(n >> 16) & 255, (n >> 8) & 255, n & 255].map(v => mix(v).toString(16).padStart(2, "0")).join("")}`;
-}
-
-export function DesignPicker({ skin, color, onChange }: {
- skin: CompanionSkin | undefined; color: string;
- /** A design to wear (its blended colour comes along), or undefined for the plain colour. */
- onChange: (skin: CompanionSkin | undefined, color: string) => void;
-}) {
- const t = useT();
- const client = useQueryClient();
- const designs = useQuery({ queryKey: DESIGNS_KEY, queryFn: fetchDesigns, staleTime: 60_000, retry: false });
- const [importing, setImporting] = useState(false);
- const [pasted, setPasted] = useState("");
- const [notice, setNotice] = useState<"" | "import_error" | "image_error" | "save_error" | "copied" | "saved">("");
- const file = useRef<HTMLInputElement>(null);
- const wear = (next: CompanionSkin | undefined) => { setNotice(""); onChange(next, next ? skinBlend(next.colors) : color); };
- const edit = (patch: Partial<CompanionSkin>) => skin && wear({ ...skin, ...patch });
-
- const save = useMutation({
- mutationFn: async (design: CompanionSkin) => {
- const res = await fetch("/api/society/designs", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(design) });
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- return (await res.json()) as SavedDesign;
- },
- onSuccess: () => { setNotice("saved"); void client.invalidateQueries({ queryKey: DESIGNS_KEY }); },
- onError: () => setNotice("save_error"),
- });
- const remove = useMutation({
- mutationFn: async (id: string) => {
- const res = await fetch(`/api/society/designs/${encodeURIComponent(id)}`, { method: "DELETE" });
- if (!res.ok && res.status !== 404) throw new Error(`HTTP ${res.status}`);
- },
- onSettled: () => void client.invalidateQueries({ queryKey: DESIGNS_KEY }),
- });
-
- const applyImport = () => {
- const found = parseDesignImport(pasted);
- if (!found) { setNotice("import_error"); return; }
- wear(found); setImporting(false); setPasted("");
- };
- const fromPicture = async (picked: File | undefined) => {
- if (!picked) return;
- try {
- const found = await skinFromImage(picked);
- if (found) wear({ ...found, name: picked.name.replace(/\.[^.]+$/, "").slice(0, 40) }); else setNotice("image_error");
- } catch { setNotice("image_error"); } // An unreadable or unsupported file: say so, keep the look.
- finally { if (file.current) file.current.value = ""; }
- };
- const copyCode = async () => {
- if (!skin) return;
- try { await navigator.clipboard.writeText(encodeDesignCode(skin)); setNotice("copied"); }
- catch { setImporting(true); setPasted(encodeDesignCode(skin)); } // No clipboard: show the code to copy by hand.
- };
-
- const saved = designs.data ?? [];
- return <div className="grid gap-3" data-testid="design-picker">
- <div>
- <span className="block text-sm font-medium">{t("society.companion.design.title")}</span>
- <p className="mt-0.5 text-xs text-muted-foreground">{t("society.companion.design.hint")}</p>
- </div>
- <div className="grid w-full grid-cols-10 items-center gap-2" role="group" aria-label={t("society.companion.design.title")}>
- {SKIN_PRESETS.map(preset => {
- const label = t(`society.companion.design.presets.${preset.id}`);
- const look = { ...preset.skin, name: label };
- return <button key={preset.id} type="button" title={label} aria-label={label} aria-pressed={sameSkin(skin, look)}
- onClick={() => wear(look)} className={tile(sameSkin(skin, look))} style={{ background: skinCss(look) }} />;
- })}
- <button type="button" title={t("society.companion.design.create")} aria-label={t("society.companion.design.create")}
- onClick={() => wear({ colors: [shade(color, 0.45), color, shade(color, -0.45)], pattern: "linear", angle: 160, effect: "none", name: "" })}
- className={`${tile(false)} grid place-items-center bg-background text-muted-foreground hover:bg-secondary`}><Plus size={16} /></button>
- </div>
- {saved.length > 0 && <div>
- <span className="mb-1.5 block text-xs text-muted-foreground">{t("society.companion.design.mine")}</span>
- <div className="grid w-full grid-cols-10 items-center gap-2">{saved.map(design => {
- const label = design.skin.name || t("society.companion.design.custom");
- return <div key={design.id} className="group relative">
- <button type="button" title={label} aria-label={label} aria-pressed={sameSkin(skin, design.skin)}
- onClick={() => wear(design.skin)} className={tile(sameSkin(skin, design.skin))} style={{ background: skinCss(design.skin) }} />
- <button type="button" aria-label={t("society.companion.design.delete").replace("{0}", label)} onClick={() => remove.mutate(design.id)}
- className="absolute -right-1 -top-1 grid h-4 w-4 place-items-center rounded-full border border-border bg-popover text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100"><X size={10} /></button>
- </div>;
- })}</div>
- </div>}
- <div className="flex flex-wrap gap-1.5">
- <button type="button" className={chip(importing)} aria-pressed={importing} onClick={() => { setImporting(v => !v); setNotice(""); }}>
- <Import size={12} className="mr-1 inline" />{t("society.companion.design.import")}</button>
- <button type="button" className={chip(false)} onClick={() => file.current?.click()}>
- <ImageUp size={12} className="mr-1 inline" />{t("society.companion.design.from_image")}</button>
- <input ref={file} type="file" accept="image/*" className="hidden" aria-hidden tabIndex={-1} onChange={e => void fromPicture(e.target.files?.[0])} />
- {skin && <button type="button" className={chip(false)} onClick={() => wear(undefined)}>{t("society.companion.design.plain")}</button>}
- </div>
- {importing && <div className="grid gap-2">
- <textarea value={pasted} onChange={e => setPasted(e.target.value)} rows={2} spellCheck={false} placeholder={t("society.companion.design.import_hint")}
- aria-label={t("society.companion.design.import")} className="w-full resize-none rounded-md border border-border bg-background px-2.5 py-1.5 font-mono text-xs" />
- <div className="flex justify-end"><button type="button" className={chip(true)} disabled={!pasted.trim()} onClick={applyImport}>{t("society.companion.design.import_apply")}</button></div>
- </div>}
- {skin && <div className="grid gap-3 rounded-lg border border-border p-3" data-testid="design-editor">
- <div className="flex flex-wrap items-center justify-between gap-2 text-sm"><span>{t("society.companion.design.colors")}</span>
- <div className="flex items-center gap-1.5">
- {skin.colors.map((stop, index) => <input key={index} type="color" value={stop} aria-label={`${t("society.companion.design.colors")} ${index + 1}`}
- onChange={e => edit({ colors: skin.colors.map((c, i) => i === index ? e.target.value : c) })} className="h-8 w-9 rounded border border-border bg-background" />)}
- {skin.colors.length > 2 && <button type="button" aria-label={t("society.companion.design.remove_color")} onClick={() => edit({ colors: skin.colors.slice(0, -1) })}
- className="grid h-8 w-8 place-items-center rounded border border-border hover:bg-secondary"><Minus size={14} /></button>}
- {skin.colors.length < 4 && <button type="button" aria-label={t("society.companion.design.add_color")} onClick={() => edit({ colors: [...skin.colors, skin.colors[skin.colors.length - 1]!] })}
- className="grid h-8 w-8 place-items-center rounded border border-border hover:bg-secondary"><Plus size={14} /></button>}
- </div>
- </div>
- <div className="flex flex-wrap items-center justify-between gap-2 text-sm"><span>{t("society.companion.design.pattern")}</span>
- <div className="flex gap-1.5" role="group" aria-label={t("society.companion.design.pattern")}>
- {SKIN_PATTERNS.map(pattern => <button key={pattern} type="button" aria-pressed={skin.pattern === pattern} onClick={() => edit({ pattern })} className={chip(skin.pattern === pattern)}>
- {t(`society.companion.design.pattern_${pattern}`)}</button>)}
- </div>
- </div>
- {skin.pattern === "linear" && <label className="flex items-center justify-between gap-3 text-sm">{t("society.companion.design.angle")}
- <input type="range" min={0} max={359} step={1} value={skin.angle} onChange={e => edit({ angle: Number(e.target.value) })} className="w-40 accent-primary" />
- </label>}
- <div className="grid gap-1.5 text-sm"><span>{t("society.companion.design.effect")}</span>
- <div className="flex flex-wrap gap-1.5" role="group" aria-label={t("society.companion.design.effect")}>
- {SKIN_EFFECTS.map(effect => <button key={effect} type="button" aria-pressed={skin.effect === effect} onClick={() => edit({ effect })} className={chip(skin.effect === effect)}>
- {t(`society.companion.design.effects.${effect}`)}</button>)}
- </div>
- </div>
- <div className="flex flex-wrap items-center gap-2">
- <input value={skin.name} maxLength={40} onChange={e => edit({ name: e.target.value.replace(/[\p{Cc}]/gu, "") })} placeholder={t("society.companion.design.name_placeholder")}
- aria-label={t("society.companion.design.name")} className="h-8 min-w-0 flex-1 rounded-md border border-border bg-background px-2.5 text-sm" />
- <button type="button" className={chip(false)} disabled={save.isPending} onClick={() => save.mutate(skin)}>
- <Save size={12} className="mr-1 inline" />{t("society.companion.design.save")}</button>
- <button type="button" className={chip(false)} onClick={() => void copyCode()}>
- {notice === "copied" ? <Check size={12} className="mr-1 inline" /> : <Copy size={12} className="mr-1 inline" />}{t(notice === "copied" ? "society.companion.design.copied" : "society.companion.design.copy_code")}</button>
- </div>
- </div>}
- {notice && notice !== "copied" && <p role={notice.endsWith("error") ? "alert" : "status"} className={`text-xs ${notice.endsWith("error") ? "text-destructive" : "text-muted-foreground"}`}>
- {t(`society.companion.design.${notice}`)}</p>}
- </div>;
-}
diff --git a/dodaios/ui/web/frontend/src/components/society/companion/SegmentedChoice.tsx b/dodaios/ui/web/frontend/src/components/society/companion/SegmentedChoice.tsx
deleted file mode 100644
index 5c5853f466..0000000000
--- a/dodaios/ui/web/frontend/src/components/society/companion/SegmentedChoice.tsx
+++ /dev/null
@@ -1,24 +0,0 @@
-import "../calmSheet.css";
-
-/**
- * One of a few choices as a single switch across the full width: the look
- * editor's rows (look, eyes, accessory slot) all read and click alike.
- */
-export function SegmentedChoice<T extends string>({ options, value, onChange, label, role = "group", marked }: {
- options: readonly { id: T; label: string }[]; value: T; onChange: (next: T) => void;
- /** What the row chooses, for assistive technology. */
- label: string;
- /** "tablist" when the choice swaps the panel below it. */
- role?: "group" | "tablist";
- /** Choices that carry a small dot (a slot that already wears something). */
- marked?: ReadonlySet<T>;
-}) {
- return <div className="cs-tabs" data-fill="true" role={role} aria-label={label}>
- {options.map(option => <button key={option.id} type="button" onClick={() => onChange(option.id)}
- {...(role === "tablist" ? { role: "tab", "aria-selected": value === option.id } : { "aria-pressed": value === option.id })}
- className="cs-tab">
- {option.label}
- {marked?.has(option.id) && <span aria-hidden className="ml-1.5 inline-block h-1.5 w-1.5 rounded-full bg-current align-middle" />}
- </button>)}
- </div>;
-}
diff --git a/dodaios/ui/web/frontend/src/components/society/companion/appearance.ts b/dodaios/ui/web/frontend/src/components/society/companion/appearance.ts
index e3f853fb36..22446a6746 100644
--- a/dodaios/ui/web/frontend/src/components/society/companion/appearance.ts
+++ b/dodaios/ui/web/frontend/src/components/society/companion/appearance.ts
@@ -17,6 +17,11 @@ export const COMPANION_SIZE_M = 0.5;
export const COMPANION_FOLLOW_DISTANCE_M = 1;
/** `PetId` in `dodaios/society/companion.py` (built-in slug or a drawn pet's `u<hex>`). */
export const PET_ID = /^[a-z0-9][a-z0-9-]{0,31}$/;
+/**
+ * The built-in pets an agent wears when nobody picked one (`DEFAULT_PETS` in
+ * `dodaios/society/companion.py`). Gigi stays the lead's own face.
+ */
+export const DEFAULT_PETS = ["ember", "miso", "bolt", "brew", "mochi", "shelly", "cocoa", "dodaios"] as const;
export const companionSchema = z.object({
shape: z.enum(COMPANION_SHAPES), color: z.string().regex(/^#[0-9a-fA-F]{6}$/),
eyes: z.enum(["dots", "lines"]).default("lines"), enabled: z.boolean().default(true),
@@ -49,12 +54,24 @@ export function defaultCompanion(identity: string): CompanionAppearance {
shape: COMPANION_SHAPES[identityHash(`shape:${identity}`) % COMPANION_SHAPES.length]!,
color: COMPANION_COLORS[identityHash(`color:${identity}`) % DEFAULT_COLOR_COUNT]!,
eyes: "lines", enabled: true, accessories: {}, sizeM: COMPANION_SIZE_M, followDistanceM: COMPANION_FOLLOW_DISTANCE_M,
+ pet: defaultPet(identity),
};
}
+/** The built-in pet an agent wears until one is picked for it; stable per agent. */
+export function defaultPet(identity: string): string {
+ return DEFAULT_PETS[identityHash(`pet:${identity}`) % DEFAULT_PETS.length]!;
+}
+
+/**
+ * Agents wear pets only. A look saved before that (a shape or a pixel
+ * creature) is shown with the agent's default pet instead.
+ */
export function resolveCompanion(identity: string, stored?: unknown): CompanionAppearance {
const parsed = companionSchema.safeParse(stored);
- return parsed.success ? parsed.data : defaultCompanion(identity);
+ if (!parsed.success) return defaultCompanion(identity);
+ const { creature: _creature, look: _look, ...look } = parsed.data;
+ return { ...look, pet: look.pet ?? defaultPet(identity) };
}
/** The same plain black ink in profiles and in the map, without catchlights. */
diff --git a/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx b/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx
index 3a1967790a..b62e619688 100644
--- a/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx
@@ -24,7 +24,6 @@ import { cn } from "@/lib/utils";
import { AgentNameTaken, RuntimeProviderUnsupported, rowToAgent, useCreateSocietyAgent, type SocietyAgent } from "../data";
import type { SocietyAgentRow } from "@/lib/societyApi";
import { defaultCompanion, type CompanionAppearance } from "../companion/appearance";
-import { randomCreature } from "../companion/creature";
import { announceSpawn } from "../world/spawnStore";
import { useCreateAgentDialog, type CreateAgentMode } from "./createAgentStore";
import { seedFirstMessage } from "./firstMessage";
@@ -42,9 +41,9 @@ const CompanionEditor = lazy(() =>
const MODES: readonly { id: CreateAgentMode }[] = [{ id: "quick" }, { id: "starter" }, { id: "import" }];
-/** A new agent starts as a pixel creature; the shape underneath is there for a change of mind. */
+/** A new agent starts with a random built-in pet. */
function randomCompanion(): CompanionAppearance {
- return { ...defaultCompanion(`${Date.now()}:${Math.random()}`), creature: randomCreature() };
+ return defaultCompanion(`${Date.now()}:${Math.random()}`);
}
function starterSeat(pick: SeatPick, companion: CompanionAppearance): StarterSeat {
diff --git a/dodaios/ui/web/frontend/src/components/society/roster/RosterRail.test.tsx b/dodaios/ui/web/frontend/src/components/society/roster/RosterRail.test.tsx
index 4dd8b2eb71..ea45726f68 100644
--- a/dodaios/ui/web/frontend/src/components/society/roster/RosterRail.test.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/roster/RosterRail.test.tsx
@@ -7,6 +7,8 @@ import { useRetireStore } from "@/components/society/world/retireStore";
import { useEventStore } from "@/store/events";
import { RosterRail, type RosterRailProps } from "./RosterRail";
+// Every agent wears a pet; these tests count their own requests, so the pets answer stays out of fetch.
+vi.mock("@/hooks/usePets", async (original) => ({ ...(await original<typeof import("@/hooks/usePets")>()), usePetById: () => null }));
vi.mock("@/i18n", () => ({ useT: () => (key: string) => key, useUiLanguage: () => "en" }));
afterEach(() => {
diff --git a/tests/contract/test_society_one_click_create.py b/tests/contract/test_society_one_click_create.py
index 34a797fb0c..0ec3be9eab 100644
--- a/tests/contract/test_society_one_click_create.py
+++ b/tests/contract/test_society_one_click_create.py
@@ -16,6 +16,7 @@ from dodaios.society.companion import (
COMPANION_SHAPES,
CREATURE_EYES,
CREATURE_PALETTES,
+ DEFAULT_PETS,
CompanionAppearance,
random_companion,
)
@@ -103,10 +104,9 @@ async def test_every_new_agent_gets_a_valid_random_companion(roster: Roster):
companion = CompanionAppearance.model_validate(agent.avatar["companion"])
assert companion.shape in COMPANION_SHAPES
assert companion.color in COMPANION_COLORS
- # A new agent starts as a pixel creature.
- assert companion.creature is not None
- assert companion.creature.palette in CREATURE_PALETTES
- assert companion.creature.eyes in CREATURE_EYES
+ # A new agent starts with a built-in pet, never a pixel creature.
+ assert companion.pet in DEFAULT_PETS
+ assert companion.creature is None
async def test_an_explicit_avatar_is_kept(roster: Roster):
@@ -131,6 +131,15 @@ def test_companion_choices_match_the_frontend():
assert tuple(re.findall(r'"([^"]+)"', colors.group(1))) == COMPANION_COLORS
+def test_default_pets_match_the_frontend_and_exist():
+ source = APPEARANCE_TS.read_text(encoding="utf-8")
+ pets = re.search(r"DEFAULT_PETS = \[([^\]]*)\]", source)
+ assert pets
+ assert tuple(re.findall(r'"([^"]+)"', pets.group(1))) == DEFAULT_PETS
+ builtin = Path(__file__).resolve().parents[2] / "dodaios" / "ui" / "pets" / "builtin"
+ assert all((builtin / pet).is_dir() for pet in DEFAULT_PETS)
+
+
def test_creature_choices_match_the_frontend():
source = CREATURE_TS.read_text(encoding="utf-8")
eyes = re.search(r"CREATURE_EYES = \[([^\]]*)\]", source)