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
fix: finalize standalone JEV adapter and decouple dispatch (#826)
Gener7566992d38d1
diff --git a/src/web/src/lib/community/jev-wake-gate.test.ts b/src/web/src/lib/community/jev-wake-gate.test.tsindex 4bcb6dd55..2062cb025 100644--- a/src/web/src/lib/community/jev-wake-gate.test.ts+++ b/src/web/src/lib/community/jev-wake-gate.test.ts@@ -115,7 +115,6 @@ describe("JEV provider adapters", () => {bot_0: {type: "noul" as const,instructions: "Wake?",- criteria: { true: "yes", false: "no" },},},}@@ -160,7 +159,6 @@ describe("JEV provider adapters", () => {bot_0: {type: "noul" as const,instructions: "Wake?",- criteria: { true: "yes", false: "no" },},},}@@ -230,16 +228,12 @@ describe("selectJevWakeCandidates", () => {"Jarvis#9866": {type: "noul",instructions: {- question: "Does message content identify this candidate as someone who should act now?",+ question: "Should this candidate act now in response to state.current_message?",candidate: {handle: "Jarvis#9866",role: "Own release coordination",},- context_rule: "Determine recipients from state.current_message first; new recipients replace earlier recipients. An unqualified whole-audience phrase includes every candidate, while a phrase qualified by a named group includes only that group's members. Use state.immediately_previous_message to resolve a context-dependent answer or approval. Use state.older_context only when current_message refers to a named person, group, or item. Return yes only when this candidate is an intended recipient, the owner of the pending request being answered, or the clear owner of an unaddressed task. Mere relevance or ability to help is no.",- },- criteria: {- true: "This candidate should act now.",- false: "This candidate should not act now.",+ decision_rule: "Determine recipients from state.current_message first; new recipients replace earlier recipients. An unqualified whole-audience phrase includes every candidate, while a phrase qualified by a named group includes only that group's members. Use state.immediately_previous_message to resolve a context-dependent answer or approval. Use state.older_context only when current_message refers to a named person, group, or item. Return yes only when this candidate is an intended recipient, the owner of the pending request being answered, or the clear owner of an unaddressed task. Mere relevance or ability to help is no.",},},},@@ -306,7 +300,7 @@ describe("selectJevWakeCandidates", () => {const question = request.questions[`${instructionLikeName}#9866`]expect(question.instructions.question).toBe(- "Does message content identify this candidate as someone who should act now?",+ "Should this candidate act now in response to state.current_message?",)expect(question.instructions.question).not.toContain(instructionLikeName)expect(question.instructions.candidate).toEqual({@@ -343,11 +337,11 @@ describe("selectJevWakeCandidates", () => {author: "Gener#6185",text: "Jarvis 和 Samara 是这次的审查组。",})- expect(request.questions["Jarvis#9866"].instructions.context_rule)+ expect(request.questions["Jarvis#9866"].instructions.decision_rule).toContain("Use state.immediately_previous_message")- expect(request.questions["Jarvis#9866"].instructions.context_rule)+ expect(request.questions["Jarvis#9866"].instructions.decision_rule).toContain("Use state.older_context only when current_message refers")- expect(request.questions["Jarvis#9866"].instructions.context_rule)+ expect(request.questions["Jarvis#9866"].instructions.decision_rule).toContain("Mere relevance or ability to help is no")})@@ -498,7 +492,7 @@ describe("selectJevWakeCandidates", () => {.toEqual(messages.slice(1, 8).map((message) => message.text))})- it("uses the single configured 0.50 threshold and fails open only invalid answers", async () => {+ it("uses the single configured inclusive 0.50 threshold", async () => {const candidates = [candidate,{ ...candidate, botUserId: "bot_2", discriminator: "0002" },@@ -512,7 +506,7 @@ describe("selectJevWakeCandidates", () => {answers: {"Jarvis#9866": { type: "noul", noul: 0.49 },"Jarvis#0002": { type: "noul", noul: 0.5 },- "Jarvis#0003": { type: "choice", noul: 1 },+ "Jarvis#0003": { type: "noul", noul: 0.51 },},}},@@ -525,6 +519,55 @@ describe("selectJevWakeCandidates", () => {expect(selected.map((item) => item.botUserId)).toEqual(["bot_2", "bot_3"])})+ it("returns every eligible candidate when all valid scores are below 0.50", async () => {+ const candidates = [+ candidate,+ { ...candidate, botUserId: "bot_2", discriminator: "0002" },+ ]+ const selected = await selectJevWakeCandidates(+ { ...input, candidates },+ { ...openRouterEnv, JEV_WAKE_THRESHOLD: "0.50" },+ { createProvider: () => provider([0.49, 0.01]) },+ )++ expect(selected).toEqual(candidates)+ expect(mocks.logInfo).toHaveBeenCalledWith(+ "jev_wake_gate_complete",+ expect.objectContaining({+ failOpenReason: "empty_selection",+ narrowedCount: 0,+ selectedCount: 2,+ }),+ )+ })++ it("returns every eligible candidate when any response answer is invalid", async () => {+ const candidates = [+ candidate,+ { ...candidate, botUserId: "bot_2", discriminator: "0002" },+ { ...candidate, botUserId: "bot_3", discriminator: "0003" },+ ]+ const invalidProvider: JevDecisionProvider = {+ name: "openrouter",+ async decide() {+ return {+ model: "typesafe/jev-1.13",+ answers: {+ "Jarvis#9866": { type: "noul", noul: 0.1 },+ "Jarvis#0002": { type: "noul", noul: 0.9 },+ "Jarvis#0003": { type: "choice", noul: 1 },+ },+ }+ },+ }++ await expect(selectJevWakeCandidates(+ { ...input, candidates },+ { ...openRouterEnv, JEV_WAKE_THRESHOLD: "0.50" },+ { createProvider: () => invalidProvider },+ )).resolves.toEqual(candidates)+ })+it.each([{ type: "noul", noul: Number.NaN },{ type: "noul", noul: -0.01 },@@ -737,6 +780,40 @@ describe("selectJevWakeCandidates", () => {expect(Object.keys(decide.mock.calls[1]![0].questions)).toHaveLength(1)})+ it("fails open to every candidate when one provider batch fails", async () => {+ const candidates = Array.from({ length: 21 }, (_, index) => ({+ ...candidate,+ botUserId: `bot_${index + 1}`,+ discriminator: String(index).padStart(4, "0"),+ }))+ const decide = vi.fn(async (request) => {+ const keys = Object.keys(request.questions)+ if (keys.length === 1) throw new Error("second batch failed")+ return {+ model: "typesafe/jev-1.13",+ answers: Object.fromEntries(keys.map((key) => [+ key,+ { type: "noul", noul: 0.9 },+ ])),+ }+ })++ await expect(selectJevWakeCandidates(+ { ...input, candidates },+ { ...openRouterEnv, JEV_WAKE_THRESHOLD: "0.50" },+ { createProvider: () => ({ name: "openrouter", decide }) },+ )).resolves.toEqual(candidates)+ expect(decide).toHaveBeenCalledTimes(2)+ expect(mocks.logInfo).toHaveBeenCalledWith(+ "jev_wake_gate_complete",+ expect.objectContaining({+ failOpenReason: "batch_failure",+ narrowedCount: 0,+ selectedCount: 21,+ }),+ )+ })+it("fails open before provider calls for candidate and payload limits", async () => {const decide = vi.fn()const createProvider = () => ({ name: "openrouter" as const, decide })diff --git a/src/web/src/lib/community/jev-wake-gate.ts b/src/web/src/lib/community/jev-wake-gate.tsindex 2694e04f9..c959ed806 100644--- a/src/web/src/lib/community/jev-wake-gate.ts+++ b/src/web/src/lib/community/jev-wake-gate.ts@@ -19,10 +19,6 @@ type JevEntry = string | JsonValue[] | { [key: string]: JsonValue }type JevNoulQuestion = {type: "noul"instructions: JevEntry- criteria: {- true: JevEntry- false: JevEntry- }}type JevProviderRequest = {@@ -324,16 +320,12 @@ function makeQuestion(return {type: "noul",instructions: {- question: "Does message content identify this candidate as someone who should act now?",+ question: "Should this candidate act now in response to state.current_message?",candidate: {handle: formatHandle(candidate.name ?? "", candidate.discriminator),role: candidate.instruction,},- context_rule: "Determine recipients from state.current_message first; new recipients replace earlier recipients. An unqualified whole-audience phrase includes every candidate, while a phrase qualified by a named group includes only that group's members. Use state.immediately_previous_message to resolve a context-dependent answer or approval. Use state.older_context only when current_message refers to a named person, group, or item. Return yes only when this candidate is an intended recipient, the owner of the pending request being answered, or the clear owner of an unaddressed task. Mere relevance or ability to help is no.",- },- criteria: {- true: "This candidate should act now.",- false: "This candidate should not act now.",+ decision_rule: "Determine recipients from state.current_message first; new recipients replace earlier recipients. An unqualified whole-audience phrase includes every candidate, while a phrase qualified by a named group includes only that group's members. Use state.immediately_previous_message to resolve a context-dependent answer or approval. Use state.older_context only when current_message refers to a named person, group, or item. Return yes only when this candidate is an intended recipient, the owner of the pending request being answered, or the clear owner of an unaddressed task. Mere relevance or ability to help is no.",},}}@@ -409,37 +401,44 @@ export async function selectJevWakeCandidates(return input.candidates}const state = makeState(input)- const batches = chunks(input.candidates, MAX_QUESTIONS_PER_BATCH)+ const batches = chunks(input.candidates, MAX_QUESTIONS_PER_BATCH).map((batch, batchIndex) => {+ const mapping = new Map<string, JevWakeGateInput["candidates"][number]>()+ const questions = Object.fromEntries(batch.map((candidate) => {+ const key = formatHandle(candidate.name ?? "", candidate.discriminator)+ mapping.set(key, candidate)+ return [key, makeQuestion(candidate)]+ }))+ return {+ batch,+ batchIndex,+ mapping,+ request: { state, questions },+ }+ })+ for (const prepared of batches) {+ if (byteLength({ model: config.model, ...prepared.request }) <= MAX_BATCH_BYTES) continue+ log.warn("jev_wake_gate_fail_open", {+ messageId: input.messageId,+ provider: provider.name,+ reason: "payload_limit",+ batchIndex: prepared.batchIndex,+ candidateCount: prepared.batch.length,+ })+ return input.candidates+ }const controller = new AbortController()const timer = setTimeout(() => controller.abort(), TOTAL_TIMEOUT_MS)const startedAt = Date.now()try {- const selected = await Promise.all(batches.map(async (batch, batchIndex) => {- const mapping = new Map<string, JevWakeGateInput["candidates"][number]>()- const questions = Object.fromEntries(batch.map((candidate) => {- const key = formatHandle(candidate.name ?? "", candidate.discriminator)- mapping.set(key, candidate)- return [key, makeQuestion(candidate)]- }))- const request = { state, questions }- if (byteLength({ model: config.model, ...request }) > MAX_BATCH_BYTES) {- log.warn("jev_wake_gate_fail_open", {- messageId: input.messageId,- provider: provider.name,- reason: "payload_limit",- batchIndex,- candidateCount: batch.length,- })- return batch- }-+ const selections = await Promise.all(batches.map(async ({ batch, batchIndex, mapping, request }) => {try {const response = await provider.decide(request, {signal: controller.signal,timeoutMs: REQUEST_TIMEOUT_MS,})const accepted: JevWakeGateInput["candidates"] = []+ let valid = truefor (const [key, candidate] of mapping) {const probability = readProbability(response.answers[key])if (probability === null) {@@ -451,7 +450,7 @@ export async function selectJevWakeCandidates(reason: "invalid_answer",batchIndex,})- accepted.push(candidate)+ valid = falsecontinue}const wouldPass = probability >= config.threshold@@ -467,7 +466,7 @@ export async function selectJevWakeCandidates(})if (wouldPass) accepted.push(candidate)}- return accepted+ return valid ? { ok: true as const, accepted } : { ok: false as const }} catch (error) {log.warn("jev_wake_gate_fail_open", {messageId: input.messageId,@@ -477,17 +476,27 @@ export async function selectJevWakeCandidates(batchIndex,candidateCount: batch.length,})- return batch+ return { ok: false as const }}}))- const result = selected.flat()+ const narrowed = selections.every((selection) => selection.ok)+ ? selections.flatMap((selection) => selection.accepted)+ : []+ const failOpenReason = selections.some((selection) => !selection.ok)+ ? "batch_failure"+ : narrowed.length === 0+ ? "empty_selection"+ : undefined+ const result = failOpenReason ? input.candidates : narrowedlog.info("jev_wake_gate_complete", {messageId: input.messageId,provider: provider.name,model: config.model,candidateCount: input.candidates.length,selectedCount: result.length,+ narrowedCount: narrowed.length,batchCount: batches.length,+ ...(failOpenReason ? { failOpenReason } : {}),durationMs: Date.now() - startedAt,})return resultdiff --git a/src/web/src/lib/community/message-dispatcher-architecture.test.ts b/src/web/src/lib/community/message-dispatcher-architecture.test.tsindex 91e10ce9c..830002e22 100644--- a/src/web/src/lib/community/message-dispatcher-architecture.test.ts+++ b/src/web/src/lib/community/message-dispatcher-architecture.test.ts@@ -26,6 +26,13 @@ describe("committed-message delivery architecture", () => {expect(producer).not.toMatch(/\bqueries\b|findWakeCandidates|resolveNotificationEligibility/)})+ it("keeps the committed-message dispatcher decoupled from the JEV adapter", () => {+ const dispatcher = source("./message-dispatcher.ts")+ expect(dispatcher).not.toMatch(+ /jev-wake-gate|JevWakeGateInput|selectJevWakeCandidates|wakeGateInput|loadWakeConversation/,+ )+ })+it("deletes the old per-recipient notify implementation", () => {expect(existsSync(new URL("./notify.ts", import.meta.url))).toBe(false)expect(existsSync(new URL("./notify.test.ts", import.meta.url))).toBe(false)diff --git a/src/web/src/lib/community/message-dispatcher.test.ts b/src/web/src/lib/community/message-dispatcher.test.tsindex 4ab558ec7..6d4557932 100644--- a/src/web/src/lib/community/message-dispatcher.test.ts+++ b/src/web/src/lib/community/message-dispatcher.test.ts@@ -7,7 +7,6 @@ vi.mock("@opennextjs/cloudflare", () => ({const mockGetMessage = vi.fn()const mockGetWakeContextMessageInScope = vi.fn()-const mockListWakeContextMessagesBefore = vi.fn()const mockGetMessageClientNonceForDelivery = vi.fn()const mockGetChannel = vi.fn()const mockListAttention = vi.fn()@@ -35,8 +34,6 @@ vi.mock("@alook/shared", async () => {getMessage: (...args: unknown[]) => mockGetMessage(...args),getWakeContextMessageInScope: (...args: unknown[]) =>mockGetWakeContextMessageInScope(...args),- listWakeContextMessagesBefore: (...args: unknown[]) =>- mockListWakeContextMessagesBefore(...args),getMessageClientNonceForDelivery: (...args: unknown[]) =>mockGetMessageClientNonceForDelivery(...args),},@@ -74,11 +71,6 @@ const mockEnqueueQueueTasks = vi.fn()vi.mock("./queue-producer", () => ({enqueueQueueTasks: (...args: unknown[]) => mockEnqueueQueueTasks(...args),}))-const mockSelectJevWakeCandidates = vi.fn()-vi.mock("./jev-wake-gate", () => ({- selectJevWakeCandidates: (...args: unknown[]) => mockSelectJevWakeCandidates(...args),-}))-import { dispatchCommittedMessage, planCommittedMessage } from "./message-dispatcher"import { deriveCommunityDeliveryOperationId } from "@alook/shared"@@ -99,7 +91,7 @@ const message = {seq: 7,}-function wakeContextRow(overrides: Partial<{+function messageContextRow(overrides: Partial<{id: stringauthorId: stringauthorName: string@@ -165,7 +157,6 @@ describe("planCommittedMessage", () => {vi.clearAllMocks()mockGetMessage.mockResolvedValue(message)mockGetWakeContextMessageInScope.mockResolvedValue(null)- mockListWakeContextMessagesBefore.mockResolvedValue({ messages: [], hasMore: false })mockGetMessageClientNonceForDelivery.mockResolvedValue("nonce_1")mockGetChannel.mockResolvedValue(channel)mockListAttachments.mockResolvedValue([])@@ -197,7 +188,6 @@ describe("planCommittedMessage", () => {runtime: "codex",},])- mockSelectJevWakeCandidates.mockImplementation(async (input) => input.candidates)mockSendMessageDeliveryBatch.mockResolvedValue(undefined)mockEnqueueQueueTasks.mockResolvedValue(undefined)})@@ -210,11 +200,7 @@ describe("planCommittedMessage", () => {expect(plan.unreadMentionUserIds).toEqual(["u_mentions", "bot_1"])expect(plan.mentionUserIds).toEqual(["u_mentions", "u_mention_only", "bot_1"])expect(plan.wakeBotUserIds).toEqual(["bot_1"])- expect(plan.wakeGateInput.candidates).toEqual([- expect.objectContaining({- botUserId: "bot_1",- }),- ])+ expect(plan).not.toHaveProperty("wakeGateInput")expect(plan.pushUserIds).toEqual(["u_all", "u_mentions", "bot_1", "u_mention_only"])expect(plan.messageEvent).toMatchObject({type: "community:message.create",@@ -280,12 +266,11 @@ describe("planCommittedMessage", () => {expect(plan.pushUserIds).toEqual(["u_all"])expect(mockResolveEligibility).toHaveBeenCalledWith({}, ["u_all"], "msg_1")expect(mockFindWakeCandidates).toHaveBeenCalledWith({}, expect.objectContaining({ recipients: ["u_all"] }))- expect(mockListWakeContextMessagesBefore).not.toHaveBeenCalled()})it("rehydrates attachment dimensions and reply preview from committed rows", async () => {mockGetMessage.mockResolvedValue({ ...message, replyToId: "reply_1" })- mockGetWakeContextMessageInScope.mockResolvedValue(wakeContextRow({+ mockGetWakeContextMessageInScope.mockResolvedValue(messageContextRow({id: "reply_1",authorName: "Earlier",content: "previous message",@@ -324,7 +309,7 @@ describe("planCommittedMessage", () => {mentionType: "everyone",replyToId: "reply_1",})- mockGetWakeContextMessageInScope.mockResolvedValue(wakeContextRow({+ mockGetWakeContextMessageInScope.mockResolvedValue(messageContextRow({id: "reply_1",authorId: "bot_1",authorName: "Bot",@@ -354,181 +339,12 @@ describe("planCommittedMessage", () => {const plan = await planCommittedMessage({} as never, "msg_1")- expect(plan.wakeGateInput.message).toEqual({- text: "",- type: "system",- attachmentContentTypes: ["image/png"],- })- expect(plan.wakeGateInput.candidates).toEqual([- expect.objectContaining({- botUserId: "bot_1",- name: null,- instruction: "",- }),- ])- expect(JSON.stringify(plan.wakeGateInput)).not.toContain("private-name.png")- })-- it("builds scoped reply, opener, and recent context once with public author handles", async () => {- mockGetMessage.mockResolvedValue({- ...message,- channelId: "thread_1",- replyToId: "reply_1",- seq: 10,- })- mockGetChannel.mockResolvedValue({- ...channel,- id: "thread_1",- type: "thread",- parentChannelId: "forum_1",- parentMessageId: "opener_1",- })- mockResolveRecipients.mockImplementation(async (_db, channelId: string) =>- channelId === "thread_1" ? ["author_1", "bot_1"] : ["parent_viewer"],- )- mockResolveEligibility.mockResolvedValue(new Map([["bot_1", state()]]))-- const recentHuman = wakeContextRow({- id: "recent_1",- content: "Earlier human context",- seq: 7,- createdAt: "2026-08-17T00:00:01.000Z",- channelId: "thread_1",- })- const ancestor = wakeContextRow({- id: "ancestor_1",- authorId: "bot_2",- authorName: "Helper",- authorDiscriminator: "0002",- authorIsBot: true,- content: "Original assignment",- seq: 8,- createdAt: "2026-08-17T00:00:02.000Z",- channelId: "thread_1",- })- const reply = wakeContextRow({+ expect(plan.wakeBotUserIds).toEqual(["bot_1"])+ expect(plan.messageEvent.message.replyTo).toMatchObject({id: "reply_1",- content: "Do that",- replyToId: "ancestor_1",- seq: 9,- createdAt: "2026-08-17T00:00:03.000Z",- channelId: "thread_1",- })- const opener = wakeContextRow({- id: "opener_1",- content: "Forum incident",- seq: 2,- createdAt: "2026-08-17T00:00:00.000Z",- channelId: "forum_1",- })- mockListWakeContextMessagesBefore.mockResolvedValue({- messages: [recentHuman, ancestor, reply],- hasMore: true,- })- mockGetWakeContextMessageInScope.mockImplementation(async (_db, id) => ({- reply_1: reply,- ancestor_1: ancestor,- opener_1: opener,- })[id] ?? null)-- const plan = await planCommittedMessage({} as never, "msg_1")-- expect(mockListWakeContextMessagesBefore).toHaveBeenCalledWith({}, {- channelId: "thread_1",- beforeSeq: 10,- limit: 6,- })- expect(mockGetWakeContextMessageInScope).toHaveBeenCalledWith(- {},- "opener_1",- { channelId: "forum_1" },- )- expect(plan.wakeGateInput.conversation).toEqual({- available: true,- truncated: true,- messages: [- expect.objectContaining({- text: "Forum incident",- author: { kind: "human", handle: "Private Human Name#1234" },- roles: ["thread_opener"],- }),- expect.objectContaining({- text: "Earlier human context",- author: { kind: "human", handle: "Private Human Name#1234" },- roles: ["recent"],- }),- expect.objectContaining({- text: "Original assignment",- author: { kind: "bot", handle: "Helper#0002" },- roles: ["reply_ancestor", "recent"],- }),- expect.objectContaining({- text: "Do that",- author: { kind: "human", handle: "Private Human Name#1234" },- roles: ["immediately_previous", "reply_target", "recent"],- }),- ],- })- const serialized = JSON.stringify(plan.wakeGateInput.conversation)- expect(serialized).not.toContain("human_1")- expect(serialized).toContain("Private Human Name#1234")- })-- it("orders equal-time conversation entries by sequence and then id", async () => {- const createdAt = "2026-08-17T00:00:00.000Z"- mockListWakeContextMessagesBefore.mockResolvedValue({- messages: [- wakeContextRow({ id: "context_z", content: "seq two", seq: 2, createdAt }),- wakeContextRow({ id: "context_b", content: "seq one id b", seq: 1, createdAt }),- wakeContextRow({ id: "context_a", content: "seq one id a", seq: 1, createdAt }),- ],- hasMore: false,- })-- const plan = await planCommittedMessage({} as never, "msg_1")-- expect(plan.wakeGateInput.conversation.messages.map(({ text }) => text)).toEqual([- "seq one id a",- "seq one id b",- "seq two",- ])- })-- it("fails open to empty context when a context-only lookup fails", async () => {- mockListWakeContextMessagesBefore.mockRejectedValue(new Error("D1 context unavailable"))-- const plan = await planCommittedMessage({} as never, "msg_1")-- expect(plan.wakeGateInput.conversation).toEqual({- available: false,- messages: [],- truncated: false,+ authorName: "Bot",+ text: "previous message",})- expect(mockLogWarn).toHaveBeenCalledWith(- "committed_message_jev_context_failed_open",- { messageId: "msg_1" },- )- })-- it("keeps the raw bot handle when it co-occurs with @everyone", async () => {- mockGetMessage.mockResolvedValue({- ...message,- content: "@everyone @Bot#0001 please investigate",- mentionType: "everyone",- })- mockListAttention.mockResolvedValue([{ userId: "bot_1", kind: "mention" }])-- const plan = await planCommittedMessage({} as never, "msg_1")-- expect(plan.wakeGateInput.message.text).toBe("@everyone @Bot#0001 please investigate")- expect(plan.wakeGateInput.candidates).toEqual([- expect.objectContaining({- botUserId: "bot_1",- }),- ])- expect(JSON.stringify(plan.wakeGateInput)).not.toContain("directlyMentioned")- expect(JSON.stringify(plan.wakeGateInput)).not.toContain("isReplyTarget")- expect(JSON.stringify(plan.wakeGateInput)).not.toContain("broadcastMention")})it("keeps forum-thread participants, mention-only attention, and parent access distinct", async () => {@@ -733,7 +549,6 @@ describe("dispatchCommittedMessage", () => {mockGetMessage.mockResolvedValue(message)mockGetChannel.mockResolvedValue(channel)mockGetWakeContextMessageInScope.mockResolvedValue(null)- mockListWakeContextMessagesBefore.mockResolvedValue({ messages: [], hasMore: false })mockGetMessageClientNonceForDelivery.mockResolvedValue("nonce_1")mockListAttachments.mockResolvedValue([])mockListAttention.mockResolvedValue([])@@ -743,7 +558,6 @@ describe("dispatchCommittedMessage", () => {)mockResolveEligibility.mockResolvedValue(new Map())mockFindWakeCandidates.mockResolvedValue([])- mockSelectJevWakeCandidates.mockImplementation(async (input) => input.candidates)mockSendMessageDeliveryBatch.mockResolvedValue(undefined)mockEnqueueQueueTasks.mockResolvedValue(undefined)})@@ -857,7 +671,7 @@ describe("dispatchCommittedMessage", () => {})})- it("enqueues deterministic candidates when the gate unexpectedly rejects", async () => {+ it("enqueues eligible candidates directly", async () => {mockResolveRecipients.mockResolvedValue(["author_1", "bot_1"])mockResolveEligibility.mockResolvedValue(new Map([["bot_1", state()]]))mockFindWakeCandidates.mockResolvedValue([{@@ -868,55 +682,14 @@ describe("dispatchCommittedMessage", () => {machineId: "m1",runtime: "codex",}])- mockSelectJevWakeCandidates.mockRejectedValue(new Error("unexpected"))-await dispatchCommittedMessage({} as never, "msg_1")expect(mockEnqueueQueueTasks).toHaveBeenCalledWith([{ version: 1, kind: "bot-wake", messageId: "msg_1", botUserId: "bot_1" },])- expect(mockLogWarn).toHaveBeenCalledWith(- "committed_message_jev_gate_failed_open",- { messageId: "msg_1" },- )- })-- it("starts browser delivery and mobile push without waiting for JEV", async () => {- let releaseGate!: (value: unknown[]) => void- mockResolveRecipients.mockResolvedValue(["author_1", "u_all", "bot_1"])- mockResolveEligibility.mockResolvedValue(new Map([- ["u_all", state()],- ["bot_1", state()],- ]))- mockFindWakeCandidates.mockResolvedValue([{- botUserId: "bot_1",- name: "Bot",- discriminator: "0001",- instruction: "",- machineId: "m1",- runtime: "codex",- }])- mockSelectJevWakeCandidates.mockReturnValue(new Promise((resolve) => {- releaseGate = resolve- }))-- const work = dispatchCommittedMessage({} as never, "msg_1")- await vi.waitFor(() => {- expect(mockSendMessageDeliveryBatch).toHaveBeenCalledOnce()- expect(mockEnqueueQueueTasks).toHaveBeenCalledWith([- { version: 1, kind: "mobile-push", messageId: "msg_1", userId: "u_all" },- { version: 1, kind: "mobile-push", messageId: "msg_1", userId: "bot_1" },- ])- })- expect(mockEnqueueQueueTasks).toHaveBeenCalledTimes(1)-- releaseGate([])- await work- expect(mockEnqueueQueueTasks).toHaveBeenNthCalledWith(2, [])})- it("starts browser delivery and mobile push without waiting for JEV context", async () => {- let releaseContext!: (value: { messages: []; hasMore: false }) => void+ it("dispatches browser, mobile push, and bot wakes concurrently", async () => {mockResolveRecipients.mockResolvedValue(["author_1", "u_all", "bot_1"])mockResolveEligibility.mockResolvedValue(new Map([["u_all", state()],@@ -930,26 +703,16 @@ describe("dispatchCommittedMessage", () => {machineId: "m1",runtime: "codex",}])- mockListWakeContextMessagesBefore.mockReturnValue(new Promise((resolve) => {- releaseContext = resolve- }))-- const work = dispatchCommittedMessage({} as never, "msg_1")- await vi.waitFor(() => {- expect(mockSendMessageDeliveryBatch).toHaveBeenCalledOnce()- expect(mockEnqueueQueueTasks).toHaveBeenCalledWith([- { version: 1, kind: "mobile-push", messageId: "msg_1", userId: "u_all" },- { version: 1, kind: "mobile-push", messageId: "msg_1", userId: "bot_1" },- ])- })- expect(mockEnqueueQueueTasks).toHaveBeenCalledTimes(1)- expect(mockSelectJevWakeCandidates).not.toHaveBeenCalled()+ await dispatchCommittedMessage({} as never, "msg_1")- releaseContext({ messages: [], hasMore: false })- await work- expect(mockSelectJevWakeCandidates).toHaveBeenCalledOnce()+ expect(mockSendMessageDeliveryBatch).toHaveBeenCalledOnce()+ expect(mockEnqueueQueueTasks).toHaveBeenNthCalledWith(1, [+ { version: 1, kind: "mobile-push", messageId: "msg_1", userId: "u_all" },+ { version: 1, kind: "mobile-push", messageId: "msg_1", userId: "bot_1" },+ ])expect(mockEnqueueQueueTasks).toHaveBeenNthCalledWith(2, [{ version: 1, kind: "bot-wake", messageId: "msg_1", botUserId: "bot_1" },])})+})diff --git a/src/web/src/lib/community/message-dispatcher.ts b/src/web/src/lib/community/message-dispatcher.tsindex f10ab721f..f8c568e32 100644--- a/src/web/src/lib/community/message-dispatcher.ts+++ b/src/web/src/lib/community/message-dispatcher.ts@@ -1,7 +1,6 @@import { getCloudflareContext } from "@opennextjs/cloudflare"import {deriveCommunityDeliveryOperationId,- formatHandle,reachIsParticipantSet,WS_EVENTS,createLogger,@@ -16,150 +15,9 @@ import {import { mapMessageForWs } from "./message-payload"import { sendMessageDeliveryBatch } from "./message-delivery-transport"import { enqueueQueueTasks } from "./queue-producer"-import {- selectJevWakeCandidates,- type JevWakeGateInput,-} from "./jev-wake-gate"import { attachmentThumbnailUrl, attachmentUrl } from "./storage"const log = createLogger({ service: "committed-message-dispatcher" })-const RECENT_WAKE_CONTEXT_MESSAGES = 6--type WakeContextRow = Awaited<ReturnType<- typeof queries.communityMessage.getWakeContextMessageInScope->>--type WakeContextRole = JevWakeGateInput["conversation"]["messages"][number]["roles"][number]--type WakeContextPlan = {- enabled: boolean- channelId: string- beforeSeq: number- parentChannelId: string | null- parentMessageId: string | null- replyTarget: WakeContextRow-}--function buildWakeConversation(- recent: NonNullable<WakeContextRow>[],- replyTarget: WakeContextRow,- replyAncestor: WakeContextRow,- threadOpener: WakeContextRow,- recentTruncated: boolean,-): JevWakeGateInput["conversation"] {- const entries = new Map<string, {- row: NonNullable<WakeContextRow>- roles: Set<WakeContextRole>- priority: number- }>()- const add = (- row: WakeContextRow,- role: WakeContextRole,- priority: number,- ) => {- if (!row) return- const existing = entries.get(row.id)- if (existing) {- existing.roles.add(role)- existing.priority = Math.min(existing.priority, priority)- return- }- entries.set(row.id, { row, roles: new Set([role]), priority })- }-- for (const row of recent) add(row, "recent", 3)- const immediatelyPrevious = [...recent].sort((left, right) =>- left.createdAt.localeCompare(right.createdAt)- || left.seq - right.seq- || left.id.localeCompare(right.id),- ).at(-1) ?? null- add(immediatelyPrevious, "immediately_previous", 0)- add(threadOpener, "thread_opener", 2)- add(replyAncestor, "reply_ancestor", 1)- add(replyTarget, "reply_target", 0)-- const ordered = [...entries.values()].sort((left, right) =>- left.row.createdAt.localeCompare(right.row.createdAt)- || left.row.seq - right.row.seq- || left.row.id.localeCompare(right.row.id),- )- const roleOrder: WakeContextRole[] = [- "immediately_previous",- "reply_target",- "reply_ancestor",- "thread_opener",- "recent",- ]- return {- available: true,- truncated: recentTruncated,- messages: ordered.map(({ row, roles, priority }, order) => ({- text: row.content,- messageType: row.type,- author: {- kind: row.authorIsBot ? "bot" : "human",- handle: formatHandle(row.authorName, row.authorDiscriminator),- },- roles: roleOrder.filter((role) => roles.has(role)),- priority,- order,- })),- }-}--function emptyWakeConversation(): JevWakeGateInput["conversation"] {- return { available: true, messages: [], truncated: false }-}--async function loadWakeConversation(- db: Database,- messageId: string,- plan: WakeContextPlan,-): Promise<JevWakeGateInput["conversation"]> {- if (!plan.enabled) return emptyWakeConversation()- try {- const [recentContext, threadOpener, replyAncestor] = await Promise.all([- withD1Retry(- () => queries.communityMessage.listWakeContextMessagesBefore(db, {- channelId: plan.channelId,- beforeSeq: plan.beforeSeq,- limit: RECENT_WAKE_CONTEXT_MESSAGES,- }),- { route: "message-dispatcher:wake-context-recent" },- ),- plan.parentChannelId && plan.parentMessageId- ? withD1Retry(- () => queries.communityMessage.getWakeContextMessageInScope(- db,- plan.parentMessageId!,- { channelId: plan.parentChannelId! },- ),- { route: "message-dispatcher:wake-context-opener" },- )- : Promise.resolve(null),- plan.replyTarget?.replyToId- ? withD1Retry(- () => queries.communityMessage.getWakeContextMessageInScope(- db,- plan.replyTarget!.replyToId!,- { channelId: plan.channelId },- ),- { route: "message-dispatcher:wake-context-reply-ancestor" },- )- : Promise.resolve(null),- ])- return buildWakeConversation(- recentContext.messages,- plan.replyTarget,- replyAncestor,- threadOpener,- recentContext.hasMore,- )- } catch {- log.warn("committed_message_jev_context_failed_open", { messageId })- return { ...emptyWakeConversation(), available: false }- }-}export type CommittedMessageStructuralOutcome = {/** A participant row inserted by this exact message write. */@@ -171,7 +29,6 @@ export type CommittedMessageStructuralOutcome = {export type MessageDeliveryPlan = MessageDeliveryBatch & {operationId: CommunityDeliveryOperationIdwakeBotUserIds: string[]- wakeGateInput: JevWakeGateInputpushUserIds: string[]}@@ -199,7 +56,7 @@ async function planCommittedMessageBase(db: Database,messageId: string,structural: CommittedMessageStructuralOutcome = {},-): Promise<MessageDeliveryPlan & { wakeContextPlan: WakeContextPlan }> {+): Promise<MessageDeliveryPlan> {const message = await withD1Retry(() => queries.communityMessage.getMessage(db, messageId),{ route: "message-dispatcher:message" },@@ -304,7 +161,6 @@ async function planCommittedMessageBase(const eligibleWakeCandidates = wakeCandidates.filter((candidate) => notificationSet.has(candidate.botUserId) && allowed(candidate.botUserId),)- const shouldBuildWakeContext = channel.type !== "dm" && eligibleWakeCandidates.length > 0const wakeBotUserIds = unique(eligibleWakeCandidates.map((candidate) => candidate.botUserId))const pushUserIds = unique([...unreadPlainUserIds,@@ -373,14 +229,6 @@ async function planCommittedMessageBase(}return {- wakeContextPlan: {- enabled: shouldBuildWakeContext,- channelId: message.channelId,- beforeSeq: message.seq,- parentChannelId: channel.parentChannelId,- parentMessageId: channel.parentMessageId,- replyTarget,- },operationId: await deriveCommunityDeliveryOperationId(message.id),messageId: message.id,messageEvent,@@ -389,26 +237,6 @@ async function planCommittedMessageBase(unreadMentionUserIds,mentionUserIds,wakeBotUserIds,- wakeGateInput: {- messageId: message.id,- channel: {- type: channel.type,- name: channel.name,- topic: channel.topic,- },- message: {- text: message.content,- type: message.type,- attachmentContentTypes: attachments.map((attachment) => attachment.contentType),- },- conversation: emptyWakeConversation(),- candidates: eligibleWakeCandidates.map((candidate) => ({- botUserId: candidate.botUserId,- name: candidate.name,- discriminator: candidate.discriminator,- instruction: candidate.instruction,- })),- },pushUserIds,...(structural.memberAddedUserId && channel.serverId? {@@ -430,26 +258,16 @@ export async function planCommittedMessage(messageId: string,structural: CommittedMessageStructuralOutcome = {},): Promise<MessageDeliveryPlan> {- const { wakeContextPlan, ...plan } = await planCommittedMessageBase(- db,- messageId,- structural,- )- const conversation = await loadWakeConversation(db, messageId, wakeContextPlan)- return {- ...plan,- wakeGateInput: { ...plan.wakeGateInput, conversation },- }+ return planCommittedMessageBase(db, messageId, structural)}async function runCommittedMessageDispatch(db: Database,messageId: string,structural: CommittedMessageStructuralOutcome,- env: RuntimeEnv,): Promise<void> {const startedAt = Date.now()- const { wakeContextPlan, ...plan } = await planCommittedMessageBase(+ const plan = await planCommittedMessageBase(db,messageId,structural,@@ -477,24 +295,12 @@ async function runCommittedMessageDispatch(}))const browserDelivery = sendMessageDeliveryBatch(browserBatch, plan.operationId)const pushDelivery = enqueueQueueTasks(pushTasks)- const botWake = loadWakeConversation(db, messageId, wakeContextPlan)- .then((conversation) => selectJevWakeCandidates({- ...plan.wakeGateInput,- conversation,- }, env))- .catch(() => {- log.warn("committed_message_jev_gate_failed_open", { messageId })- return plan.wakeGateInput.candidates- })- .then(async (candidates) => {- await enqueueQueueTasks(candidates.map((candidate) => ({- version: 1 as const,- kind: "bot-wake" as const,- messageId: plan.messageId,- botUserId: candidate.botUserId,- })))- return candidates.length- })+ const botWake = enqueueQueueTasks(plan.wakeBotUserIds.map((botUserId) => ({+ version: 1 as const,+ kind: "bot-wake" as const,+ messageId: plan.messageId,+ botUserId,+ }))).then(() => plan.wakeBotUserIds.length)const [browser, push, wake] = await Promise.allSettled([browserDelivery,pushDelivery,@@ -540,16 +346,14 @@ export function dispatchCommittedMessage(messageId: string,structural: CommittedMessageStructuralOutcome = {},): Promise<void> {- let env = {} as RuntimeEnvlet executionContext: ExecutionContext | undefinedtry {const cloudflare = getCloudflareContext()- env = cloudflare.envexecutionContext = cloudflare.ctx} catch {// Unit tests and non-Cloudflare callers may not expose a request context.}- const work = runCommittedMessageDispatch(db, messageId, structural, env).catch((err) => {+ const work = runCommittedMessageDispatch(db, messageId, structural).catch((err) => {log.warn("committed_message_dispatch_failed", { messageId, err: String(err) })})executionContext?.waitUntil(work)diff --git a/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts b/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.tsindex 4cfa44d6b..c696d9073 100644--- a/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts+++ b/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts@@ -330,11 +330,13 @@ test("app edge fade keeps a real WebSocket outage native-aligned and Retry restoawait alice.page.screenshot({ path: testInfo.outputPath("390-bots.png") })await alice.page.emulateMedia({ reducedMotion: "reduce" })await expect.poll(() => artwork.innerHTML()).toBe(staticMarkup)+ await expect.poll(() => composer.evaluate((element) =>+ element.closest("[inert]") !== null,+ )).toBe(true)await alice.page.keyboard.press("Tab")- expect(await alice.page.evaluate(() => {- const inertRoot = document.querySelector("[inert]")- return inertRoot?.contains(document.activeElement) ?? false- })).toBe(false)+ expect(await alice.page.evaluate(() =>+ document.activeElement?.closest("[inert]") !== null,+ )).toBe(false)const mobileReconnectPath = testInfo.outputPath("390-dark-reconnecting-reduced-motion.png")await alice.page.screenshot({ path: mobileReconnectPath })await testInfo.attach("390-dark-reconnecting-reduced-motion.png", {@@ -398,7 +400,9 @@ test("app edge fade keeps a real WebSocket outage native-aligned and Retry restoawait retry.click()await expect(overlay).toHaveCount(0, { timeout: 20_000 })await expect(composer).toBeVisible()- expect(await alice.page.locator("[inert]").count()).toBe(0)+ await expect.poll(() => composer.evaluate((element) =>+ element.closest("[inert]") !== null,+ )).toBe(false)expect(authenticatedConnections).toBeGreaterThanOrEqual(2)await testInfo.attach("ws-recovery-evidence", { body: JSON.stringify({ authenticatedConnections, status: "connected", overlayRemoved: true }), contentType: "application/json" })} finally {