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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(world): the conversation model - near talks, far calls, bounded rooms
rubenluetke10-beep859089e634cf
diff --git a/jarvis/ui/web/frontend/src/components/society/world/conversation.test.ts b/jarvis/ui/web/frontend/src/components/society/world/conversation.test.tsnew file mode 100644index 0000000000..c3841e0083--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/conversation.test.ts@@ -0,0 +1,244 @@+import { describe, expect, it } from "vitest";++import { MSG_TYPES } from "@/lib/societyApi";+import { headingFor } from "./walkerKinematics";+import {+ ARC_BEADS,+ BUBBLE_MAX_S,+ BUBBLE_MIN_S,+ CALL_ORDER,+ MIN_FACE_M,+ NEAR_EXIT_M,+ NEAR_RADIUS_M,+ ROOM_ORDER,+ TALK_ORDER,+ WORLD_MSG_TYPES,+ arcApexFor,+ arcPoint,+ beadAlive,+ beadScale,+ bubbleSeconds,+ classify,+ clamp01,+ driftedApart,+ ease,+ facingBetween,+ hangupSweep,+ isOpenPhase,+ kindOf,+ nextCallPhase,+ nextRoomPhase,+ nextTalkPhase,+ pairKey,+ pingFade,+ pingScale,+ roomKey,+ tangentFacing,+} from "./conversation";++describe("who is talking to whom", () => {+ it("keys a pair the same way round", () => {+ expect(pairKey("scout", "archivist")).toBe(pairKey("archivist", "scout"));+ expect(pairKey("a", "b")).toBe("a|b");+ });++ it("keeps a room's key apart from any pair", () => {+ expect(roomKey("r1")).toBe("room:r1");+ expect(roomKey("r1")).not.toBe(pairKey("room", "r1"));+ });++ it("names the bubble by the board type", () => {+ expect(kindOf("QUERY")).toBe("query");+ expect(kindOf("ANSWER")).toBe("answer");+ expect(kindOf("PROPOSE")).toBe("propose");+ expect(kindOf("SAY")).toBe("say");+ expect(kindOf("nonsense")).toBe("say");+ });+});++describe("near or far", () => {+ it("talks inside the radius and calls outside it", () => {+ expect(classify(0)).toBe("talk");+ expect(classify(NEAR_RADIUS_M - 0.1)).toBe("talk");+ expect(classify(NEAR_RADIUS_M)).toBe("call");+ expect(classify(120)).toBe("call");+ });++ it("holds a running talk through the hysteresis band", () => {+ expect(NEAR_EXIT_M).toBeGreaterThan(NEAR_RADIUS_M);+ expect(driftedApart(NEAR_RADIUS_M + 1)).toBe(false);+ expect(driftedApart(NEAR_EXIT_M + 0.1)).toBe(true);+ });++ it("puts the two closest distinct hubs safely on the far side", () => {+ // The Signal Office and the Desktop hall are mirrored halves of one block+ // template, 28 m apart — the tightest pair the island can produce.+ expect(classify(28)).toBe("call");+ // …and two figures on one stand tile are always well inside.+ expect(classify(0.6)).toBe("talk");+ });+});++describe("how long a line stays up", () => {+ it("is monotonic and clamped", () => {+ expect(bubbleSeconds(0)).toBe(BUBBLE_MIN_S);+ expect(bubbleSeconds(10_000)).toBe(BUBBLE_MAX_S);+ expect(bubbleSeconds(120)).toBeGreaterThan(bubbleSeconds(20));+ expect(bubbleSeconds(-5)).toBe(BUBBLE_MIN_S);+ });++ it("keeps a full 180-character preview readable", () => {+ const s = bubbleSeconds(180);+ expect(s).toBeGreaterThanOrEqual(BUBBLE_MIN_S);+ expect(s).toBeLessThanOrEqual(BUBBLE_MAX_S);+ });+});++describe("the phase clocks", () => {+ it("walks each order and stops at done", () => {+ expect(TALK_ORDER[TALK_ORDER.length - 1]).toBe("done");+ expect(nextTalkPhase("turn")).toBe("speak");+ expect(nextTalkPhase("hold")).toBe("done");+ expect(nextTalkPhase("done")).toBe("done");++ expect(nextCallPhase("dial")).toBe("arc");+ expect(nextCallPhase("hangup")).toBe("done");+ expect(nextCallPhase("done")).toBe("done");+ expect(CALL_ORDER).toContain("arc");++ expect(nextRoomPhase("opening")).toBe("live");+ expect(nextRoomPhase("closing")).toBe("done");+ expect(ROOM_ORDER[0]).toBe("opening");+ });++ it("marks exactly the phases that end on an event, not a clock", () => {+ expect(isOpenPhase("speak")).toBe(true);+ expect(isOpenPhase("live")).toBe(true);+ expect(isOpenPhase("turn")).toBe(false);+ expect(isOpenPhase("hangup")).toBe(false);+ });+});++describe("facing", () => {+ it("agrees with the walker's own +Z convention", () => {+ // This is the assertion that stops a figure talking to the back of a head:+ // the pipeline faces +Z, so the heading is atan2(dx, dz).+ for (const [dx, dz] of [+ [1, 0],+ [0, 1],+ [-1, 0],+ [0, -1],+ [3, -4],+ ] as const) {+ expect(facingBetween(0, 0, dx, dz)).toBeCloseTo(headingFor(dx, dz), 10);+ }+ });++ it("looks straight at the other one", () => {+ expect(facingBetween(0, 0, 0, 5)).toBeCloseTo(0, 10);+ expect(facingBetween(0, 0, 5, 0)).toBeCloseTo(Math.PI / 2, 10);+ });++ it("turns two figures on one tile across each other, not into each other", () => {+ const front = 0.4;+ const a = tangentFacing(front, 1);+ const b = tangentFacing(front, -1);+ expect(Math.abs(a - b)).toBeCloseTo(Math.PI, 10);+ expect(MIN_FACE_M).toBeGreaterThan(0.6); // wider than the lateral offset+ });+});++describe("the signal arc", () => {+ const a = { x: -10, y: 2.7, z: 4 };+ const b = { x: 30, y: 3.9, z: -12 };++ it("starts at one head and ends at the other", () => {+ expect(arcPoint(a, b, 0, 12)).toEqual(a);+ const end = arcPoint(a, b, 1, 12);+ expect(end.x).toBeCloseTo(b.x, 10);+ expect(end.y).toBeCloseTo(b.y, 10);+ expect(end.z).toBeCloseTo(b.z, 10);+ });++ it("actually reaches its apex in the middle", () => {+ const apex = 12;+ const mid = arcPoint(a, b, 0.5, apex);+ expect(mid.y).toBeCloseTo((a.y + b.y) / 2 + apex, 10);+ });++ it("never dips below the lower head", () => {+ for (let t = 0; t <= 1.0001; t += 0.05) {+ expect(arcPoint(a, b, t, 9).y).toBeGreaterThanOrEqual(Math.min(a.y, b.y) - 1e-9);+ }+ });++ it("clamps its rise so it clears the island without a terrain query", () => {+ expect(arcApexFor(0)).toBe(5);+ expect(arcApexFor(28)).toBeCloseTo(7.48, 2);+ expect(arcApexFor(400)).toBe(22);+ // The summit sits at 12.6 m and the town at 1.8 m.+ expect(arcApexFor(120)).toBeGreaterThan(12.6 - 1.8);+ });+});++describe("the beads", () => {+ it("is born only at the sending end", () => {+ expect(beadScale(0, ARC_BEADS, 0)).toBeGreaterThan(0);+ expect(beadScale(ARC_BEADS - 1, ARC_BEADS, 0)).toBe(0);+ });++ it("lights every bead once the signal has landed", () => {+ for (let i = 0; i < ARC_BEADS; i++) {+ expect(beadScale(i, ARC_BEADS, 1)).toBeGreaterThan(0);+ }+ });++ it("stays inside 0..1", () => {+ for (let t = 0; t <= 1.0001; t += 0.1) {+ for (let i = 0; i < ARC_BEADS; i++) {+ const s = beadScale(i, ARC_BEADS, t);+ expect(s).toBeGreaterThanOrEqual(0);+ expect(s).toBeLessThanOrEqual(1);+ }+ }+ });++ it("runs off from the sending end on hang-up", () => {+ expect(hangupSweep(0)).toBe(0);+ expect(hangupSweep(99)).toBe(1);+ expect(beadAlive(0, ARC_BEADS, 0.5)).toBe(false);+ expect(beadAlive(ARC_BEADS - 1, ARC_BEADS, 0.5)).toBe(true);+ expect(beadAlive(ARC_BEADS - 1, ARC_BEADS, 1)).toBe(false);+ });+});++describe("the small curves", () => {+ it("clamps and eases", () => {+ expect(clamp01(-3)).toBe(0);+ expect(clamp01(3)).toBe(1);+ expect(ease(0)).toBe(0);+ expect(ease(1)).toBe(1);+ expect(ease(0.5)).toBeCloseTo(0.5, 10);+ });++ it("expands a ping and fades it as it goes", () => {+ expect(pingScale(0)).toBe(0);+ expect(pingScale(99)).toBe(1);+ expect(pingFade(0)).toBe(1);+ expect(pingFade(99)).toBe(0);+ });+});++describe("the drift guard", () => {+ it("only lists board types the backend can actually produce", () => {+ for (const type of WORLD_MSG_TYPES) {+ expect(MSG_TYPES).toContain(type);+ }+ });++ it("covers every talking type and both room brackets", () => {+ expect(new Set(WORLD_MSG_TYPES)).toEqual(+ new Set(["SAY", "QUERY", "ANSWER", "PROPOSE", "ROOM_OPEN", "ROOM_SETTLE"]),+ );+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/world/conversation.ts b/jarvis/ui/web/frontend/src/components/society/world/conversation.tsnew file mode 100644index 0000000000..3fcdf7fc7b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/conversation.ts@@ -0,0 +1,354 @@+/**+ * Two agents talking, as numbers — the pure half.+ *+ * A message on the board is not a row in a log. On the island it is either a+ * conversation (two figures close enough to turn to each other and speak) or a+ * call (a signal arcing across the map between two shops that are nowhere near+ * one another). Which one it is depends on nothing but the distance between+ * their feet, and the distance is free: every walker writes its position into+ * `walkerRegistry.ts` each frame.+ *+ * Everything here is a pure function of a phase and a local time, so the whole+ * choreography can be pinned by `conversation.test.ts` without a Canvas — the+ * shape `walkerKinematics.ts` and `retirement.ts` already use. The R3F side+ * (`ConversationScene.tsx`) owns the meshes and the clock; the store+ * (`conversationStore.ts`) owns which conversations are live and hands out the+ * per-frame poses the walkers read.+ *+ * The one rule that outranks every number below: **nothing an agent says moves+ * it** (`docs/agent-society/world-behaviour-manual.md` §1). A conversation may+ * turn a head and open a mouth. It may never take a step.+ */++/** What kind of line it was — the bubble is tinted and labelled by this. */+export type TalkKind = "say" | "query" | "answer" | "propose";++/** Close enough to speak, or far enough to need a signal. */+export type ConvoKind = "talk" | "call";++/** The beats of a near conversation. */+export type TalkPhase =+ | "turn" // both heads come round+ | "speak" // the bubble is up, the speaker plays `talk`+ | "hold" // the bubble is gone, the facing lingers so a reply can land+ | "done";++/** The beats of a call. */+export type CallPhase =+ | "dial" // handset and antenna pop, the ground pips light+ | "arc" // the signal travels the bezier+ | "speak" // the bubble is up at the receiving end+ | "hangup" // the arc runs off, the badges fade+ | "done";++/** The beats of a bounded room at the Town Hall. */+export type RoomPhase =+ | "opening" // the ring scales in under the table+ | "live" // ends on an event, not a clock+ | "settling" // the banner says why it broke up+ | "closing"+ | "done";++// ---------------------------------------------------------------------------+// phase clocks+// ---------------------------------------------------------------------------++/** `speak` is 0 here because its length is the text (see `bubbleSeconds`). */+export const TALK_SECONDS: Record<TalkPhase, number> = {+ turn: 0.45,+ speak: 0,+ hold: 0.6,+ done: 0,+};++export const CALL_SECONDS: Record<CallPhase, number> = {+ dial: 0.35,+ arc: 0.75,+ speak: 0,+ hangup: 0.7,+ done: 0,+};++/** `live` is 0 because the backend ends it, not a timer. */+export const ROOM_SECONDS: Record<RoomPhase, number> = {+ opening: 0.5,+ live: 0,+ settling: 1.6,+ closing: 0.8,+ done: 0,+};++export const TALK_ORDER: readonly TalkPhase[] = ["turn", "speak", "hold", "done"];+export const CALL_ORDER: readonly CallPhase[] = ["dial", "arc", "speak", "hangup", "done"];+export const ROOM_ORDER: readonly RoomPhase[] = [+ "opening",+ "live",+ "settling",+ "closing",+ "done",+];++function step<T extends string>(order: readonly T[], phase: T): T {+ const i = order.indexOf(phase);+ if (i < 0 || i >= order.length - 1) return order[order.length - 1];+ return order[i + 1];+}++export function nextTalkPhase(phase: TalkPhase): TalkPhase {+ return step(TALK_ORDER, phase);+}+export function nextCallPhase(phase: CallPhase): CallPhase {+ return step(CALL_ORDER, phase);+}+export function nextRoomPhase(phase: RoomPhase): RoomPhase {+ return step(ROOM_ORDER, phase);+}++/** True while the phase waits for an event rather than a clock. */+export function isOpenPhase(phase: TalkPhase | CallPhase | RoomPhase): boolean {+ return phase === "speak" || phase === "live";+}++// ---------------------------------------------------------------------------+// near or far+// ---------------------------------------------------------------------------++/**+ * Close enough to talk across, in metres — seven tiles at `TILE_M = 2`.+ *+ * Not a guess. Two figures standing at the SAME place are `lateralOffset`+ * apart (±0.3 m) plus a tile or two of wander, so under ~4 m. The two closest+ * DISTINCT hubs on the island (the Signal Office and the Desktop hall, mirrored+ * halves of the same block template) stand 28 m apart. 14 m is exactly halfway:+ * no pair of different shops can ever read as "near", and no pair at one shop+ * can ever read as "far".+ */+export const NEAR_RADIUS_M = 14;++/**+ * A running talk only gives up its bubbles past this. The 6 m band is pure+ * hysteresis: a wandering figure at the boundary must not flip a live+ * conversation into a call mid-sentence.+ */+export const NEAR_EXIT_M = 20;++/**+ * Closer than this and the vector between two figures is too short to derive a+ * heading from — it jitters, and the two would turn into each other. Below it,+ * they face along the building's front instead (`tangentFacing`).+ */+export const MIN_FACE_M = 0.9;++/** Which choreography a fresh conversation gets. Decided once, at ingest. */+export function classify(distanceM: number): ConvoKind {+ return distanceM < NEAR_RADIUS_M ? "talk" : "call";+}++/** True when a live talk has drifted far enough to drop its facing. */+export function driftedApart(distanceM: number): boolean {+ return distanceM > NEAR_EXIT_M;+}++// ---------------------------------------------------------------------------+// how long a line is up+// ---------------------------------------------------------------------------++export const BUBBLE_MIN_S = 2.2;+export const BUBBLE_MAX_S = 7.0;+export const BUBBLE_BASE_S = 1.6;+/** Characters per second of reading time — a comfortable island pace. */+export const BUBBLE_CHARS_PER_S = 22;++/** How long a bubble of `chars` characters stays up, in seconds. */+export function bubbleSeconds(chars: number): number {+ const raw = BUBBLE_BASE_S + Math.max(0, chars) / BUBBLE_CHARS_PER_S;+ return Math.min(BUBBLE_MAX_S, Math.max(BUBBLE_MIN_S, raw));+}++// ---------------------------------------------------------------------------+// identity+// ---------------------------------------------------------------------------++/** One conversation per pair, whichever way round the message went. */+export function pairKey(a: string, b: string): string {+ return a < b ? `${a}|${b}` : `${b}|${a}`;+}++/** The key a room's scene is stored under. */+export function roomKey(roomId: string): string {+ return `room:${roomId}`;+}++// ---------------------------------------------------------------------------+// facing+// ---------------------------------------------------------------------------++/**+ * The heading that turns `self` to look straight at `other`.+ *+ * A figure faces +Z in its own space (character-pipeline §4.1), which is why+ * this is `atan2(dx, dz)` and not the usual `atan2(dz, dx)`. Pinned against the+ * real `headingFor` in the test — a figure facing backwards is the single most+ * common way to get this wrong.+ */+export function facingBetween(ax: number, az: number, bx: number, bz: number): number {+ return Math.atan2(bx - ax, bz - az);+}++/**+ * The same-place case: two figures on one stand tile turn along the building's+ * front instead of into each other. `side` is −1 or +1, taken from the sign of+ * their lateral offset, so the pair always turns to face across, never through.+ */+export function tangentFacing(placeFacing: number, side: -1 | 1): number {+ return placeFacing + (side * Math.PI) / 2;+}++// ---------------------------------------------------------------------------+// the arc+// ---------------------------------------------------------------------------++/** Head height in metres, where a call attaches (a figure at WORLD_HERO_SCALE). */+export const HEAD_Y_M = 2.7;++/** How many beads make the signal. */+export const ARC_BEADS = 16;+/** Radius of one bead, in metres. */+export const ARC_BEAD_R_M = 0.16;++/**+ * How high the arc rises over the straight line, in metres.+ *+ * Clamped so it clears the island without a single terrain query: the summit+ * sits at 12.6 m and the town at 1.8 m, so the 22 m ceiling passes over the+ * mountain by a comfortable margin even on the longest call.+ */+export function arcApexFor(distanceM: number): number {+ return Math.min(22, Math.max(5, 3 + 0.16 * distanceM));+}++export interface Vec3 {+ x: number;+ y: number;+ z: number;+}++/** A quadratic arc from `a` to `b`, peaking `apex` metres above the midpoint. */+export function arcPoint(a: Vec3, b: Vec3, t: number, apex: number): Vec3 {+ const u = clamp01(t);+ return {+ x: a.x + (b.x - a.x) * u,+ y: a.y + (b.y - a.y) * u + Math.sin(Math.PI * u) * apex,+ z: a.z + (b.z - a.z) * u,+ };+}++/**+ * How big bead `index` is right now, 0 to 1.+ *+ * Scale, never opacity: `worldMaterials.halo()` caches one material per+ * `colour@opacity` pair, so animating opacity would grow that cache without+ * bound. A travelling head of light plus a short tail, and every bead behind+ * the head sits at a low resting glow so the line reads as a connection rather+ * than a lone dot.+ */+export function beadScale(index: number, count: number, t: number): number {+ if (count <= 1) return t > 0 ? 1 : 0;+ const at = index / (count - 1);+ const head = clamp01(t);+ if (at > head) return 0;+ const behind = head - at;+ const pulse = behind < 0.22 ? 1 - (behind / 0.22) * 0.45 : 0.55;+ // The far end fades in over the last stretch so the signal "lands".+ return pulse * (0.55 + 0.45 * ease(clamp01((head - at) * 6)));+}++/** How far the arc has run off after hang-up, 0 (whole) to 1 (gone). */+export function hangupSweep(local: number): number {+ return ease(clamp01(local / CALL_SECONDS.hangup));+}++/** True while bead `index` still exists during the hang-up sweep. */+export function beadAlive(index: number, count: number, sweep: number): boolean {+ if (count <= 1) return sweep < 1;+ return index / (count - 1) > sweep;+}++// ---------------------------------------------------------------------------+// small curves+// ---------------------------------------------------------------------------++export function clamp01(v: number): number {+ return v < 0 ? 0 : v > 1 ? 1 : v;+}++/** Smoothstep — the house ease for anything that starts and stops. */+export function ease(v: number): number {+ const t = clamp01(v);+ return t * t * (3 - 2 * t);+}++/** A ping ring expanding from a head, 0 to 1 over `dial`. */+export function pingScale(local: number): number {+ return ease(clamp01(local / CALL_SECONDS.dial));+}++/** How bright that ring still is: full at the start, gone at the edge. */+export function pingFade(local: number): number {+ return 1 - clamp01(local / CALL_SECONDS.dial);+}++/** A ground pip breathing under a figure that is in a conversation. */+export function pipScale(t: number): number {+ return 1 + Math.sin(t * 3.1) * 0.09;+}++// ---------------------------------------------------------------------------+// budget+// ---------------------------------------------------------------------------++/** Full choreographies drawn at once; a fifth pair gets the clip and a bubble only. */+export const MAX_CONCURRENT = 3;+/** Conversations kept in the store at all — a runaway backend cannot grow it. */+export const MAX_LIVE_PAIRS = 8;+/** Lines held behind the one on screen; past this they collapse into a digest. */+export const QUEUE_MAX = 3;+/** A walker that has not appeared yet gets this long before we give up on it. */+export const PIN_GRACE_MS = 1_500;+/** A conversation nothing has advanced in this long is closed. */+export const TALK_TIMEOUT_MS = 20_000;+/** A room nobody has spoken in for this long is closed. */+export const ROOM_IDLE_MS = 45_000;+/** Radius of the ring drawn under a room at the Town Hall, in metres. */+export const ROOM_RING_R_M = 4.5;+/** Radius of the pip under a figure in a conversation, in metres. */+export const PIP_R_M = 1.2;++/**+ * The board types the island reacts to. Pinned against the Python+ * `WorldFeed.VISIBLE_TYPES | ROOM_TYPES` by `test_world_feed.py`, so a type+ * added on one side and forgotten on the other fails the build rather than+ * silently going undrawn.+ */+export const WORLD_MSG_TYPES: readonly string[] = [+ "SAY",+ "QUERY",+ "ANSWER",+ "PROPOSE",+ "ROOM_OPEN",+ "ROOM_SETTLE",+];++/** `MsgType` on the wire → the bubble's kind. */+export function kindOf(msgType: string): TalkKind {+ switch (msgType) {+ case "QUERY":+ return "query";+ case "ANSWER":+ return "answer";+ case "PROPOSE":+ return "propose";+ default:+ return "say";+ }+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/conversationStore.test.ts b/jarvis/ui/web/frontend/src/components/society/world/conversationStore.test.tsnew file mode 100644index 0000000000..4e5b05306f--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/conversationStore.test.ts@@ -0,0 +1,252 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { QUEUE_MAX, ROOM_IDLE_MS, TALK_TIMEOUT_MS, pairKey, roomKey } from "./conversation";+import {+ clearSpeechPoses,+ lineLifeMs,+ orderedTalks,+ setSpeechPose,+ speechPose,+ useConversationStore,+ type IncomingMessage,+ type IncomingRoom,+} from "./conversationStore";++const KNOWN = new Set(["scout", "archivist", "runner"]);++let nextSeq = 1;++function message(over: Partial<IncomingMessage> = {}): IncomingMessage {+ const seq = over.seq ?? nextSeq++;+ const base: IncomingMessage = {+ eventId: `evt-${seq}`,+ seq,+ msgType: "SAY",+ fromAgent: "scout",+ toAgent: "archivist",+ roomId: "",+ roomRound: 0,+ text: "Found the manifest.",+ textChars: 19,+ truncated: false,+ };+ return { ...base, ...over, seq };+}++function room(over: Partial<IncomingRoom> = {}): IncomingRoom {+ return {+ roomId: "r1",+ phase: "open",+ members: ["scout", "archivist"],+ topic: "Plan the week",+ reason: "",+ maxRounds: 3,+ ...over,+ };+}++function send(m: IncomingMessage): void {+ useConversationStore.getState().noteMessage(m, KNOWN);+}++beforeEach(() => {+ vi.useFakeTimers();+ nextSeq = 1;+ useConversationStore.setState({ talks: {}, room: null, lastSeq: 0 });+ clearSpeechPoses();+});++afterEach(() => {+ useConversationStore.getState().reset();+ vi.useRealTimers();+});++describe("one conversation per pair", () => {+ it("opens a conversation on the first line", () => {+ send(message());+ const talks = useConversationStore.getState().talks;+ const key = pairKey("scout", "archivist");+ expect(Object.keys(talks)).toEqual([key]);+ expect(talks[key].speakerId).toBe("scout");+ expect(talks[key].partnerId).toBe("archivist");+ expect(talks[key].line?.text).toBe("Found the manifest.");+ expect(talks[key].kind).toBeNull(); // the scene decides from the live distance+ });++ it("lands a reply on the SAME conversation instead of opening a second", () => {+ send(message());+ send(message({ fromAgent: "archivist", toAgent: "scout", msgType: "ANSWER" }));++ const talks = useConversationStore.getState().talks;+ expect(Object.keys(talks)).toHaveLength(1);+ const talk = talks[pairKey("scout", "archivist")];+ expect(talk.queued).toHaveLength(1);+ expect(talk.queued[0].speakerId).toBe("archivist");+ expect(talk.queued[0].kind).toBe("answer");+ });++ it("swaps the speaker when the queue is promoted", () => {+ send(message());+ send(message({ fromAgent: "archivist", toAgent: "scout", msgType: "ANSWER" }));+ const key = pairKey("scout", "archivist");++ useConversationStore.getState().advance(key);+ const talk = useConversationStore.getState().talks[key];+ expect(talk.speakerId).toBe("archivist");+ expect(talk.queued).toHaveLength(0);+ });++ it("empties the bubble when nothing is queued, and keeps the conversation", () => {+ send(message());+ const key = pairKey("scout", "archivist");+ useConversationStore.getState().advance(key);+ expect(useConversationStore.getState().talks[key].line).toBeNull();+ });+});++describe("a burst", () => {+ it("queues up to the cap and digests the rest", () => {+ for (let i = 0; i < QUEUE_MAX + 4; i++) send(message({ text: `line ${i}` }));++ const talk = useConversationStore.getState().talks[pairKey("scout", "archivist")];+ expect(talk.queued).toHaveLength(QUEUE_MAX);+ expect(talk.skipped).toBe(3); // one on screen + QUEUE_MAX queued + 3 collapsed+ });++ it("drops a frame it has already drawn", () => {+ send(message({ seq: 7 }));+ send(message({ seq: 7, text: "same row again" }));+ const talk = useConversationStore.getState().talks[pairKey("scout", "archivist")];+ expect(talk.queued).toHaveLength(0);+ expect(talk.line?.text).toBe("Found the manifest.");+ });++ it("drops a frame older than the highest it has seen", () => {+ send(message({ seq: 20 }));+ send(message({ seq: 3, text: "a straggler" }));+ const talk = useConversationStore.getState().talks[pairKey("scout", "archivist")];+ expect(talk.queued).toHaveLength(0);+ });+});++describe("who is on the island", () => {+ it("shows a one-sided conversation when the partner has no figure", () => {+ send(message({ toAgent: "user" }));+ const talk = useConversationStore.getState().talks[pairKey("scout", "user")];+ expect(talk).toBeDefined();+ expect(talk.partnerId).toBe("");+ expect(talk.speakerId).toBe("scout");+ });++ it("keeps the receiver's side when the SENDER is off-island", () => {+ send(message({ fromAgent: "scheduler", toAgent: "scout" }));+ const talk = useConversationStore.getState().talks[pairKey("scheduler", "scout")];+ expect(talk).toBeDefined();+ expect(talk.partnerId).toBe("scout");+ });++ it("draws nothing at all when neither side has a figure", () => {+ send(message({ fromAgent: "scheduler", toAgent: "user" }));+ expect(useConversationStore.getState().talks).toEqual({});+ // …but the sequence still advances, so the frame is not replayed.+ expect(useConversationStore.getState().lastSeq).toBeGreaterThan(0);+ });+});++describe("the watchdogs", () => {+ it("closes a conversation nothing has advanced", () => {+ send(message());+ const key = pairKey("scout", "archivist");+ expect(useConversationStore.getState().talks[key]).toBeDefined();++ vi.advanceTimersByTime(TALK_TIMEOUT_MS + 10);+ expect(useConversationStore.getState().talks[key]).toBeUndefined();+ });++ it("frees the figures it was driving when it closes", () => {+ send(message());+ setSpeechPose("scout", { heading: 1, talking: true });+ setSpeechPose("archivist", { heading: 2, talking: false });++ vi.advanceTimersByTime(TALK_TIMEOUT_MS + 10);+ expect(speechPose("scout")).toBeNull();+ expect(speechPose("archivist")).toBeNull();+ });++ it("closes a room nobody has spoken in", () => {+ useConversationStore.getState().noteRoom(room());+ expect(useConversationStore.getState().room?.roomId).toBe("r1");++ vi.advanceTimersByTime(ROOM_IDLE_MS + 10);+ expect(useConversationStore.getState().room).toBeNull();+ });+});++describe("a room", () => {+ it("opens, counts its rounds and settles with a reason", () => {+ const store = useConversationStore.getState();+ store.noteRoom(room());+ expect(useConversationStore.getState().room?.topic).toBe("Plan the week");+ expect(useConversationStore.getState().room?.maxRounds).toBe(3);++ send(message({ toAgent: "", roomId: "r1", roomRound: 2, text: "I will take the mail." }));+ expect(useConversationStore.getState().room?.round).toBe(2);+ expect(useConversationStore.getState().talks[roomKey("r1")]).toBeDefined();++ store.noteRoom(room({ phase: "settle", reason: "round_cap" }));+ expect(useConversationStore.getState().room?.settled).toBe(true);+ expect(useConversationStore.getState().room?.reason).toBe("round_cap");+ });++ it("ignores a settle for a room it is not showing", () => {+ const store = useConversationStore.getState();+ store.noteRoom(room());+ store.noteRoom(room({ roomId: "other", phase: "settle", reason: "silence" }));+ expect(useConversationStore.getState().room?.settled).toBe(false);+ });+});++describe("the helpers the scene reads", () => {+ it("orders conversations oldest first, so the oldest wins a heading", () => {+ send(message());+ vi.advanceTimersByTime(50);+ send(message({ fromAgent: "runner", toAgent: "scout" }));++ const ordered = orderedTalks(useConversationStore.getState().talks);+ expect(ordered).toHaveLength(2);+ expect(ordered[0].startedMs).toBeLessThanOrEqual(ordered[1].startedMs);+ });++ it("gives a line a life proportional to its length", () => {+ send(message({ text: "hi", textChars: 2 }));+ const short = lineLifeMs(useConversationStore.getState().talks[pairKey("scout", "archivist")]);+ useConversationStore.getState().reset();+ send(message({ text: "x".repeat(180), textChars: 180 }));+ const long = lineLifeMs(useConversationStore.getState().talks[pairKey("scout", "archivist")]);+ expect(long).toBeGreaterThan(short);+ });++ it("reports no life for a conversation whose bubble has gone", () => {+ send(message());+ const key = pairKey("scout", "archivist");+ useConversationStore.getState().advance(key);+ expect(lineLifeMs(useConversationStore.getState().talks[key])).toBe(0);+ });+});++describe("reset", () => {+ it("forgets every conversation, pose and timer", () => {+ send(message());+ useConversationStore.getState().noteRoom(room());+ setSpeechPose("scout", { heading: 0, talking: true });++ useConversationStore.getState().reset();+ expect(useConversationStore.getState().talks).toEqual({});+ expect(useConversationStore.getState().room).toBeNull();+ expect(speechPose("scout")).toBeNull();++ // A watchdog that survived reset would fire into an empty store.+ expect(() => vi.advanceTimersByTime(ROOM_IDLE_MS * 2)).not.toThrow();+ expect(useConversationStore.getState().room).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/world/conversationStore.ts b/jarvis/ui/web/frontend/src/components/society/world/conversationStore.tsnew file mode 100644index 0000000000..41b04b1d10--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/conversationStore.ts@@ -0,0 +1,354 @@+/**+ * Which agents are talking right now, and what that asks of their figures —+ * the state half of `conversation.ts`.+ *+ * Two channels, on purpose, exactly like `retireStore.ts`:+ *+ * - the zustand store carries the conversations themselves (who, which line,+ * which beat). One changes a few times over a handful of seconds, so a+ * React render per change costs nothing and the bubbles — which are DOM —+ * can read it;+ * - the pose map is a plain mutable `Map`, written and read inside+ * `useFrame`, exactly like `walkerRegistry.ts`. A walker in a conversation+ * reads its pose every frame; re-rendering React at 60 fps to turn a head+ * would be absurd.+ *+ * The pose is deliberately weaker than the retirement ceremony's+ * `WalkerOverride`: it has no position, no pitch, no hidden flag. A+ * conversation may turn a head and open a mouth and nothing else+ * (world-behaviour-manual §1), so the two systems have no territory to fight+ * over — the ceremony owns where a figure is, speech owns where it looks.+ *+ * Every watchdog lives here rather than in the scene: a conversation no stage+ * ever picks up (the viewer is on the ledger, the canvas never mounted, WebGL+ * is gone) must still expire instead of sitting in the store forever.+ */+import { create } from "zustand";++import {+ MAX_LIVE_PAIRS,+ QUEUE_MAX,+ ROOM_IDLE_MS,+ TALK_TIMEOUT_MS,+ bubbleSeconds,+ kindOf,+ pairKey,+ roomKey,+ type ConvoKind,+ type TalkKind,+} from "./conversation";++/** One line somebody said, as the island needs it. */+export interface TalkLine {+ /** The board envelope's id — the dedupe key and the deep link. */+ id: string;+ seq: number;+ speakerId: string;+ text: string;+ kind: TalkKind;+ /** Characters in the original, so the bubble can say there is more. */+ chars: number;+ truncated: boolean;+ ms: number;+}++/** A conversation between two figures, or one figure and somebody off-island. */+export interface Conversation {+ key: string;+ /** The two participants; `partnerId` is "" when the other side has no figure. */+ speakerId: string;+ partnerId: string;+ /** "" unless the line was spoken into a room. */+ roomId: string;+ /** Decided once from the distance at ingest, never re-decided mid-sentence. */+ kind: ConvoKind | null;+ line: TalkLine | null;+ queued: TalkLine[];+ /** Lines that overflowed the queue; the bubble shows "+N" for them. */+ skipped: number;+ startedMs: number;+ lineStartedMs: number;+ /** True while the scene draws the badges/arc; a 4th conversation runs plain. */+ degraded: boolean;+}++/** A bounded room in session at the Town Hall. */+export interface RoomScene {+ roomId: string;+ members: string[];+ topic: string;+ round: number;+ maxRounds: number;+ settled: boolean;+ reason: string;+ startedMs: number;+ touchedMs: number;+}++/** What a conversation asks of a walker. It can never move one. */+export interface SpeechPose {+ /** Heading to turn toward, or null for "keep your own". */+ heading: number | null;+ /** Play the `talk` clip this frame. */+ talking: boolean;+}++/** What arrives from the WebSocket, already narrowed. */+export interface IncomingMessage {+ eventId: string;+ seq: number;+ msgType: string;+ fromAgent: string;+ toAgent: string;+ roomId: string;+ roomRound: number;+ text: string;+ textChars: number;+ truncated: boolean;+}++export interface IncomingRoom {+ roomId: string;+ phase: string;+ members: string[];+ topic: string;+ reason: string;+ maxRounds: number;+}++interface ConvoState {+ talks: Record<string, Conversation>;+ room: RoomScene | null;+ /** Highest board sequence already ingested; anything older is a replay. */+ lastSeq: number;+}++interface ConvoActions {+ noteMessage: (m: IncomingMessage, known: ReadonlySet<string>) => void;+ noteRoom: (r: IncomingRoom) => void;+ /** The line on screen finished: promote the queue, or close the conversation. */+ advance: (key: string) => void;+ closeTalk: (key: string) => void;+ closeRoom: () => void;+ /** Reduced motion, a lost canvas, a section change: forget everything. */+ reset: () => void;+}++/** Per-frame poses, keyed by agent id. Mutable on purpose; see the docstring. */+const poses = new Map<string, SpeechPose>();++/** Watchdogs, one per live key, cleared whenever the key goes. */+const timers = new Map<string, ReturnType<typeof setTimeout>>();++function arm(key: string, ms: number, run: () => void): void {+ disarm(key);+ timers.set(+ key,+ setTimeout(() => {+ timers.delete(key);+ run();+ }, ms),+ );+}++function disarm(key: string): void {+ const handle = timers.get(key);+ if (handle !== undefined) {+ clearTimeout(handle);+ timers.delete(key);+ }+}++function lineFrom(m: IncomingMessage, now: number): TalkLine {+ return {+ id: m.eventId,+ seq: m.seq,+ speakerId: m.fromAgent,+ text: m.text,+ kind: kindOf(m.msgType),+ chars: m.textChars || m.text.length,+ truncated: m.truncated,+ ms: now,+ };+}++export const useConversationStore = create<ConvoState & ConvoActions>((set, get) => ({+ talks: {},+ room: null,+ lastSeq: 0,++ noteMessage: (m, known) => {+ const state = get();+ // A replayed or duplicated frame changes nothing. `seq` is the board's own+ // monotone row number, which is exactly why it rides on the event.+ if (m.seq > 0 && m.seq <= state.lastSeq) return;++ const speakerKnown = known.has(m.fromAgent);+ const partnerKnown = m.toAgent !== "" && known.has(m.toAgent);+ // Nobody on the island said this and nobody on the island heard it — the+ // board's own plumbing talking to itself. There is nothing to draw.+ if (!speakerKnown && !partnerKnown) {+ if (m.seq > 0) set({ lastSeq: m.seq });+ return;+ }++ const now = Date.now();+ const line = lineFrom(m, now);+ const key = m.roomId ? roomKey(m.roomId) : pairKey(m.fromAgent, m.toAgent || m.fromAgent);+ const talks = { ...state.talks };+ const live = talks[key];++ if (live) {+ // A reply does not restart the conversation: it swaps the roles and the+ // two keep standing there. Four disconnected pops would read as noise.+ if (live.line === null) {+ talks[key] = { ...live, line, lineStartedMs: now, speakerId: line.speakerId };+ } else if (live.queued.length < QUEUE_MAX) {+ talks[key] = { ...live, queued: [...live.queued, line] };+ } else {+ talks[key] = { ...live, skipped: live.skipped + 1 };+ }+ } else {+ const partnerId = partnerKnown ? m.toAgent : "";+ const fresh: Conversation = {+ key,+ speakerId: m.fromAgent,+ partnerId,+ roomId: m.roomId,+ kind: null, // the scene decides from the live distance, once+ line,+ queued: [],+ skipped: 0,+ startedMs: now,+ lineStartedMs: now,+ degraded: false,+ };+ talks[key] = fresh;+ // Oldest out first when the board floods: the island is not a transcript.+ const keys = Object.keys(talks);+ if (keys.length > MAX_LIVE_PAIRS) {+ keys+ .sort((a, b) => talks[a].startedMs - talks[b].startedMs)+ .slice(0, keys.length - MAX_LIVE_PAIRS)+ .forEach((old) => {+ disarm(old);+ poses.delete(talks[old].speakerId);+ if (talks[old].partnerId) poses.delete(talks[old].partnerId);+ delete talks[old];+ });+ }+ }++ arm(key, TALK_TIMEOUT_MS, () => get().closeTalk(key));+ set({ talks, lastSeq: m.seq > 0 ? m.seq : state.lastSeq });++ if (m.roomId && get().room?.roomId === m.roomId) {+ const room = get().room;+ if (room) set({ room: { ...room, round: m.roomRound || room.round, touchedMs: now } });+ }+ },++ noteRoom: (r) => {+ const now = Date.now();+ if (r.phase === "open") {+ arm("room", ROOM_IDLE_MS, () => get().closeRoom());+ set({+ room: {+ roomId: r.roomId,+ members: r.members,+ topic: r.topic,+ round: 1,+ maxRounds: r.maxRounds || 3,+ settled: false,+ reason: "",+ startedMs: now,+ touchedMs: now,+ },+ });+ return;+ }+ const room = get().room;+ if (!room || room.roomId !== r.roomId) return;+ disarm("room");+ set({ room: { ...room, settled: true, reason: r.reason, touchedMs: now } });+ },++ advance: (key) => {+ const talks = { ...get().talks };+ const live = talks[key];+ if (!live) return;+ const [next, ...rest] = live.queued;+ if (next) {+ talks[key] = {+ ...live,+ line: next,+ queued: rest,+ speakerId: next.speakerId,+ lineStartedMs: Date.now(),+ };+ arm(key, TALK_TIMEOUT_MS, () => get().closeTalk(key));+ set({ talks });+ return;+ }+ talks[key] = { ...live, line: null };+ set({ talks });+ },++ closeTalk: (key) => {+ disarm(key);+ const talks = { ...get().talks };+ const live = talks[key];+ if (!live) return;+ poses.delete(live.speakerId);+ if (live.partnerId) poses.delete(live.partnerId);+ delete talks[key];+ set({ talks });+ },++ closeRoom: () => {+ disarm("room");+ const room = get().room;+ if (room) for (const id of room.members) poses.delete(id);+ set({ room: null });+ },++ reset: () => {+ for (const key of [...timers.keys()]) disarm(key);+ poses.clear();+ set({ talks: {}, room: null });+ },+}));++// --------------------------------------------------------------- the poses++/** The pose a conversation wants this walker in, or null when it is free. */+export function speechPose(agentId: string): SpeechPose | null {+ return poses.get(agentId) ?? null;+}++/** Written by the scene each frame for the figures it drives. */+export function setSpeechPose(agentId: string, pose: SpeechPose): void {+ poses.set(agentId, pose);+}++/** Hand one figure back to its own sim. */+export function clearSpeechPose(agentId: string): void {+ poses.delete(agentId);+}++/** Scene unmount, a lost WebGL context, reduced motion: everybody is free. */+export function clearSpeechPoses(): void {+ poses.clear();+}++// ------------------------------------------------------------- convenience++/** How long the line currently on `talk` should stay up, in ms. */+export function lineLifeMs(talk: Conversation): number {+ return talk.line ? bubbleSeconds(talk.line.chars) * 1000 : 0;+}++/** Live conversations, oldest first — the order that decides who wins a heading. */+export function orderedTalks(talks: Record<string, Conversation>): Conversation[] {+ return Object.values(talks).sort((a, b) => a.startedMs - b.startedMs);+}diff --git a/jarvis/ui/web/frontend/src/components/society/world/useConversationFeed.ts b/jarvis/ui/web/frontend/src/components/society/world/useConversationFeed.tsnew file mode 100644index 0000000000..b80ae495cf--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/world/useConversationFeed.ts@@ -0,0 +1,121 @@+/**+ * The island's ear: `SocietyMessageSent` and `SocietyRoomChanged` off the+ * app-wide WebSocket, into the conversation store.+ *+ * Modelled on `questsData.ts`, with one difference that matters. That hook+ * peeks at `events[0]` and invalidates a query — losing the middle of a burst+ * costs nothing there, because the refetch sees the final state anyway. Here a+ * lost message is a lost sentence, so this DRAINS: it keeps a cursor on the+ * last id it handled and replays everything above it, oldest first.+ *+ * Nothing is fetched and nothing is polled. When the island is not drawing —+ * reduced motion, no WebGL, another section — the subscription is dropped and+ * the store is emptied, so an idle society costs exactly nothing (MASTERPLAN+ * §2.8).+ */+import { useEffect } from "react";++import { useEventStore } from "@/store/events";+import type { SocietyAgent } from "../data";+import {+ useConversationStore,+ type IncomingMessage,+ type IncomingRoom,+} from "./conversationStore";++const MESSAGE_EVENT = "SocietyMessageSent";+const ROOM_EVENT = "SocietyRoomChanged";++/**+ * How far back to walk when the cursor is not in the log any more. The store+ * keeps 500 events and a conversation is seconds old, so a cursor that fell+ * off the end means we were away — replaying hundreds of stale lines would+ * bubble a conversation that finished minutes ago.+ */+const MAX_CATCHUP = 64;++function asMessage(payload: unknown): IncomingMessage | null {+ if (!payload || typeof payload !== "object") return null;+ const p = payload as Record<string, unknown>;+ const from = typeof p.from_agent === "string" ? p.from_agent : "";+ if (!from) return null;+ return {+ eventId: typeof p.event_id === "string" ? p.event_id : "",+ seq: typeof p.seq === "number" ? p.seq : 0,+ msgType: typeof p.msg_type === "string" ? p.msg_type : "SAY",+ fromAgent: from,+ toAgent: typeof p.to_agent === "string" ? p.to_agent : "",+ roomId: typeof p.room_id === "string" ? p.room_id : "",+ roomRound: typeof p.room_round === "number" ? p.room_round : 0,+ text: typeof p.text === "string" ? p.text : "",+ textChars: typeof p.text_chars === "number" ? p.text_chars : 0,+ truncated: p.truncated === true,+ };+}++function asRoom(payload: unknown): IncomingRoom | null {+ if (!payload || typeof payload !== "object") return null;+ const p = payload as Record<string, unknown>;+ const roomId = typeof p.room_id === "string" ? p.room_id : "";+ if (!roomId) return null;+ return {+ roomId,+ phase: typeof p.phase === "string" ? p.phase : "",+ members: Array.isArray(p.members) ? p.members.map(String) : [],+ topic: typeof p.topic === "string" ? p.topic : "",+ reason: typeof p.reason === "string" ? p.reason : "",+ maxRounds: typeof p.max_rounds === "number" ? p.max_rounds : 0,+ };+}++/**+ * Subscribe the conversation store to the live board while `enabled`.+ *+ * `agents` is the roster the island is drawing: an id that is not in it has no+ * figure, so a message from the scheduler or to an archived row is either+ * one-sided or dropped rather than drawn as a beam into empty water.+ */+export function useConversationFeed(agents: SocietyAgent[], enabled: boolean): void {+ // The set is rebuilt whenever the roster identity changes; the roster query+ // hands back the same array between refetches, so this is not per-render.+ const ids = agents.map((a) => a.agentId).join(",");++ useEffect(() => {+ const store = useConversationStore.getState();+ if (!enabled) {+ store.reset();+ return;+ }+ const known = new Set(ids ? ids.split(",") : []);+ let cursor: string | null = useEventStore.getState().events[0]?.id ?? null;++ return useEventStore.subscribe((state) => {+ const log = state.events;+ const top = log[0];+ if (!top || top.id === cursor) return;++ // The log is newest-first: collect everything above the cursor, then+ // replay it in the order it happened.+ const fresh = [];+ for (let i = 0; i < log.length && i < MAX_CATCHUP; i++) {+ if (log[i].id === cursor) break;+ fresh.push(log[i]);+ }+ cursor = top.id;++ const convo = useConversationStore.getState();+ for (let i = fresh.length - 1; i >= 0; i--) {+ const item = fresh[i];+ if (item.name === MESSAGE_EVENT) {+ const message = asMessage(item.payload);+ if (message) convo.noteMessage(message, known);+ } else if (item.name === ROOM_EVENT) {+ const room = asRoom(item.payload);+ if (room) convo.noteRoom(room);+ }+ }+ });+ }, [enabled, ids]);++ useEffect(() => () => useConversationStore.getState().reset(), []);+}