Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(c): bot typing indicator with daemon-metered heartbeat
Gus5198b2975429
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.tsindex ecaa9a14c..e0e8c488e 100644--- a/src/daemon/src/daemon/createDaemon.ts+++ b/src/daemon/src/daemon/createDaemon.ts@@ -24,7 +24,8 @@import { homedir } from "os";import { WsControlChannel } from "../server/wsControlChannel.js";import { CredentialBroker, startCredentialProxy } from "../credentials/index.js";-import { AgentProcessManager, AgentRouter } from "../manager/index.js";+import { AgentProcessManager, AgentRouter, createTypingScopeTracker } from "../manager/index.js";+import type { TypingScopeTracker } from "../manager/index.js";import { UnknownBotError, BotEnrollFailedError, UnknownRuntimeError } from "../manager/agentRouter.js";import { createTimelineRecorder } from "../timeline/index.js";import { resolveAlookCliPathWithFallback } from "../discovery.js";@@ -187,6 +188,53 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa// Per-agent enrolled runner keys (enrollment is async; stored before deliver).const enrolledKeys = new Map<string, string>();+ // ── Bot typing indicator (DM-only) ─────────────────────────────────────+ //+ // Shared in-memory tracker of per-agent DM conversation ids the daemon+ // should be broadcasting "bot is typing…" for. Populated by the+ // AgentRouter on each `agent:wake` (from `unreadNotice.dmConversationId`)+ // and cleared on FSM transitions into `idle`/`stopping`.+ const typingTracker: TypingScopeTracker = createTypingScopeTracker();+ // Per-agent heartbeat interval handles. Only alive while an agent is in+ // a running-family state; recreated on each starting/running transition.+ const typingHeartbeats = new Map<string, ReturnType<typeof setInterval>>();+ const TYPING_HEARTBEAT_MS = 5_000;+ function stopTypingHeartbeat(agentId: string): void {+ const timer = typingHeartbeats.get(agentId);+ if (timer) {+ clearInterval(timer);+ typingHeartbeats.delete(agentId);+ }+ }+ function startTypingHeartbeat(agentId: string): void {+ stopTypingHeartbeat(agentId);+ // Immediate emit + every 5s while active — comfortably refreshes the+ // client's 8s expiry, and bypasses the ws-do 8s dedup gate (which only+ // guards the client-inbound `community:typing.start` path — daemon+ // metered heartbeats reach clients unconditionally).+ for (const dmConversationId of typingTracker.snapshot(agentId)) {+ channel.reportAgentTyping?.({ agentId, dmConversationId });+ }+ const timer = setInterval(() => {+ for (const dmConversationId of typingTracker.snapshot(agentId)) {+ channel.reportAgentTyping?.({ agentId, dmConversationId });+ }+ }, TYPING_HEARTBEAT_MS);+ timer.unref?.();+ typingHeartbeats.set(agentId, timer);+ }+ function emitTypingStopsAndClear(agentId: string): void {+ // Order: emit stops FIRST, then clear tracker. If two transitions fire+ // (running→stopping→idle), the second sees an empty tracker and+ // per-scope loop no-ops — matches the "emit-then-clear" rule in the+ // plan's race-handling section.+ stopTypingHeartbeat(agentId);+ for (const dmConversationId of typingTracker.snapshot(agentId)) {+ channel.reportAgentTypingStop?.({ agentId, dmConversationId });+ }+ typingTracker.clear(agentId);+ }+// ── Bot cache ──────────────────────────────────────────────────────────//// `botsById` holds the minimum info the daemon needs to assemble system@@ -427,7 +475,25 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa},tickIntervalMs: opts.tickIntervalMs ?? 2000,onAgentSession: (info) => void channel.reportAgentSession(info),- onAgentActivity: (info) => void channel.reportAgentActivity?.(info),+ onAgentActivity: (info) => {+ void channel.reportAgentActivity?.(info);+ // Bot typing indicator (DM-only) — install / tear down the daemon-metered+ // heartbeat off the derived FSM activity, so the pill lifecycle exactly+ // mirrors "is this bot actively working."+ //+ // `onAgentActivity` fires on every derived-activity change, so a natural+ // `idle → starting → running` sequence emits BOTH starting and running.+ // The `typingHeartbeats.has(agentId)` guard makes install idempotent —+ // subsequent starting/running transitions are no-ops instead of+ // restarting the interval + firing a duplicate immediate frame.+ if (info.state === "starting" || info.state === "running") {+ if (!typingHeartbeats.has(info.agentId)) {+ startTypingHeartbeat(info.agentId);+ }+ } else {+ emitTypingStopsAndClear(info.agentId);+ }+ },// Bot audit log — Producer A (runtime thinking + non-Bash tool_call).// Bash suppression + thinking truncation happen inside managerRuntime.onBotAuditEvent: (agentId, event, context) => emitBotAuditEvent(agentId, event, context),@@ -455,6 +521,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDaarch: opts.arch,osRelease: opts.osRelease,daemonVersion: opts.daemonVersion,+ typingTracker,logger: log.child("router"),// onBeforeAgent gate — reject unknown bots BEFORE enroll to keep the// failure code stable (`bot_unknown` vs `bot_enroll_failed`).@@ -509,6 +576,11 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDaisOpen: () => channel.status === "open",proxyUrl: proxy.url,stop: async () => {+ // Clear all bot-typing heartbeat intervals and emit final stops for+ // any outstanding scopes so no pill is left dangling.+ for (const agentId of [...typingHeartbeats.keys()]) {+ emitTypingStopsAndClear(agentId);+ }channel.close();await proxy.close();await manager.stopAll();diff --git a/src/daemon/src/manager/agentRouter.test.ts b/src/daemon/src/manager/agentRouter.test.tsindex bfcc08749..ad42987ed 100644--- a/src/daemon/src/manager/agentRouter.test.ts+++ b/src/daemon/src/manager/agentRouter.test.ts@@ -24,9 +24,10 @@ function stubLogger(): Logger & { calls: Record<"debug" | "info" | "warn" | "err}/** Fake manager recording deliver/register; enough for router behavior tests. */-function fakeManager() {+function fakeManager(initialStatuses: Record<string, "idle" | "starting" | "running" | "stopping"> = {}) {const delivers: Array<{ agentId: string; text: string; seq?: number }> = [];const registers: Array<{ agentId: string; sessionId?: string; launchId?: string }> = [];+ const statuses: Record<string, "idle" | "starting" | "running" | "stopping"> = { ...initialStatuses };const mgr = {register(agentId: string, launch?: { sessionId?: string; launchId?: string }) {registers.push({ agentId, sessionId: launch?.sessionId, launchId: launch?.launchId });@@ -36,8 +37,13 @@ function fakeManager() {},stop() {},liveSessionReports: () => [],+ snapshot() {+ const agents: Record<string, { status: string }> = {};+ for (const [id, status] of Object.entries(statuses)) agents[id] = { status };+ return { agents };+ },} as unknown as AgentProcessManager;- return { mgr, delivers, registers };+ return { mgr, delivers, registers, statuses };}/** Fake channel capturing acks + the command handler the router registers. */@@ -46,6 +52,7 @@ function fakeChannel() {const wakeAcks: Array<{ agentId: string; launchId: string; status: string }> = [];const readys: Array<Parameters<HostControlChannel["reportReady"]>[0]> = [];const sessionErrors: SessionErrorFrame[] = [];+ const typings: Array<{ agentId: string; dmConversationId: string }> = [];const ch: HostControlChannel = {onCommand(cb) {handler = cb;@@ -60,9 +67,12 @@ function fakeChannel() {async reportSessionError(frame) {sessionErrors.push(frame);},+ reportAgentTyping(info) {+ typings.push(info);+ },onResync() {},};- return { ch, wakeAcks, readys, sessionErrors, fire: (c: HostCommand) => handler?.(c) };+ return { ch, wakeAcks, readys, sessionErrors, typings, fire: (c: HostCommand) => handler?.(c) };}describe("AgentRouter — agent:wake", () => {@@ -426,3 +436,135 @@ describe("AgentRouter — logging", () => {expect(logger.calls.info.filter(([m]) => m === "runtime marked healthy again")).toHaveLength(1);});});++describe("AgentRouter — bot typing indicator", () => {+ function makeTracker() {+ const scopes = new Map<string, Set<string>>();+ return {+ add(agentId: string, dm: string) {+ let s = scopes.get(agentId);+ if (!s) { s = new Set(); scopes.set(agentId, s); }+ s.add(dm);+ },+ snapshot(agentId: string) {+ return [...(scopes.get(agentId) ?? [])];+ },+ hasAny(agentId: string) {+ return (scopes.get(agentId)?.size ?? 0) > 0;+ },+ clear(agentId: string) {+ scopes.delete(agentId);+ },+ };+ }++ it("first wake (unregistered → running): router does NOT emit typing (FSM owns first frame)", async () => {+ const { mgr } = fakeManager();+ const { ch, typings, fire } = fakeChannel();+ const tracker = makeTracker();+ const router = new AgentRouter({+ manager: mgr,+ channel: ch,+ runtimeReport: [{ id: "mock" }],+ typingTracker: tracker,+ });+ await router.start();+ await fire({+ type: "agent:wake",+ agentId: "bot_1",+ config: { version: 1, runtime: "mock", model: { kind: "default" }, mode: { kind: "default" } },+ launchId: "l1",+ unreadNotice: {+ kind: "unread_notice",+ channel: "/.dm/peer#0042",+ latestSeq: 1,+ dmConversationId: "dm_1",+ },+ });+ expect(typings).toEqual([]);+ expect(tracker.snapshot("bot_1")).toEqual(["dm_1"]);+ });++ it("mid-turn wake (beforeStatus=running AND wasActive=true): router emits ONCE for the newly-added scope", async () => {+ const { mgr, statuses } = fakeManager({ bot_1: "running" });+ const { ch, typings, fire } = fakeChannel();+ const tracker = makeTracker();+ tracker.add("bot_1", "dm_1"); // wasActive=true — bot already handling dm_1+ const router = new AgentRouter({+ manager: mgr,+ channel: ch,+ runtimeReport: [{ id: "mock" }],+ typingTracker: tracker,+ });+ await router.start();+ // Sanity: statuses map preserved after start+ expect(statuses.bot_1).toBe("running");+ await fire({+ type: "agent:wake",+ agentId: "bot_1",+ config: { version: 1, runtime: "mock", model: { kind: "default" }, mode: { kind: "default" } },+ launchId: "l2",+ unreadNotice: {+ kind: "unread_notice",+ channel: "/.dm/peer2#0042",+ latestSeq: 3,+ dmConversationId: "dm_2",+ },+ });+ expect(typings).toEqual([{ agentId: "bot_1", dmConversationId: "dm_2" }]);+ });++ it("wake during stopping (beforeStatus=stopping): router does NOT emit — FSM will fire stopping→running", async () => {+ const { mgr } = fakeManager({ bot_1: "stopping" });+ const { ch, typings, fire } = fakeChannel();+ const tracker = makeTracker();+ tracker.add("bot_1", "dm_prev"); // wasActive=true (stale from prior turn)+ const router = new AgentRouter({+ manager: mgr,+ channel: ch,+ runtimeReport: [{ id: "mock" }],+ typingTracker: tracker,+ });+ await router.start();+ await fire({+ type: "agent:wake",+ agentId: "bot_1",+ config: { version: 1, runtime: "mock", model: { kind: "default" }, mode: { kind: "default" } },+ launchId: "l3",+ unreadNotice: {+ kind: "unread_notice",+ channel: "/.dm/peer#0042",+ latestSeq: 4,+ dmConversationId: "dm_1",+ },+ });+ expect(typings).toEqual([]);+ });++ it("wake without dmConversationId (channel/thread scope): tracker untouched, no typing frame", async () => {+ const { mgr } = fakeManager();+ const { ch, typings, fire } = fakeChannel();+ const tracker = makeTracker();+ const router = new AgentRouter({+ manager: mgr,+ channel: ch,+ runtimeReport: [{ id: "mock" }],+ typingTracker: tracker,+ });+ await router.start();+ await fire({+ type: "agent:wake",+ agentId: "bot_1",+ config: { version: 1, runtime: "mock", model: { kind: "default" }, mode: { kind: "default" } },+ launchId: "l4",+ unreadNotice: {+ kind: "unread_notice",+ channel: "/srv_1/general",+ latestSeq: 5,+ },+ });+ expect(typings).toEqual([]);+ expect(tracker.snapshot("bot_1")).toEqual([]);+ expect(tracker.hasAny("bot_1")).toBe(false);+ });+});diff --git a/src/daemon/src/manager/agentRouter.ts b/src/daemon/src/manager/agentRouter.tsindex 04b093dbb..0b8540504 100644--- a/src/daemon/src/manager/agentRouter.ts+++ b/src/daemon/src/manager/agentRouter.ts@@ -20,6 +20,7 @@*/import type { HostCommand, HostControlChannel, HostReady, HostReadyRuntime, UnreadNotice, AgentSessionReport, SessionErrorFrame } from "../server/contract.js";import type { AgentProcessManager } from "./managerRuntime.js";+import type { TypingScopeTracker } from "./typingScopeTracker.js";import { createLogger, type Logger } from "../logger.js";/**@@ -99,6 +100,13 @@ export interface AgentRouterOpts {* into one wire frame. Tests inject a synchronous scheduler.*/scheduleReadyResend?: (fn: () => void) => void;+ /**+ * Shared in-memory tracker of per-agent DM typing scopes. Populated here+ * on `agent:wake` (when `unreadNotice.dmConversationId` is set); read by+ * the daemon's heartbeat manager. Optional so tests / non-community daemon+ * builds can construct AgentRouter without one.+ */+ typingTracker?: TypingScopeTracker;/** Defaults to `createLogger({ header: "@alook/daemon:router" })`. */logger?: Logger;}@@ -270,6 +278,18 @@ export class AgentRouter {latestSeq: cmd.unreadNotice.latestSeq,});try {+ // Capture pre-transition FSM status + tracker state BEFORE+ // register/deliver so we can decide whether the FSM's+ // `onAgentActivity` callback owns the first typing frame or this+ // router does — see "First-ever wake ordering" in+ // plans/bot-typing-indicator.md. The FSM path OWNS the first frame+ // whenever a transition into a running-family state fires; the+ // router emits only on a true mid-turn wake (`beforeStatus ===+ // "running"` AND `wasActive`) where no FSM edge would leave the+ // newly-added scope silent for up to 5s.+ const beforeStatus =+ this.opts.manager.snapshot?.().agents?.[cmd.agentId]?.status ?? "unregistered";+ const wasActive = this.opts.typingTracker?.hasAny(cmd.agentId) ?? false;await this.opts.onBeforeAgent?.(cmd.agentId);this.opts.manager.register(cmd.agentId, {runtimeConfig: cmd.config,@@ -277,10 +297,23 @@ export class AgentRouter {launchId: cmd.launchId,});this.running.add(cmd.agentId);+ // Track the DM scope AFTER register succeeds (register may throw on+ // an unknown runtime) but BEFORE deliver, so the FSM callback+ // installed synchronously inside deliver sees the scope in its+ // snapshot. Adding before register would leak a stale scope into+ // the shared tracker on any register-time throw.+ const dmScope = cmd.unreadNotice.dmConversationId;+ if (dmScope) this.opts.typingTracker?.add(cmd.agentId, dmScope);const text = (this.opts.formatUnreadNoticeText ?? defaultFormatUnreadNoticeText)(cmd.unreadNotice);// The manager (not this router) decides spawn vs. in-process notify// vs. coalesce — see managerPolicy's `onWake`.this.opts.manager.deliver(cmd.agentId, { seq: cmd.unreadNotice.latestSeq, text });+ if (dmScope && wasActive && beforeStatus === "running") {+ this.opts.channel.reportAgentTyping?.({+ agentId: cmd.agentId,+ dmConversationId: dmScope,+ });+ }await this.opts.channel.reportWakeAck?.({agentId: cmd.agentId,launchId: cmd.launchId,diff --git a/src/daemon/src/manager/index.ts b/src/daemon/src/manager/index.tsindex 3db2318fe..1cf3baebd 100644--- a/src/daemon/src/manager/index.ts+++ b/src/daemon/src/manager/index.ts@@ -9,3 +9,4 @@export * from "./managerPolicy.js";export * from "./managerRuntime.js";export * from "./agentRouter.js";+export * from "./typingScopeTracker.js";diff --git a/src/daemon/src/manager/typingScopeTracker.test.ts b/src/daemon/src/manager/typingScopeTracker.test.tsnew file mode 100644index 000000000..ec13a5209--- /dev/null+++ b/src/daemon/src/manager/typingScopeTracker.test.ts@@ -0,0 +1,42 @@+import { describe, it, expect } from "vitest";+import { createTypingScopeTracker } from "./typingScopeTracker.js";++describe("typingScopeTracker", () => {+ it("add + snapshot yields the current scope set", () => {+ const t = createTypingScopeTracker();+ t.add("bot_1", "dm_a");+ t.add("bot_1", "dm_b");+ expect(t.snapshot("bot_1").sort()).toEqual(["dm_a", "dm_b"]);+ });++ it("add is idempotent — set semantics prevent duplicate scopes", () => {+ const t = createTypingScopeTracker();+ t.add("bot_1", "dm_a");+ t.add("bot_1", "dm_a");+ t.add("bot_1", "dm_a");+ expect(t.snapshot("bot_1")).toEqual(["dm_a"]);+ });++ it("hasAny reflects presence — false for unknown agents and after clear", () => {+ const t = createTypingScopeTracker();+ expect(t.hasAny("bot_1")).toBe(false);+ t.add("bot_1", "dm_a");+ expect(t.hasAny("bot_1")).toBe(true);+ t.clear("bot_1");+ expect(t.hasAny("bot_1")).toBe(false);+ });++ it("snapshot for an unknown agent returns an empty array", () => {+ const t = createTypingScopeTracker();+ expect(t.snapshot("nobody")).toEqual([]);+ });++ it("clear drops all scopes for one agent — other agents unaffected", () => {+ const t = createTypingScopeTracker();+ t.add("bot_1", "dm_a");+ t.add("bot_2", "dm_b");+ t.clear("bot_1");+ expect(t.snapshot("bot_1")).toEqual([]);+ expect(t.snapshot("bot_2")).toEqual(["dm_b"]);+ });+});diff --git a/src/daemon/src/manager/typingScopeTracker.ts b/src/daemon/src/manager/typingScopeTracker.tsnew file mode 100644index 000000000..21663bc7f--- /dev/null+++ b/src/daemon/src/manager/typingScopeTracker.ts@@ -0,0 +1,48 @@+/**+ * Per-agent typing-scope tracker — the daemon's in-memory record of which+ * DM conversation ids each running bot should be broadcasting a "bot is+ * typing…" pill for. Populated on each `agent:wake` (from+ * `unreadNotice.dmConversationId`), read by the heartbeat manager, and+ * cleared bulk on turn end.+ *+ * Set semantics — repeated `add` for the same scope is a no-op, so two+ * wakes for the same DM inside one coalesced turn don't double the frame+ * rate. Kept as a plain in-memory Map (daemon is single-process per+ * machine, tracker doesn't need to survive a crash — the client's 8s+ * auto-expire cleans up if the daemon dies mid-turn).+ */+export interface TypingScopeTracker {+ /** Insert (idempotent) a DM scope for this agent. */+ add(agentId: string, dmConversationId: string): void;+ /** Current DM scopes for this agent (empty if none / unknown). */+ snapshot(agentId: string): string[];+ /** Whether this agent has ANY active scope. */+ hasAny(agentId: string): boolean;+ /** Drop all scopes for this agent. */+ clear(agentId: string): void;+}++export function createTypingScopeTracker(): TypingScopeTracker {+ const scopes = new Map<string, Set<string>>();+ return {+ add(agentId, dmConversationId) {+ let set = scopes.get(agentId);+ if (!set) {+ set = new Set();+ scopes.set(agentId, set);+ }+ set.add(dmConversationId);+ },+ snapshot(agentId) {+ const set = scopes.get(agentId);+ return set ? [...set] : [];+ },+ hasAny(agentId) {+ const set = scopes.get(agentId);+ return !!set && set.size > 0;+ },+ clear(agentId) {+ scopes.delete(agentId);+ },+ };+}diff --git a/src/daemon/src/server/wsControlChannel.ts b/src/daemon/src/server/wsControlChannel.tsindex cfa597cee..dda4d9480 100644--- a/src/daemon/src/server/wsControlChannel.ts+++ b/src/daemon/src/server/wsControlChannel.ts@@ -97,6 +97,8 @@ type OutboundFrame =| ({ type: "ready" } & HostReady)| { type: "agent_session"; agentId: AgentId; sessionId: string; launchId: string }| { type: "agent_activity"; agentId: AgentId; state: AgentActivityState }+ | { type: "agent_typing"; agentId: AgentId; dmConversationId: string }+ | { type: "agent_typing_stop"; agentId: AgentId; dmConversationId: string }| {type: "agent_wake_ack";agentId: AgentId;@@ -213,6 +215,27 @@ export class WsControlChannel implements HostControlChannel {this.sendFrame({ type: "agent_activity", ...info });}+ /**+ * Emit an `agent_typing` frame (daemon → server). Sync + fire-and-forget:+ * this is a heartbeat, dropped silently when the socket isn't open — the+ * next heartbeat tick re-fires within 5s and the client's 8s expiry keeps+ * the pill from flickering. Never traverses the ws-do 8s dedup gate on+ * the client-inbound path (the daemon meters cadence, ws-do fans out+ * unconditionally).+ */+ reportAgentTyping(info: { agentId: AgentId; dmConversationId: string }): void {+ this.sendFrame({ type: "agent_typing", ...info });+ }++ /**+ * Emit an `agent_typing_stop` frame (daemon → server). One-shot at turn+ * end; ws-do fans out `community:typing.stop` with no dedup so the pill+ * clears within ~50ms.+ */+ reportAgentTypingStop(info: { agentId: AgentId; dmConversationId: string }): void {+ this.sendFrame({ type: "agent_typing_stop", ...info });+ }+/*** Emit a bot audit event upward — either from the credential proxy sighting* (`cli_invocation`) or from a runtime `thinking` / non-Bash `tool_call`diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex 1cbe6e1ed..eeebf92aa 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -435,6 +435,14 @@ export interface UnreadNotice {channel: ChannelRef;/** The high-water seq that triggered this notice, for `AgentMsg.seq`. */latestSeq: Seq;+ /**+ * When the notice targets a DM, the DM's conversation id. Populated+ * server-side (`buildUnreadWakeCommand`) so the daemon can emit+ * `agent_typing` frames for the correct DM scope without parsing+ * `channel: ChannelRef` (a peer-handle path). Absent for channel/thread+ * wakes — bot typing is DM-only for now.+ */+ dmConversationId?: string;}/* ------------------------------------------------------------------ */@@ -625,6 +633,18 @@ export interface HostControlChannel {* local mock channel can omit it.*/reportAgentActivity?(info: { agentId: AgentId; state: AgentActivityState }): Promise<void>;+ /**+ * Emit an `agent_typing` frame for the given (agentId, dmConversationId)+ * scope — the daemon-metered heartbeat that keeps the "bot is typing…" pill+ * lit for a working bot. Optional so LocalControlChannel can omit.+ */+ reportAgentTyping?(info: { agentId: AgentId; dmConversationId: string }): void;+ /**+ * Emit an `agent_typing_stop` frame for the given scope — one-shot on turn+ * end so the pill disappears immediately instead of dangling until the+ * client's 8s auto-expire. Optional so LocalControlChannel can omit.+ */+ reportAgentTypingStop?(info: { agentId: AgentId; dmConversationId: string }): void;/*** Report a bot audit event (cli_invocation | tool_call | thinking) upward.* Optional so LocalControlChannel can omit — matches `reportAgentActivity?`diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.tsindex 1192ae8fb..6494c2c1a 100644--- a/src/shared/src/community-ws-events.ts+++ b/src/shared/src/community-ws-events.ts@@ -84,6 +84,20 @@ export type CommunityTypingStart = {userId: string}+/**+ * Explicit "stop typing" event. Fired by the daemon's bot-typing pipeline+ * when a bot's turn ends, so the pill disappears immediately instead of+ * dangling until the client's 8s auto-expire. Channel/thread fields are+ * shaped for future parity — today only `dmConversationId` is emitted.+ */+export type CommunityTypingStop = {+ type: "community:typing.stop"+ channelId?: string+ dmConversationId?: string+ threadId?: string+ userId: string+}+// ── Child channel events (threads + forum posts) ─────────────────────────────export type CommunityChildChannelCreate = {@@ -492,6 +506,7 @@ export type CommunityWsEvent =| CommunityPinAdd| CommunityPinRemove| CommunityTypingStart+ | CommunityTypingStop| CommunityChildChannelCreate| CommunityChildChannelUpdate| CommunityServerUpdate@@ -539,6 +554,7 @@ export const WS_EVENTS = {PIN_ADD: "community:pin.add",PIN_REMOVE: "community:pin.remove",TYPING_START: "community:typing.start",+ TYPING_STOP: "community:typing.stop",CHILD_CHANNEL_CREATE: "community:channel.child_create",CHILD_CHANNEL_UPDATE: "community:channel.child_update",SERVER_UPDATE: "community:server.update",diff --git a/src/shared/src/community/wake-dispatch.ts b/src/shared/src/community/wake-dispatch.tsindex 345132abc..2b3a57a45 100644--- a/src/shared/src/community/wake-dispatch.ts+++ b/src/shared/src/community/wake-dispatch.ts@@ -142,7 +142,12 @@ export async function buildUnreadWakeCommand(const channel = await agentInbox.resolveUnreadNoticeChannel(db, scope, input.botUserId);if (!channel) return { state: "skip", reason: "notice_channel_unresolvable" };- const unreadNotice: UnreadNotice = { kind: "unread_notice", channel, latestSeq: msg.seq };+ const unreadNotice: UnreadNotice = {+ kind: "unread_notice",+ channel,+ latestSeq: msg.seq,+ ...(scope.dmConversationId ? { dmConversationId: scope.dmConversationId } : {}),+ };const config = makeRuntimeConfig({runtime: botCtx.runtime,agentName: botCtx.name,diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 510995808..62474ee24 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -256,6 +256,8 @@ export {HostReadyMessageSchema,SessionErrorFrameSchema,AgentActivityMessageSchema,+ AgentTypingMessageSchema,+ AgentTypingStopMessageSchema,COMMUNITY_RUNTIME_ID_MAX,COMMUNITY_RUNTIME_VERSION_MAX,COMMUNITY_RUNTIME_LIST_MAX,@@ -339,6 +341,8 @@ export type {HostReadyMessage,SessionErrorFrame,AgentActivityMessage,+ AgentTypingMessage,+ AgentTypingStopMessage,CommunityBotCreateRequest,CommunityBotPatchRequest,CommunityBotAddToServerRequest,diff --git a/src/shared/src/schemas.test.ts b/src/shared/src/schemas.test.tsindex 5e1d66e7b..4cd7cda13 100644--- a/src/shared/src/schemas.test.ts+++ b/src/shared/src/schemas.test.ts@@ -1,5 +1,10 @@import { describe, it, expect } from "vitest"-import { CommunityBotCreateRequestSchema, CommunityBotPatchRequestSchema } from "./schemas"+import {+ CommunityBotCreateRequestSchema,+ CommunityBotPatchRequestSchema,+ AgentTypingMessageSchema,+ AgentTypingStopMessageSchema,+} from "./schemas"function validCreatePayload(image?: string) {return {@@ -75,3 +80,72 @@ describe("BotImageUrlSchema (via CommunityBotPatchRequestSchema)", () => {expect(res.success).toBe(false)})})++describe("AgentTypingMessageSchema", () => {+ it("parses a well-formed frame", () => {+ const res = AgentTypingMessageSchema.safeParse({+ type: "agent_typing",+ agentId: "bot_1",+ dmConversationId: "dm_1",+ })+ expect(res.success).toBe(true)+ })++ it("rejects missing dmConversationId", () => {+ const res = AgentTypingMessageSchema.safeParse({ type: "agent_typing", agentId: "bot_1" })+ expect(res.success).toBe(false)+ })++ it("rejects empty dmConversationId (min length 1)", () => {+ const res = AgentTypingMessageSchema.safeParse({+ type: "agent_typing",+ agentId: "bot_1",+ dmConversationId: "",+ })+ expect(res.success).toBe(false)+ })++ it("rejects missing agentId", () => {+ const res = AgentTypingMessageSchema.safeParse({+ type: "agent_typing",+ dmConversationId: "dm_1",+ })+ expect(res.success).toBe(false)+ })++ it("rejects the wrong discriminant", () => {+ const res = AgentTypingMessageSchema.safeParse({+ type: "agent_activity",+ agentId: "bot_1",+ dmConversationId: "dm_1",+ })+ expect(res.success).toBe(false)+ })+})++describe("AgentTypingStopMessageSchema", () => {+ it("parses a well-formed frame", () => {+ const res = AgentTypingStopMessageSchema.safeParse({+ type: "agent_typing_stop",+ agentId: "bot_1",+ dmConversationId: "dm_1",+ })+ expect(res.success).toBe(true)+ })++ it("rejects missing dmConversationId", () => {+ const res = AgentTypingStopMessageSchema.safeParse({+ type: "agent_typing_stop",+ agentId: "bot_1",+ })+ expect(res.success).toBe(false)+ })++ it("rejects missing agentId", () => {+ const res = AgentTypingStopMessageSchema.safeParse({+ type: "agent_typing_stop",+ dmConversationId: "dm_1",+ })+ expect(res.success).toBe(false)+ })+})diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex cc0b4be22..8c71332d7 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -940,6 +940,27 @@ export const AgentActivityMessageSchema = z.object({});export type AgentActivityMessage = z.infer<typeof AgentActivityMessageSchema>;+/**+ * `agent_typing` / `agent_typing_stop` frames — daemon → server. Report+ * that a bot is (or is not) actively working on a specific DM. The daemon+ * meters cadence (5s heartbeat while running; one-shot stop on idle) so+ * ws-do can fan out unconditionally without traversing the 8s client-typing+ * dedup gate.+ */+export const AgentTypingMessageSchema = z.object({+ type: z.literal("agent_typing"),+ agentId: z.string(),+ dmConversationId: z.string().min(1),+});+export type AgentTypingMessage = z.infer<typeof AgentTypingMessageSchema>;++export const AgentTypingStopMessageSchema = z.object({+ type: z.literal("agent_typing_stop"),+ agentId: z.string(),+ dmConversationId: z.string().min(1),+});+export type AgentTypingStopMessage = z.infer<typeof AgentTypingStopMessageSchema>;+export const CommunityPairTokenResponseSchema = z.object({tokenId: z.string(),diff --git a/src/shared/test/community/wake-dispatch-build.test.ts b/src/shared/test/community/wake-dispatch-build.test.tsindex c8c629b3d..2c23e1f8c 100644--- a/src/shared/test/community/wake-dispatch-build.test.ts+++ b/src/shared/test/community/wake-dispatch-build.test.ts@@ -111,6 +111,7 @@ describe("buildUnreadWakeCommand", () => {kind: "unread_notice",channel: "/.dm/gustavo#0042",latestSeq: 7,+ dmConversationId: "dm_1",});expect(mockCanBotReadWakeScope).toHaveBeenCalledWith(fakeDb, "bot_1", { dmConversationId: "dm_1" });expect(mockResolveUnreadNoticeChannel).toHaveBeenCalledWith(fakeDb, { dmConversationId: "dm_1" }, "bot_1");@@ -124,6 +125,9 @@ describe("buildUnreadWakeCommand", () => {expect(result.state).toBe("ready");if (result.state !== "ready") throw new Error("expected ready");expect(result.command.unreadNotice.channel).toBe("/srv_1/general/#3");+ // Channel/thread wakes never carry dmConversationId — DM-only invariant+ // for the bot-typing indicator pipeline.+ expect(result.command.unreadNotice.dmConversationId).toBeUndefined();});it("skip: message_missing when the message no longer exists", async () => {diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.tsindex a78154ab8..d94110184 100644--- a/src/web/src/hooks/community/use-community-ws.ts+++ b/src/web/src/hooks/community/use-community-ws.ts@@ -410,10 +410,12 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {case "community:message.create": {if (wsStore.hasSeenMessage(event.message.id)) returnwsStore.markSeenMessage(event.message.id)-// Sending a message is an implicit typing.stop for its author —- // clear immediately so the indicator doesn't linger under the- // freshly-arrived message until the 8s timeout expires.+ // clear once we know this is a fresh message. In a DM the bot's+ // reply is broadcast as BOTH message.create AND dm.new_message;+ // whichever wins the dedup fires the clear, the loser is a no-op.+ // Clearing before dedup would also clear on WS-reconnect replays+ // of stale messages, briefly wiping a still-active heartbeat pill.clearTypingIndicator(event.message.authorId)// 1) Patch the focused channel/dm page cache if the event matches.@@ -514,6 +516,18 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {return}+ // ── Typing stop — explicit clear (bot turn-end path) ────────────+ // Symmetric with typing.start: only clear when focused on the same+ // target so a stop for a different DM doesn't wipe the local pill.+ case "community:typing.stop": {+ const userId = event.userId+ const viewerId = viewerUserIdRef.current+ if (viewerId && userId === viewerId) return+ if (!matchesFocus(event)) return+ clearTypingIndicator(userId)+ return+ }+// ── Child channels (threads + forum posts) ──────────────────────case "community:channel.child_create":case "community:channel.child_update": {@@ -799,6 +813,10 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {case "community:dm.new_message": {if (wsStore.hasSeenMessage(event.message.id)) returnwsStore.markSeenMessage(event.message.id)+ // Same rationale as `community:message.create` above — either the+ // message.create or dm.new_message broadcast will pass the dedup+ // first and clear the pill; the other is a no-op.+ clearTypingIndicator(event.message.authorId)// Focus-scope patch (mirrors community message.create).if (event.dmConversationId === sub.dmConversationId) {diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.tsindex bcd76720f..50ab3211f 100644--- a/src/ws-do/src/ws-durable.test.ts+++ b/src/ws-do/src/ws-durable.test.ts@@ -177,6 +177,30 @@ vi.mock("@alook/shared", () => {return { success: true as const, data: { type: "agent_activity" as const, agentId: m.agentId, state: m.state } }},}+ const AgentTypingMessageSchema = {+ safeParse(v: unknown) {+ const m = v as { type?: unknown; agentId?: unknown; dmConversationId?: unknown }+ if (m?.type !== "agent_typing") return { success: false } as const+ if (typeof m.agentId !== "string" || m.agentId.length === 0) return { success: false } as const+ if (typeof m.dmConversationId !== "string" || m.dmConversationId.length === 0) return { success: false } as const+ return {+ success: true as const,+ data: { type: "agent_typing" as const, agentId: m.agentId, dmConversationId: m.dmConversationId },+ }+ },+ }+ const AgentTypingStopMessageSchema = {+ safeParse(v: unknown) {+ const m = v as { type?: unknown; agentId?: unknown; dmConversationId?: unknown }+ if (m?.type !== "agent_typing_stop") return { success: false } as const+ if (typeof m.agentId !== "string" || m.agentId.length === 0) return { success: false } as const+ if (typeof m.dmConversationId !== "string" || m.dmConversationId.length === 0) return { success: false } as const+ return {+ success: true as const,+ data: { type: "agent_typing_stop" as const, agentId: m.agentId, dmConversationId: m.dmConversationId },+ }+ },+ }const HostBotAuditEventFrameSchema = {safeParse(v: unknown) {const m = v as { type?: unknown; agentId?: unknown; sessionId?: unknown; launchId?: unknown; event?: unknown }@@ -213,6 +237,8 @@ vi.mock("@alook/shared", () => {SessionErrorFrameSchema,HostReadyMessageSchema,AgentActivityMessageSchema,+ AgentTypingMessageSchema,+ AgentTypingStopMessageSchema,HostBotAuditEventFrameSchema,// Deterministic preset picker so the assertion can pin exact// `statusEmoji`/`statusText` values regardless of the injected `seed`.@@ -1256,6 +1282,167 @@ describe("WebSocketDurableObject", () => {})})+ describe("community-machine — agent_typing / agent_typing_stop frames", () => {+ beforeEach(() => {+ mockGetBotBindingWithOwner.mockReset()+ mockGetDM.mockReset()+ mockStubFetch.mockClear()+ })++ it("agent_typing: fans out community:typing.start to the DM peer when machine owns the bot and DM is valid", async () => {+ const { durable, store } = createDO()+ store.set("community-machine-identity", {+ userId: "u_1",+ machineId: "cm_1",+ credentialHash: "0".repeat(64),+ })+ mockGetBotBindingWithOwner.mockResolvedValue({+ machineId: "cm_1",+ runtime: "codex",+ ownerUserId: "u_1",+ })+ mockGetDM.mockResolvedValue({ user1Id: "bot_1", user2Id: "peer_1" })++ const ws = createMockWebSocket()+ ws.serializeAttachment({+ type: "community-machine",+ machineId: "cm_1",+ userId: "u_1",+ authenticated: true,+ })++ const frame = JSON.stringify({+ type: "agent_typing",+ agentId: "bot_1",+ dmConversationId: "dm_1",+ })+ await durable.webSocketMessage(ws as any, frame)++ const call = mockStubFetch.mock.calls.find((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))+ expect(call).toBeDefined()+ const body = JSON.parse(await (call![0] as Request).clone().text()) as {+ type: string+ userId: string+ dmConversationId: string+ }+ expect(body).toEqual({+ type: "community:typing.start",+ userId: "bot_1",+ dmConversationId: "dm_1",+ })+ })++ it("agent_typing: drops a frame naming a bot bound to a different machine — no fan-out", async () => {+ const { durable, store } = createDO()+ store.set("community-machine-identity", {+ userId: "u_1",+ machineId: "cm_1",+ credentialHash: "0".repeat(64),+ })+ mockGetBotBindingWithOwner.mockResolvedValue({+ machineId: "cm_OTHER",+ runtime: "codex",+ ownerUserId: "u_1",+ })++ const ws = createMockWebSocket()+ ws.serializeAttachment({+ type: "community-machine",+ machineId: "cm_1",+ userId: "u_1",+ authenticated: true,+ })++ const frame = JSON.stringify({+ type: "agent_typing",+ agentId: "bot_1",+ dmConversationId: "dm_1",+ })+ await durable.webSocketMessage(ws as any, frame)++ expect(mockGetDM).not.toHaveBeenCalled()+ expect(mockStubFetch).not.toHaveBeenCalled()+ })++ it("agent_typing: drops a frame for a bot that is not a DM participant — no fan-out", async () => {+ const { durable, store } = createDO()+ store.set("community-machine-identity", {+ userId: "u_1",+ machineId: "cm_1",+ credentialHash: "0".repeat(64),+ })+ mockGetBotBindingWithOwner.mockResolvedValue({+ machineId: "cm_1",+ runtime: "codex",+ ownerUserId: "u_1",+ })+ mockGetDM.mockResolvedValue({ user1Id: "someone", user2Id: "else" })++ const ws = createMockWebSocket()+ ws.serializeAttachment({+ type: "community-machine",+ machineId: "cm_1",+ userId: "u_1",+ authenticated: true,+ })++ const frame = JSON.stringify({+ type: "agent_typing",+ agentId: "bot_1",+ dmConversationId: "dm_1",+ })+ await durable.webSocketMessage(ws as any, frame)++ expect(mockStubFetch).not.toHaveBeenCalled()+ })++ it("agent_typing_stop: fans out community:typing.stop to the DM peer, excludes sender", async () => {+ const { durable, store } = createDO()+ store.set("community-machine-identity", {+ userId: "u_1",+ machineId: "cm_1",+ credentialHash: "0".repeat(64),+ })+ mockGetBotBindingWithOwner.mockResolvedValue({+ machineId: "cm_1",+ runtime: "codex",+ ownerUserId: "u_1",+ })+ mockGetDM.mockResolvedValue({ user1Id: "bot_1", user2Id: "peer_1" })++ const ws = createMockWebSocket()+ ws.serializeAttachment({+ type: "community-machine",+ machineId: "cm_1",+ userId: "u_1",+ authenticated: true,+ })++ const frame = JSON.stringify({+ type: "agent_typing_stop",+ agentId: "bot_1",+ dmConversationId: "dm_1",+ })+ await durable.webSocketMessage(ws as any, frame)++ const call = mockStubFetch.mock.calls.find((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))+ expect(call).toBeDefined()+ const body = JSON.parse(await (call![0] as Request).clone().text()) as {+ type: string+ userId: string+ dmConversationId: string+ }+ expect(body).toEqual({+ type: "community:typing.stop",+ userId: "bot_1",+ dmConversationId: "dm_1",+ })+ // Sender exclusion: only the peer (peer_1) is targeted — a single+ // /broadcast call, addressed via the peer's user DO.+ expect(mockStubFetch.mock.calls.filter((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))).toHaveLength(1)+ })+ })+describe("community-machine — bot_audit_event frame", () => {beforeEach(() => {mockGetBotBindingWithOwner.mockReset()diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.tsindex 2e23f6c5e..2f06300a8 100644--- a/src/ws-do/src/ws-durable.ts+++ b/src/ws-do/src/ws-durable.ts@@ -8,6 +8,8 @@ import {HostReadyMessageSchema,SessionErrorFrameSchema,AgentActivityMessageSchema,+ AgentTypingMessageSchema,+ AgentTypingStopMessageSchema,HostBotAuditEventFrameSchema,pickBotActivityPreset,RUNNING_PRESETS,@@ -709,6 +711,52 @@ export class WebSocketDurableObject extends DurableObject<Env> {return}+ // `agent_typing` / `agent_typing_stop` — daemon reports the bot is (or+ // stopped) actively working on a DM. Fan out `community:typing.start` /+ // `community:typing.stop` to the DM's peer. Deliberately does NOT traverse+ // the client-inbound 8s dedup gate at ws-durable.ts:367-419 — daemon meters+ // cadence (5s heartbeat), so gating here would cause pill flicker every+ // ~3s. Client-side auto-expire (`TYPING_INDICATOR_TIMEOUT_MS = 8000`)+ // recovers if a heartbeat is dropped.+ const typingParse = AgentTypingMessageSchema.safeParse(parsed)+ if (typingParse.success) {+ const { agentId, dmConversationId } = typingParse.data+ const db = createDb(this.env.DB)+ const binding = await queries.communityBot.getBotBindingWithOwner(db, agentId)+ if (!binding || binding.machineId !== identity.machineId) {+ log.warn("agent_typing frame for a bot not bound to this machine — dropped", {+ agentId,+ machineId: identity.machineId,+ })+ return+ }+ // DM participancy is enforced inside `fanOutTyping` — no need to+ // pre-query `getDM` here at 5s cadence.+ const event = JSON.stringify({+ type: "community:typing.start",+ dmConversationId,+ userId: agentId,+ })+ await this.fanOutTyping(agentId, undefined, dmConversationId, undefined, event)+ return+ }+ const typingStopParse = AgentTypingStopMessageSchema.safeParse(parsed)+ if (typingStopParse.success) {+ const { agentId, dmConversationId } = typingStopParse.data+ const db = createDb(this.env.DB)+ const binding = await queries.communityBot.getBotBindingWithOwner(db, agentId)+ if (!binding || binding.machineId !== identity.machineId) {+ log.warn("agent_typing_stop frame for a bot not bound to this machine — dropped", {+ agentId,+ machineId: identity.machineId,+ })+ return+ }+ // DM participancy enforced inside `fanOutTypingStop`.+ await this.fanOutTypingStop(agentId, dmConversationId)+ return+ }+// `bot_audit_event` — daemon reports a bot activity event (cli_invocation,// tool_call, or thinking). Insert + rolling-500 prune land atomically via// `db.batch`; server stamps `createdAt` (never trust the daemon clock).@@ -1084,6 +1132,45 @@ export class WebSocketDurableObject extends DurableObject<Env> {}}+ /**+ * Fan out an explicit `community:typing.stop` for a DM scope to the DM's+ * peer. Mirrors `fanOutTyping` for DM but never traverses a dedup cache —+ * a stop must always land or the pill dangles until the client's 8s expiry.+ */+ private async fanOutTypingStop(+ senderUserId: string,+ dmConversationId: string,+ ): Promise<void> {+ const db = createDb(this.env.DB)+ const dm = await queries.communityDm.getDM(db, dmConversationId)+ if (!dm || (dm.user1Id !== senderUserId && dm.user2Id !== senderUserId)) {+ log.warn("fanOutTypingStop: sender not a DM participant", { senderUserId, dmConversationId })+ return+ }+ const recipientUserIds = [dm.user1Id, dm.user2Id]+ .filter(Boolean)+ .filter((id): id is string => typeof id === "string" && id !== senderUserId)+ if (recipientUserIds.length === 0) return+ const body = JSON.stringify({+ type: "community:typing.stop",+ dmConversationId,+ userId: senderUserId,+ })+ for (let i = 0; i < recipientUserIds.length; i += WebSocketDurableObject.SUBREQUEST_BATCH_SIZE) {+ const batch = recipientUserIds.slice(i, i + WebSocketDurableObject.SUBREQUEST_BATCH_SIZE)+ await Promise.all(+ batch.map((userId) => {+ const doId = this.env.WS_DO.idFromName("user:" + userId)+ const stub = this.env.WS_DO.get(doId)+ return stub.fetch(new Request("http://internal/broadcast", {+ method: "POST",+ body,+ })).catch(() => { })+ })+ )+ }+ }+private countAuthenticatedUserConnections(userId: string): number {let count = 0for (const ws of this.ctx.getWebSockets()) {