Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(community): publish machine version with online state (#1148)

Generb9247a368641
diff --git a/src/web/src/components/community/shell/use-shell-daemon-update-controller.restore.dom.test.tsx b/src/web/src/components/community/shell/use-shell-daemon-update-controller.restore.dom.test.tsx
index 1934b483b..58969f76c 100644
--- a/src/web/src/components/community/shell/use-shell-daemon-update-controller.restore.dom.test.tsx
+++ b/src/web/src/components/community/shell/use-shell-daemon-update-controller.restore.dom.test.tsx
@@ -8,11 +8,13 @@ import { CommunityTestProvider } from "@/test/community-owner-fixture"
import { communityKeys } from "@/lib/query-keys"
import { createIdbPersister, PERSIST_BUSTER } from "@/lib/query-persister"
import type { MachinesResponse, MachineSummary } from "@/hooks/community/use-machines"
+import type { CommunityMachineSummary } from "@alook/shared"
import { initialUserBarExtensionState, userBarExtensionReducer, type UserBarExtensionState } from "@/components/community/shell/user-bar-extension-state"
import { daemonUpdateCollapseStorageKey, useShellDaemonUpdateController } from "./use-shell-daemon-update-controller"
+import { handleMachineUpdated } from "@/hooks/community/community-ws/presence-machine-events"
const transport = vi.hoisted(() => ({ load: vi.fn() }))
vi.mock("@/lib/api/client", async original => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: (...args: unknown[]) => transport.load(...args) }))
-const machine: MachineSummary = { id: "machine-1", hostname: "fixture", displayName: "Fixture", platform: "darwin", arch: "arm64", osRelease: "26.0", daemonVersion: "0.1.34", status: "online", lastSeenAt: null, availableRuntimes: [], createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z" }
+const machine: CommunityMachineSummary = { id: "machine-1", hostname: "fixture", displayName: "Fixture", platform: "darwin", arch: "arm64", osRelease: "26.0", daemonVersion: "0.1.34", status: "online", lastSeenAt: null, availableRuntimes: [], createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z" }
it.each([false, true])("preserves collapsed preference through native restored list; empty=%s", async empty => {
const owner = await createCommunityQueryOwner("user-1")
const disk = createIdbPersister("user-1")
@@ -128,3 +130,43 @@ it("syncs the same eligible machine identity only when its partial list becomes
window.localStorage.removeItem(key)
}
})
+
+it.each([
+ ["0.1.35", false], ["0.1.34", false], ["0.1.35", true], ["0.1.34", true],
+] as const)("uses the whole online version publication; next=%s, another old machine=%s", async (daemonVersion, anotherOldMachine) => {
+ const owner = await createCommunityQueryOwner("user-1")
+ const offline = { ...machine, status: "offline" as const }
+ const other = { ...machine, id: "machine-2" }
+ owner.client.setQueryData<MachinesResponse>(communityKeys.machines(), { machines: [offline, ...(anotherOldMachine ? [other] : [])], complete: true, observed: true })
+ transport.load.mockReset()
+ transport.load.mockResolvedValue({ quotas: [] })
+ const key = daemonUpdateCollapseStorageKey("user-1", "0.1.35")
+ window.localStorage.removeItem(key)
+ let state!: UserBarExtensionState
+ const renderedTargets: string[][] = []
+ function Probe() {
+ const [current, dispatch] = useReducer(userBarExtensionReducer, initialUserBarExtensionState)
+ useShellDaemonUpdateController({ userId: "user-1", extensionState: current, dispatch, latestDaemonVersion: "0.1.35" })
+ state = current
+ renderedTargets.push([...(current.update?.targetMachineIds ?? [])])
+ return null
+ }
+ const view = render(createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "user-1", retainOwner: true }, createElement(Probe)))
+ try {
+ await waitFor(() => expect((state.update?.targetMachineIds ?? []).slice().sort()).toEqual(anotherOldMachine ? [other.id] : []))
+ await act(async () => { await handleMachineUpdated({ type: "community:machine.updated", machine: { ...offline, status: "online", daemonVersion } }, { queryClient: owner.client }) })
+ const expected = [...(daemonVersion === "0.1.34" ? [machine.id] : []), ...(anotherOldMachine ? [other.id] : [])]
+ await waitFor(() => expect((state.update?.targetMachineIds ?? []).slice().sort()).toEqual(expected))
+ if (daemonVersion === "0.1.35") {
+ expect(renderedTargets.every(ids => !ids.includes(machine.id))).toBe(true)
+ await act(async () => { await handleMachineUpdated({ type: "community:machine.updated", machine: { ...machine, daemonVersion: "0.1.34" } }, { queryClient: owner.client }) })
+ await waitFor(() => expect(state.update?.targetMachineIds).toContain(machine.id))
+ }
+ if (anotherOldMachine) expect(owner.client.getQueryData<MachinesResponse>(communityKeys.machines())?.machines.find(row => row.id === other.id)).toEqual(other)
+ expect(transport.load.mock.calls.some(([url]) => String(url).includes("view=list"))).toBe(false)
+ } finally {
+ view.unmount()
+ owner.client.clear()
+ window.localStorage.removeItem(key)
+ }
+})
diff --git a/src/web/src/hooks/community/community-ws/handler-context.ts b/src/web/src/hooks/community/community-ws/handler-context.ts
index f48940ad1..c49943038 100644
--- a/src/web/src/hooks/community/community-ws/handler-context.ts
+++ b/src/web/src/hooks/community/community-ws/handler-context.ts
@@ -33,6 +33,7 @@ export type CommunityWsDispatchContext = {
sub: Subscription
viewerUserIdRef: { current: string | null }
matchesFocus: (event: { channelId?: string }) => boolean
+ onMachineOnline?: () => void
}
export type CommunityWsHandlerContext = CommunityWsDispatchContext & {
@@ -69,5 +70,5 @@ export type SocialEventContext = Pick<
>
export type PresenceMachineEventContext = Pick<
CommunityWsHandlerContext,
- "queryClient"
+ "queryClient" | "onMachineOnline"
>
diff --git a/src/web/src/hooks/community/community-ws/presence-machine-events.ts b/src/web/src/hooks/community/community-ws/presence-machine-events.ts
index de643700e..7b4e8b487 100644
--- a/src/web/src/hooks/community/community-ws/presence-machine-events.ts
+++ b/src/web/src/hooks/community/community-ws/presence-machine-events.ts
@@ -88,11 +88,13 @@ export async function handleMachineStatus(
export async function handleMachineUpdated(
event: CommunityMachineUpdated,
- { queryClient }: PresenceMachineEventContext,
+ { queryClient, onMachineOnline }: PresenceMachineEventContext,
) {
const original = captureMachinesPublication(queryClient)
+ let becameOnline = false
const published = await publishMachines(queryClient, original,
(prev) => {
+ becameOnline = event.machine.status === "online" && prev?.machines.find(machine => machine.id === event.machine.id)?.status !== "online"
if (!prev) return { machines: [event.machine], complete: false }
const idx = prev.machines.findIndex((m) => m.id === event.machine.id)
if (idx === -1) return replaceMachines(prev, [event.machine, ...prev.machines])
@@ -104,6 +106,7 @@ export async function handleMachineUpdated(
if (!published) return
assertCommunityLiveSnapshotTokenCurrent(queryClient, original.token, undefined)
if (queryClient.getQueryCache().get(original.query.queryHash) !== original.query) return
+ if (becameOnline) onMachineOnline?.()
const current = queryClient.getQueryData<MachinesResponse>(original.query.queryKey)
if (current?.complete === false || current?.observed === false) void queryClient.invalidateQueries({ queryKey: communityKeys.machines(), exact: true })
}
diff --git a/src/web/src/hooks/community/use-community-ws.dom.test.ts b/src/web/src/hooks/community/use-community-ws.dom.test.ts
index 69fa768d6..e31b1ddc2 100644
--- a/src/web/src/hooks/community/use-community-ws.dom.test.ts
+++ b/src/web/src/hooks/community/use-community-ws.dom.test.ts
@@ -31,6 +31,8 @@ import {
} from "./community-ws/connection-status"
import { communityBrowserEventBatchType, deriveCommunityDeliveryOperationId, encodeCommunityBrowserEventBatch, prepareCommunityDeliveryEvents } from "@alook/shared"
import * as analytics from "@/lib/analytics"
+import { currentCommunityEventFixture, machineResourceFixture } from "@/test/community-resource-fixtures"
+import type { CommunityMachineUpdated } from "@alook/shared"
beforeEach(resetCommunityWsHarness)
afterEach(cleanupCommunityWsHarness)
@@ -324,3 +326,69 @@ it("requests inviter joins on current-account authentication and consent changes
expect(joined).toHaveBeenCalledTimes(before + 1)
expect(joined).toHaveBeenLastCalledWith(getCapturedRuntime().lifecycle)
})
+
+it.each([false, true])("drains the full machine transition without draining steady metadata; batch=%s", async batch => {
+ await mountHook({ viewerUserId: "u_me" })
+ const connected = vi.spyOn(funnel, "drainCommunityFunnelEvents").mockResolvedValue(undefined)
+ const joined = vi.spyOn(funnel, "drainInvitedHumanJoined").mockResolvedValue(undefined)
+ const machine = machineResourceFixture({ id: "machine-transition", status: "offline", daemonVersion: "0.1.62" })
+ capturedQueryClient.setQueryData(communityKeys.machines(), { machines: [machine], complete: true, observed: true })
+ let sequence = 0
+ const deliver = async (event: CommunityMachineUpdated) => {
+ if (!batch) return await capturedOnMessage!(currentCommunityEventFixture(event))
+ const prepared = await prepareCommunityDeliveryEvents([event])
+ if (!prepared.ok) throw new Error("invalid machine fixture")
+ const encoded = await encodeCommunityBrowserEventBatch({ operationDigest: prepared.prepared.digest, operationId: await deriveCommunityDeliveryOperationId(`machine-transition-${++sequence}`), events: [event] })
+ if (!encoded.ok) throw new Error("invalid machine batch")
+ await capturedOnMessage!(encoded.batch)
+ }
+ try {
+ const online = { ...machine, status: "online" as const, daemonVersion: "0.1.63" }
+ await act(async () => { await deliver({ type: "community:machine.updated", machine: online }) })
+ expect(connected).toHaveBeenCalledOnce()
+ expect(joined).toHaveBeenCalledExactlyOnceWith(getCapturedRuntime().lifecycle)
+ await act(async () => { await deliver({ type: "community:machine.updated", machine: { ...online, hostname: "renamed" } }) })
+ expect(connected).toHaveBeenCalledOnce()
+ expect(joined).toHaveBeenCalledOnce()
+ await act(async () => { await capturedOnMessage!(currentCommunityEventFixture({ type: "community:machine.status", machineId: machine.id, status: "offline", lastSeenAt: "2026-11-02T00:00:00.000Z" })) })
+ expect(connected).toHaveBeenCalledTimes(2)
+ expect(joined).toHaveBeenCalledTimes(2)
+ } finally {
+ connected.mockRestore()
+ joined.mockRestore()
+ }
+})
+
+it("qualifies overlapping full machine updates at their serialized accepted row", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const machine = machineResourceFixture({ id: "overlap-machine", status: "offline", daemonVersion: "0.1.62" })
+ capturedQueryClient.setQueryData(communityKeys.machines(), { machines: [machine], complete: true, observed: true })
+ const query = capturedQueryClient.getQueryCache().find({ queryKey: communityKeys.machines(), exact: true })!
+ expect(query).toBeDefined()
+ let release!: () => void
+ const held = new Promise<void>(resolve => { release = resolve })
+ const cancel = vi.spyOn(query, "cancel").mockReturnValue(held)
+ const connected = vi.spyOn(funnel, "drainCommunityFunnelEvents").mockResolvedValue(undefined)
+ const joined = vi.spyOn(funnel, "drainInvitedHumanJoined").mockResolvedValue(undefined)
+ const pending: Promise<unknown>[] = []
+ try {
+ const online = { ...machine, status: "online" as const, daemonVersion: "0.1.63" }
+ await act(async () => {
+ pending.push(Promise.resolve(capturedOnMessage!(currentCommunityEventFixture({ type: "community:machine.updated", machine: online }))))
+ pending.push(Promise.resolve(capturedOnMessage!(currentCommunityEventFixture({ type: "community:machine.updated", machine: { ...online, hostname: "second metadata" } }))))
+ await Promise.resolve()
+ expect(capturedQueryClient.getQueryData(communityKeys.machines())).toMatchObject({ machines: [{ status: "offline", daemonVersion: "0.1.62" }] })
+ release()
+ await Promise.all(pending)
+ })
+ expect(connected).toHaveBeenCalledOnce()
+ expect(joined).toHaveBeenCalledOnce()
+ expect(capturedQueryClient.getQueryData(communityKeys.machines())).toMatchObject({ machines: [{ hostname: "second metadata", status: "online", daemonVersion: "0.1.63" }] })
+ } finally {
+ release()
+ await Promise.allSettled(pending)
+ cancel.mockRestore()
+ connected.mockRestore()
+ joined.mockRestore()
+ }
+})
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index fc32a3d31..f3cbcc676 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -189,6 +189,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
const communityStore = runtime.ui
const sub = communityStore.get().subscription
const wsStore = runtime.ws
+ let machineBecameOnline = false
// A DM is a channel now — every message/typing/reaction event carries a
// single `channelId`. The subscription still tracks two slots so the
// handler can route a DM channel's events into the `dmMessages` cache vs
@@ -212,6 +213,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
sub,
viewerUserIdRef,
matchesFocus,
+ onMachineOnline: () => { machineBecameOnline = true },
})
const reconcileAfterBatchFailure = (
reason: "digest-conflict" | "projection-failed",
@@ -296,7 +298,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
decoded.batch.operationId,
decoded.batch.operationDigest,
)
- if (hasCommunityFunnelTrigger(decoded.events)) {
+ if (machineBecameOnline || hasCommunityFunnelTrigger(decoded.events)) {
void drainCommunityFunnelEvents()
void drainInvitedHumanJoined(runtime.lifecycle)
}
@@ -318,7 +320,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
return
}
await dispatchCommunityWsEvent(decoded.event, context("single"))
- if (hasCommunityFunnelTrigger([decoded.event])) {
+ if (machineBecameOnline || hasCommunityFunnelTrigger([decoded.event])) {
void drainCommunityFunnelEvents()
void drainInvitedHumanJoined(runtime.lifecycle)
}
diff --git a/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts b/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts
index b30087709..877caba23 100644
--- a/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts
+++ b/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts
@@ -1016,11 +1016,15 @@ test("real machine status, removal and creation retire an older list response",
await expect.poll(() => proxy.connectionFrames.some(frame => frame.type === "auth.ok")).toBe(true)
const connection = connectRealMachine(first.credential, caseResources)
await connection.opened
- connection.socket.send(JSON.stringify(HostReadyMessageSchema.parse({ type: "ready", runtimeReport: [{ id: "pi", status: "healthy" }], capabilities: [CONTROL_HEARTBEAT_CAPABILITY], runningAgents: [], hostname: first.hostname, platform: "linux", arch: "x64", daemonVersion: (JSON.parse(readFileSync(resolve(REPO_ROOT, "src/daemon/package.json"), "utf8")) as { version: string }).version })))
- await expect.poll(() => proxy.frames.some(frame => frame.type === "community:machine.status" && frame.machineId === first.machineId && frame.status === "online")).toBe(true)
+ const daemonVersion = (JSON.parse(readFileSync(resolve(REPO_ROOT, "src/daemon/package.json"), "utf8")) as { version: string }).version
+ connection.socket.send(JSON.stringify(HostReadyMessageSchema.parse({ type: "ready", runtimeReport: [{ id: "pi", status: "healthy" }], capabilities: [CONTROL_HEARTBEAT_CAPABILITY], runningAgents: [], hostname: first.hostname, platform: "linux", arch: "x64", daemonVersion })))
+ await expect.poll(() => proxy.frames.some(frame => {
+ const machine = frame.machine as { id?: string; status?: string; daemonVersion?: string } | undefined
+ return frame.type === "community:machine.updated" && machine?.id === first.machineId && machine.status === "online" && machine.daemonVersion === daemonVersion
+ })).toBe(true)
const online = await confirmCommunityFixtureApiResponse(page.request.get("/api/community/machines?view=list", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(online.status()).toBe(200)
- expect((await online.json()).machines).toEqual(expect.arrayContaining([expect.objectContaining({ id: first.machineId, status: "online" })]))
+ expect((await online.json()).machines).toEqual(expect.arrayContaining([expect.objectContaining({ id: first.machineId, status: "online", daemonVersion })]))
await connection.close()
await expect.poll(() => proxy.frames.some(frame => frame.type === "community:machine.status" && frame.machineId === first.machineId && frame.status === "offline")).toBe(true)
const removed = await confirmCommunityFixtureApiResponse(page.request.delete(`/api/community/machines/${first.machineId}`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
@@ -1038,7 +1042,7 @@ test("real machine status, removal and creation retire an older list response",
await expect(page.getByText(second.hostname, { exact: true })).toHaveCount(1)
await expect(page.getByText(first.hostname, { exact: true })).toHaveCount(0)
await expect(page.getByRole("heading", { name: "No machines yet", exact: true })).toHaveCount(0)
- await testInfo.attach("real-machine-ws-before-old-list", { body: JSON.stringify({ originalIds: original.machines.map(machine => machine.id), currentIds: [second.machineId], originalRequestAborted: held.aborted(), heartbeatAcks: connection.heartbeatAcks(), events: proxy.frames.filter(frame => frame.type.startsWith("community:machine.")).map(frame => ({ type: frame.type, machineId: frame.machineId ?? (frame.machine as { id?: string } | undefined)?.id, status: frame.status })) }), contentType: "application/json" })
+ await testInfo.attach("real-machine-ws-before-old-list", { body: JSON.stringify({ originalIds: original.machines.map(machine => machine.id), currentIds: [second.machineId], originalRequestAborted: held.aborted(), heartbeatAcks: connection.heartbeatAcks(), events: proxy.frames.filter(frame => frame.type.startsWith("community:machine.")).map(frame => ({ type: frame.type, machineId: frame.machineId ?? (frame.machine as { id?: string } | undefined)?.id, status: frame.status ?? (frame.machine as { status?: string } | undefined)?.status, daemonVersion: (frame.machine as { daemonVersion?: string } | undefined)?.daemonVersion })) }), contentType: "application/json" })
} finally { await held.close() }
})
diff --git a/src/ws-do/src/ws-durable/machine-frames.test.ts b/src/ws-do/src/ws-durable/machine-frames.test.ts
index 27fc91a3a..5b050ed4c 100644
--- a/src/ws-do/src/ws-durable/machine-frames.test.ts
+++ b/src/ws-do/src/ws-durable/machine-frames.test.ts
@@ -850,6 +850,61 @@ describe("WebSocketDurableObject", () => {
)
})
+ it.each([
+ ["0.1.62", "0.1.63", false],
+ ["0.1.63", "0.1.63", false],
+ ["0.1.62", "0.1.63", true],
+ ["0.1.63", "0.1.63", true],
+ ] as const)("publishes one full online machine on ready %s to %s, owner failure=%s", async (priorDaemonVersion, daemonVersion, ownerFailure) => {
+ const { durable, store, storage } = createDO()
+ seedIdentity(store)
+ const machine = { id: "cm_1", hostname: "host", daemonVersion, availableRuntimes: [], status: "online", lastSeenAt: "2026-11-02T00:00:00.000Z" }
+ mockUpsertMachineByMachineId.mockResolvedValue({ machine, priorAvailableRuntimes: [], priorDaemonVersion, priorStatus: "offline" })
+ mockListBotsForMachine.mockResolvedValue([{ id: "bot-1", name: "Bot", discriminator: "0001", description: "" }])
+ mockGetCoMemberUserIds.mockResolvedValue(["viewer-1"])
+ if (ownerFailure) mockStubFetch.mockRejectedValueOnce(new Error("owner unavailable"))
+
+ const frame = JSON.stringify({ type: "ready", runtimeReport: [], capabilities: ["control-heartbeat-v1"], runningAgents: [], daemonVersion })
+ const ws = machineWs()
+ await durable.webSocketMessage(ws as WebSocket, frame)
+ const bodies = await Promise.all(mockStubFetch.mock.calls.map(async ([request]) => await (request as Request).clone().json() as { type: string; machine?: { id: string; status: string; daemonVersion: string }; userId?: string; online?: boolean }))
+ const machineEvents = bodies.filter(body => body.type.startsWith("community:machine."))
+ expect(machineEvents).toEqual([expect.objectContaining({ type: "community:machine.updated", machine: expect.objectContaining({ id: "cm_1", status: "online", daemonVersion }) })])
+ expect(bodies.filter(body => body.type === "community:presence.update")).toEqual([expect.objectContaining({ userId: "bot-1", online: true })])
+ expect(mockListBotsForMachine).toHaveBeenCalledExactlyOnceWith({}, "cm_1")
+ expect(storage.setAlarm).toHaveBeenCalledTimes(1)
+ expect(ws.close).not.toHaveBeenCalled()
+ expect(mockLogWarn).not.toHaveBeenCalledWith("ws_frame_dropped", expect.anything())
+
+ mockStubFetch.mockClear()
+ mockListBotsForMachine.mockClear()
+ mockUpsertMachineByMachineId.mockResolvedValue({ machine, priorAvailableRuntimes: [], priorDaemonVersion: daemonVersion, priorStatus: "online" })
+ await durable.webSocketMessage(machineWs() as WebSocket, frame)
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ expect(mockListBotsForMachine).not.toHaveBeenCalled()
+ })
+
+ it("keeps the complete owner publication and heartbeat when bound-bot lookup fails", async () => {
+ const { durable, store, storage } = createDO()
+ seedIdentity(store)
+ const machine = { id: "cm_1", hostname: "host", daemonVersion: "0.1.63", availableRuntimes: [], status: "online", lastSeenAt: "2026-11-02T00:00:00.000Z" }
+ mockUpsertMachineByMachineId.mockResolvedValue({ machine, priorAvailableRuntimes: [], priorDaemonVersion: "0.1.62", priorStatus: "offline" })
+ mockListBotsForMachine.mockRejectedValueOnce(new Error("D1 unavailable"))
+ const ws = machineWs()
+
+ await durable.webSocketMessage(ws as WebSocket, JSON.stringify({
+ type: "ready", runtimeReport: [], capabilities: ["control-heartbeat-v1"], runningAgents: [], daemonVersion: "0.1.63",
+ }))
+
+ expect(mockStubFetch).toHaveBeenCalledTimes(1)
+ const body = await (mockStubFetch.mock.calls[0]![0] as Request).clone().json()
+ expect(body).toMatchObject({ type: "community:machine.updated", machine: { id: "cm_1", status: "online", daemonVersion: "0.1.63" } })
+ expect(mockListBotsForMachine).toHaveBeenCalledExactlyOnceWith({}, "cm_1")
+ expect(storage.setAlarm).toHaveBeenCalledTimes(1)
+ expect(ws.close).not.toHaveBeenCalled()
+ expect(mockLogWarn).not.toHaveBeenCalledWith("ws_frame_dropped", expect.anything())
+ })
+
it("emits machine.updated for status or lastError drift and emits nothing for steady metadata", async () => {
const { durable, store } = createDO()
seedIdentity(store)
@@ -881,6 +936,7 @@ describe("WebSocketDurableObject", () => {
)
expect(driftBodies.filter((body) => body.type === "community:machine.updated")).toHaveLength(1)
expect(driftBodies.filter((body) => body.type === "community:machine.status")).toHaveLength(0)
+ expect(mockListBotsForMachine).not.toHaveBeenCalled()
mockStubFetch.mockClear()
mockUpsertMachineByMachineId.mockResolvedValue({
diff --git a/src/ws-do/src/ws-durable/machine-ready.ts b/src/ws-do/src/ws-durable/machine-ready.ts
index 83ba81361..27f2e1054 100644
--- a/src/ws-do/src/ws-durable/machine-ready.ts
+++ b/src/ws-do/src/ws-durable/machine-ready.ts
@@ -194,26 +194,15 @@ export async function handleReadyFrame(
machineId: machine.id,
})
- // Activation owns machine.created. Ready emits status only for an actual
- // offline → online transition, using the pre-upsert status returned by D1.
- if (priorStatus !== "online") {
- await notifyUserDO(context, identity.userId, {
- type: WS_EVENTS.MACHINE_STATUS,
- machineId: machine.id,
- status: "online",
- lastSeenAt: machine.lastSeenAt ?? new Date().toISOString(),
- }).catch(() => { })
- }
-
const priorCanonical = canonicalRuntimes(priorAvailableRuntimes ?? [])
const nextCanonical = canonicalRuntimes(availableRuntimes)
// Runtime status/lastError drift is machine metadata drift and must reach
// open clients even when the runtime set and versions are unchanged.
- if (priorCanonical !== nextCanonical || priorDaemonVersion !== daemonVersion) {
+ if (priorStatus !== "online" || priorCanonical !== nextCanonical || priorDaemonVersion !== daemonVersion) {
await notifyUserDO(context, identity.userId, {
type: WS_EVENTS.MACHINE_UPDATED,
machine: summary,
- }).catch(() => { })
+ }, { machineOnlineTransition: priorStatus !== "online" })
}
await scheduleHeartbeatAlarm(context)
diff --git a/src/ws-do/src/ws-durable/presence-typing.ts b/src/ws-do/src/ws-durable/presence-typing.ts
index 86eb8419f..154f4adc1 100644
--- a/src/ws-do/src/ws-durable/presence-typing.ts
+++ b/src/ws-do/src/ws-durable/presence-typing.ts
@@ -8,6 +8,7 @@ import {
isCommunityEventCandidate,
visibilityIsDmParticipant,
type Database,
+ type CommunityMachineUpdated,
} from "@alook/shared"
import type { UserConnectionState, WsDurableContext } from "./internal"
import { createInternalBrowserBroadcastRequest } from "../internal-user-broadcast"
@@ -144,6 +145,7 @@ export async function notifyUserDO(
context: WsDurableContext,
userId: string,
payload: unknown,
+ options?: { machineOnlineTransition: boolean },
): Promise<void> {
const normalized = normalizeBrowserPayload(context, payload)
if (!normalized.ok) return
@@ -160,7 +162,7 @@ export async function notifyUserDO(
}
try {
- const status = machineStatusPayload(outboundPayload)
+ const status = machineStatusPayload(outboundPayload, options?.machineOnlineTransition ?? false)
if (!status) return
const db = createDb(context.env.DB)
const bots = await queries.communityBot.listBotsForMachine(db, status.machineId)
@@ -176,9 +178,13 @@ export async function notifyUserDO(
}
}
-function machineStatusPayload(payload: unknown): { machineId: string; online: boolean } | null {
+function machineStatusPayload(payload: unknown, machineOnlineTransition: boolean): { machineId: string; online: boolean } | null {
if (typeof payload !== "object" || payload === null) return null
- const p = payload as { type?: unknown; machineId?: unknown; status?: unknown }
+ const p = payload as { type?: unknown; machineId?: unknown; status?: unknown; machine?: unknown }
+ if (p.type === WS_EVENTS.MACHINE_UPDATED && machineOnlineTransition) {
+ const { machine } = payload as CommunityMachineUpdated
+ return { machineId: machine.id, online: machine.status === "online" }
+ }
if (p.type !== WS_EVENTS.MACHINE_STATUS) return null
if (typeof p.machineId !== "string") return null
if (p.status !== "online" && p.status !== "offline") return null