Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

Remove unsupported message editing (#1085)

Gustavo Ye158c4942e790
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.ts
index 5e0d819d1..addd1753a 100644
--- a/src/shared/src/community-ws-events.ts
+++ b/src/shared/src/community-ws-events.ts
@@ -59,15 +59,6 @@ const communityMessageUpdatedSchema = z.strictObject({
botCreation: BotCreationPayloadSchema.optional(),
}).refine((event) => event.approval !== undefined || event.botCreation !== undefined)
-const communityMessageEditedSchema = z.strictObject({
- type: z.literal("community:message.edited"),
- channelId: string,
- messageId: string,
- content: string,
- parentChannelId: string.optional(),
- serverId: string.optional(),
-}).refine((event) => event.parentChannelId === undefined || event.serverId !== undefined)
-
const communityReactionAddSchema = z.strictObject({
type: z.literal("community:reaction.add"),
channelId: string,
@@ -467,7 +458,6 @@ const communityBotPiiSchema = z.strictObject({
const commonCommunityEventSchemas = [
communityBotPiiSchema,
communityMessageUpdatedSchema,
- communityMessageEditedSchema,
communityReactionAddSchema,
communityReactionRemoveSchema,
communityPinAddSchema,
@@ -535,33 +525,8 @@ export function communityWsEventSchemaForContract(contract: CommunityContract) {
return contract === 3 ? CommunityResourceWsEventSchema : CommunityWsEventSchema
}
-type InferredCommunityWsEvent = z.infer<typeof CommunityWsEventDiscriminatedSchema>
-type InferredCommunityMessageEdited = Extract<
- InferredCommunityWsEvent,
- { type: "community:message.edited" }
->
-type CommunityMessageEditedOutput = Omit<
- InferredCommunityMessageEdited,
- "parentChannelId" | "serverId"
-> & (
- | { parentChannelId: string; serverId: string }
- | { parentChannelId?: never; serverId?: string }
-)
-type CommunityWsEventOutput =
- | Exclude<InferredCommunityWsEvent, InferredCommunityMessageEdited>
- | CommunityMessageEditedOutput
-
-export const CommunityWsEventSchema = CommunityWsEventDiscriminatedSchema.transform(
- (event): CommunityWsEventOutput => event as CommunityWsEventOutput,
-)
-
-type CommunityResourceWsEventOutput = Exclude<
- z.infer<typeof CommunityResourceWsEventDiscriminatedSchema>,
- { type: "community:message.edited" }
-> | CommunityMessageEditedOutput
-export const CommunityResourceWsEventSchema = CommunityResourceWsEventDiscriminatedSchema.transform(
- (event): CommunityResourceWsEventOutput => event as CommunityResourceWsEventOutput,
-)
+export const CommunityWsEventSchema = CommunityWsEventDiscriminatedSchema
+export const CommunityResourceWsEventSchema = CommunityResourceWsEventDiscriminatedSchema
export type CommunityLegacyWsEvent = z.infer<typeof CommunityWsEventSchema>
export type CommunityResourceWsEvent = z.infer<typeof CommunityResourceWsEventSchema>
@@ -569,7 +534,6 @@ export type CommunityWsEvent = CommunityLegacyWsEvent | CommunityResourceWsEvent
export type CommunityLegacyMessageCreate = z.infer<typeof CommunityLegacyMessageCreateSchema>
export type CommunityMessageCreate = Extract<CommunityWsEvent, { type: "community:message.create" }>
export type CommunityMessageUpdated = Extract<CommunityWsEvent, { type: "community:message.updated" }>
-export type CommunityMessageEdited = Extract<CommunityWsEvent, { type: "community:message.edited" }>
export type CommunityReactionAdd = Extract<CommunityWsEvent, { type: "community:reaction.add" }>
export type CommunityReactionRemove = Extract<CommunityWsEvent, { type: "community:reaction.remove" }>
export type CommunityPinAdd = Extract<CommunityWsEvent, { type: "community:pin.add" }>
@@ -642,7 +606,6 @@ export type CommunityBotHostFrame = BotAddedFrame | BotUpdatedFrame | BotRemoved
export const WS_EVENTS = {
MESSAGE_CREATE: "community:message.create",
MESSAGE_UPDATED: "community:message.updated",
- MESSAGE_EDITED: "community:message.edited",
REACTION_ADD: "community:reaction.add",
REACTION_REMOVE: "community:reaction.remove",
PIN_ADD: "community:pin.add",
diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.ts
index 635fdec54..f8ea522c9 100644
--- a/src/shared/src/db/queries/community/message.ts
+++ b/src/shared/src/db/queries/community/message.ts
@@ -1113,20 +1113,6 @@ export async function getMessageByAuthorAndNonce(
return parseEmbeds(row);
}
-/** Update only the author's own message content. The author predicate lives in
- * the write itself so a stale permission check cannot edit another row. */
-export async function updateOwnMessageContent(
- db: Database,
- data: { messageId: string; authorId: string; content: string }
-) {
- const [updated] = await db
- .update(communityMessage)
- .set({ content: data.content })
- .where(and(eq(communityMessage.id, data.messageId), eq(communityMessage.authorId, data.authorId)))
- .returning({ id: communityMessage.id, channelId: communityMessage.channelId, content: communityMessage.content });
- return updated ?? null;
-}
-
// No ordering guarantee — callers build a Map<id, row> and hydrate by id.
// Unknown ids silently drop out via the natural WHERE id IN (...) semantics.
//
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index f7897d951..c5c046aa7 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -594,7 +594,6 @@ export type {
export type {
CommunityMessageCreate,
CommunityMessageUpdated,
- CommunityMessageEdited,
CommunityReactionAdd,
CommunityReactionRemove,
CommunityPinAdd,
diff --git a/src/shared/test/community-ws-bundle.contract.test.ts b/src/shared/test/community-ws-bundle.contract.test.ts
index ed5a2e618..a86d98cf8 100644
--- a/src/shared/test/community-ws-bundle.contract.test.ts
+++ b/src/shared/test/community-ws-bundle.contract.test.ts
@@ -145,7 +145,7 @@ describe("community WS batch transport contract", () => {
expect(isCommunityDeliveryDigest("a".repeat(63))).toBe(false)
})
- it("round-trips one strict outer frame without entering the 49-event union", async () => {
+ it("round-trips one strict outer frame without entering the 48-event union", async () => {
const operationId = await deriveCommunityDeliveryOperationId("message-1")
const prepared = await prepareCommunityDeliveryEvents(children)
expect(prepared.ok).toBe(true)
@@ -173,7 +173,7 @@ describe("community WS batch transport contract", () => {
})
expect(isCommunityBrowserEventBatchCandidate(encoded.batch)).toBe(true)
expect(Object.values(WS_EVENTS)).not.toContain(COMMUNITY_BROWSER_EVENT_BATCH_TYPE)
- expect(Object.values(WS_EVENTS)).toHaveLength(49)
+ expect(Object.values(WS_EVENTS)).toHaveLength(48)
})
it("rejects invalid count, child, operation metadata, digest mismatch, and strict outer keys", async () => {
diff --git a/src/shared/test/community-ws-events.contract.test.ts b/src/shared/test/community-ws-events.contract.test.ts
index 60bd52625..449370dae 100644
--- a/src/shared/test/community-ws-events.contract.test.ts
+++ b/src/shared/test/community-ws-events.contract.test.ts
@@ -65,13 +65,13 @@ describe("Community browser event runtime contract", () => {
const fixtures = Object.values(communityWsEventFixtures)
const names = Object.values(WS_EVENTS).sort()
- it("locks the exact 49-event inventory", () => {
- expect(names).toHaveLength(49)
+ it("locks the exact 48-event inventory", () => {
+ expect(names).toHaveLength(48)
expect(Object.keys(communityWsEventFixtures).sort()).toEqual(names)
expect(Object.keys(requiredFixturePaths).sort()).toEqual(names)
})
- it("decodes and canonically encodes all 49 current event fixtures", () => {
+ it("decodes and canonically encodes all 48 current event fixtures", () => {
for (const fixture of fixtures) {
expect(decodeCommunityBrowserEvent(fixture)).toEqual({ ok: true, event: fixture })
const encoded = encodeCommunityBrowserEvent(fixture)
@@ -166,7 +166,7 @@ describe("Community browser event runtime contract", () => {
messageId: "message",
content: "title",
parentChannelId: "forum",
- })).toMatchObject({ reason: "invalid-payload" })
+ })).toMatchObject({ reason: "unknown-community-type" })
})
it("keeps exact and candidate guards distinct", () => {
diff --git a/src/shared/test/community-ws-events.fixtures.ts b/src/shared/test/community-ws-events.fixtures.ts
index e7bb255c1..929da93e1 100644
--- a/src/shared/test/community-ws-events.fixtures.ts
+++ b/src/shared/test/community-ws-events.fixtures.ts
@@ -52,12 +52,6 @@ export const communityWsEventFixtures = {
messageId: "message-1",
approval,
},
- "community:message.edited": {
- type: "community:message.edited",
- channelId: "channel-1",
- messageId: "message-1",
- content: "edited",
- },
"community:reaction.add": {
type: "community:reaction.add",
channelId: "channel-1",
@@ -300,7 +294,6 @@ export const communityWsEventFixtures = {
export const requiredFixturePaths = {
"community:message.create": ["channelId"],
"community:message.updated": ["approval"],
- "community:message.edited": ["messageId"],
"community:reaction.add": ["emoji"],
"community:reaction.remove": ["emoji"],
"community:pin.add": ["messageId"],
diff --git a/src/shared/test/community-ws-events.test.ts b/src/shared/test/community-ws-events.test.ts
index 24aef5086..19f78116d 100644
--- a/src/shared/test/community-ws-events.test.ts
+++ b/src/shared/test/community-ws-events.test.ts
@@ -2,7 +2,6 @@ import { describe, it, expect } from "vitest";
import { CommunityWsEventSchema, isCommunityEvent, WS_EVENTS } from "../src/community-ws-events";
import type {
CommunityChannelDelete,
- CommunityMessageEdited,
CommunityMachineCreated,
CommunityMachineUpdated,
} from "../src/community-ws-events";
@@ -51,20 +50,9 @@ describe("CommunityChannelDelete post-unit address contract", () => {
});
});
-describe("CommunityMessageEdited address contract", () => {
- it("supports forum opener, ordinary server, and DM edits", () => {
- const events: CommunityMessageEdited[] = [
- { type: "community:message.edited", channelId: "post", parentChannelId: "forum", serverId: "server", messageId: "opener", content: "new" },
- { type: "community:message.edited", channelId: "text", serverId: "server", messageId: "message", content: "new" },
- { type: "community:message.edited", channelId: "dm", messageId: "message", content: "new" },
- ];
- expect(events).toHaveLength(3);
- });
-});
-
describe("isCommunityEvent", () => {
it("accepts every exact event declared by WS_EVENTS", () => {
- expect(Object.values(WS_EVENTS)).toHaveLength(49);
+ expect(Object.values(WS_EVENTS)).toHaveLength(48);
for (const type of Object.values(WS_EVENTS)) {
expect(isCommunityEvent({ type })).toBe(true);
}
@@ -72,6 +60,7 @@ describe("isCommunityEvent", () => {
it("rejects unknown, approximate, and non-community event names", () => {
expect(isCommunityEvent({ type: "community:unknown" })).toBe(false);
+ expect(isCommunityEvent({ type: "community:message.edited" })).toBe(false);
expect(isCommunityEvent({ type: "community:message.create.extra" })).toBe(false);
expect(isCommunityEvent({ type: "foo:bar" })).toBe(false);
expect(isCommunityEvent({ type: "runtime.status" })).toBe(false);
diff --git a/src/shared/test/queries/community-message.test.ts b/src/shared/test/queries/community-message.test.ts
index cde34e594..d34e0859e 100644
--- a/src/shared/test/queries/community-message.test.ts
+++ b/src/shared/test/queries/community-message.test.ts
@@ -34,22 +34,6 @@ describe("getMessageIdentityByChannelAndSeq", () => {
});
});
-describe("updateOwnMessageContent", () => {
- it("guards the UPDATE by both message id and author id", async () => {
- const chain: any = {};
- chain.update = vi.fn(() => chain);
- chain.set = vi.fn(() => chain);
- chain.where = vi.fn(() => chain);
- chain.returning = vi.fn(() => Promise.resolve([{ id: "m1", channelId: "c1", content: "new" }]));
- const result = await messageQueries.updateOwnMessageContent(chain, {
- messageId: "m1", authorId: "u1", content: "new",
- });
- expect(chain.set).toHaveBeenCalledWith({ content: "new" });
- expect(chain.where).toHaveBeenCalledTimes(1);
- expect(result).toEqual({ id: "m1", channelId: "c1", content: "new" });
- });
-});
-
function messageRow(id: string) {
return {
id,
diff --git a/src/web/src/app/api/community/messages/[id]/route.test.ts b/src/web/src/app/api/community/messages/[id]/route.test.ts
index cd96d05ae..2d0d9af23 100644
--- a/src/web/src/app/api/community/messages/[id]/route.test.ts
+++ b/src/web/src/app/api/community/messages/[id]/route.test.ts
@@ -16,7 +16,6 @@ vi.mock("@opennextjs/cloudflare", () => ({
}))
const mockGetMessage = vi.fn()
-const mockUpdateOwnMessageContent = vi.fn()
const mockGetMessagesByIdsInScope = vi.fn()
const mockGetChannelForMember = vi.fn()
const mockGetChannelType = vi.fn()
@@ -29,13 +28,11 @@ const mockGetPrivateChannelAudienceUserIds = vi.fn()
const mockGetDM = vi.fn()
const mockGetDMPeer = vi.fn()
const mockIsBlocked = vi.fn()
-const mockAreFriends = vi.fn()
const mockListByMessageIds = vi.fn()
const mockListReactionsByMessageIds = vi.fn()
const mockGetMessageByChannelAndSeq = vi.fn()
const mockToAgentMessage = vi.fn()
const mockResolveTargetForMember = vi.fn()
-const mockFanOutToChannel = vi.fn()
const mockFanOutToServerMembers = vi.fn()
const mockBroadcastToUserSafe = vi.fn()
@@ -52,7 +49,6 @@ vi.mock("@/lib/community/resolve-ref", () => ({
resolveTargetForMember: (...a: unknown[]) => mockResolveTargetForMember(...a),
}))
vi.mock("@/lib/community/fanout", () => ({
- fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),
fanOutToServerMembers: (...a: unknown[]) => mockFanOutToServerMembers(...a),
broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),
}))
@@ -74,7 +70,6 @@ vi.mock("@alook/shared", async () => {
getMessage: (...a: unknown[]) => mockGetMessage(...a),
getMessagesByIdsInScope: (...a: unknown[]) => mockGetMessagesByIdsInScope(...a),
getMessageByChannelAndSeq: (...a: unknown[]) => mockGetMessageByChannelAndSeq(...a),
- updateOwnMessageContent: (...a: unknown[]) => mockUpdateOwnMessageContent(...a),
},
communityAgentInbox: {
toAgentMessage: (...a: unknown[]) => mockToAgentMessage(...a),
@@ -97,7 +92,6 @@ vi.mock("@alook/shared", async () => {
},
communityFriendship: {
isBlocked: (...a: unknown[]) => mockIsBlocked(...a),
- areFriends: (...a: unknown[]) => mockAreFriends(...a),
},
},
}
@@ -131,7 +125,7 @@ vi.mock("@/lib/middleware/helpers", () => {
}
})
-import { DELETE, GET, PATCH } from "./route"
+import { DELETE, GET } from "./route"
function req() {
return new NextRequest("http://localhost/api/community/messages/m1", { method: "GET" })
@@ -405,115 +399,6 @@ describe("GET /api/community/messages/[id]", () => {
})
})
-describe("PATCH /api/community/messages/[id]", () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockGetChannelType.mockResolvedValue("text")
- mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })
- mockGetMessage.mockResolvedValue({ id: "m1", channelId: "c1", authorId: "u1", content: "old" })
- mockUpdateOwnMessageContent.mockResolvedValue({ id: "m1", channelId: "c1", content: "new" })
- mockFanOutToChannel.mockResolvedValue(undefined)
- mockIsBlocked.mockResolvedValue(false)
- mockAreFriends.mockResolvedValue(true)
- })
-
- function editReq(content: unknown, bot = false) {
- return new NextRequest("http://localhost/api/community/messages/m1", {
- method: "PATCH",
- headers: { "content-type": "application/json", ...(bot ? { Authorization: "Bearer crk_x" } : {}) },
- body: JSON.stringify({ content }),
- })
- }
-
- it("updates the author's own content", async () => {
- const res = await PATCH(editReq("new"), { params: { id: "m1" } } as any)
- expect(res.status).toBe(200)
- expect(mockGetPrimaryDb).toHaveBeenCalledOnce()
- expect(mockUpdateOwnMessageContent).toHaveBeenCalledWith(primaryDb, {
- messageId: "m1", authorId: "u1", content: "new",
- })
- expect(mockFanOutToChannel).toHaveBeenCalledWith("c1", {
- type: "community:message.edited", channelId: "c1", messageId: "m1", content: "new", serverId: "s1",
- })
- })
-
- it("does not let an admin or other member edit someone else's message", async () => {
- mockGetMessage.mockResolvedValue({ id: "m1", channelId: "c1", authorId: "u2", content: "old" })
- const res = await PATCH(editReq("hijack"), { params: { id: "m1" } } as any)
- expect(res.status).toBe(403)
- expect(mockUpdateOwnMessageContent).not.toHaveBeenCalled()
- })
-
- it("resolves a real parent-forum opener to its child and omits parent data for replies", async () => {
- // Production shape: opener m1 belongs to the parent forum c1; the child
- // post row points back to it through parentMessageId.
- mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "forum" })
- mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "forum", parentChannelId: null })
- mockGetThreadChannelByParentMessage.mockResolvedValue({ id: "post_1", serverId: "s1", type: "thread", parentChannelId: "c1", parentMessageId: "m1" })
- const res = await PATCH(editReq("new"), { params: { id: "m1" } } as any)
- expect(res.status).toBe(200)
- expect(mockGetThreadChannelByParentMessage).toHaveBeenCalledWith(expect.anything(), "c1", "m1")
- expect(mockFanOutToChannel).toHaveBeenCalledWith("c1", {
- type: "community:message.edited",
- channelId: "post_1",
- parentChannelId: "c1",
- serverId: "s1",
- messageId: "m1",
- content: "new",
- })
-
- mockFanOutToChannel.mockClear()
- mockGetChannel.mockResolvedValue({ id: "post_1", serverId: "s1", type: "thread" })
- mockGetMessage.mockResolvedValue({ id: "reply_1", channelId: "post_1", authorId: "u1", content: "old" })
- mockGetChannelForMember.mockResolvedValue({ id: "post_1", serverId: "s1", type: "thread", parentChannelId: "c1" })
- mockUpdateOwnMessageContent.mockResolvedValue({ id: "reply_1", channelId: "post_1", content: "new" })
- await PATCH(
- new NextRequest("http://localhost/api/community/messages/reply_1", {
- method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify({ content: "new" }),
- }),
- { params: { id: "reply_1" } } as any,
- )
- expect(mockFanOutToChannel.mock.calls[0]?.[1]).not.toHaveProperty("parentChannelId")
- expect(mockFanOutToChannel.mock.calls[0]?.[1]).toMatchObject({ serverId: "s1" })
- })
-
- it("keeps DM edit events free of server identity", async () => {
- mockGetChannel.mockResolvedValue({ id: "dm_1", serverId: "dm-server", type: "dm" })
- mockGetMessage.mockResolvedValue({ id: "m1", channelId: "dm_1", authorId: "u1", content: "old" })
- mockUpdateOwnMessageContent.mockResolvedValue({ id: "m1", channelId: "dm_1", content: "new" })
- mockGetDM.mockResolvedValue({ id: "dm_1", channelId: "dm_1" })
- mockGetDMPeer.mockResolvedValue({ otherUserId: "u2" })
-
- const res = await PATCH(editReq("new"), { params: { id: "m1" } } as any)
- expect(res.status).toBe(200)
- expect(mockFanOutToChannel).toHaveBeenCalledWith("dm_1", {
- type: "community:message.edited",
- channelId: "dm_1",
- messageId: "m1",
- content: "new",
- })
- })
-
- it("denies editing an old DM message after unfriend", async () => {
- mockGetChannel.mockResolvedValue({ id: "dm_1", serverId: null, type: "dm" })
- mockGetMessage.mockResolvedValue({ id: "m1", channelId: "dm_1", authorId: "u1", content: "old" })
- mockGetDM.mockResolvedValue({ id: "dm_1", lastMessageAt: null, createdAt: "2026-09-22" })
- mockGetDMPeer.mockResolvedValue({ otherUserId: "u2" })
- mockAreFriends.mockResolvedValue(false)
-
- const res = await PATCH(editReq("new"), { params: { id: "m1" } } as any)
-
- expect(res.status).toBe(403)
- expect(await res.json()).toEqual({ error: "accepted friendship required" })
- expect(mockUpdateOwnMessageContent).not.toHaveBeenCalled()
- })
-
- it("rejects bot credentials and empty content", async () => {
- expect((await PATCH(editReq("new", true), { params: { id: "m1" } } as any)).status).toBe(401)
- expect((await PATCH(editReq(" "), { params: { id: "m1" } } as any)).status).toBe(400)
- })
-})
-
describe("DELETE /api/community/messages/[id]", () => {
beforeEach(() => {
vi.clearAllMocks()
diff --git a/src/web/src/app/api/community/messages/[id]/route.ts b/src/web/src/app/api/community/messages/[id]/route.ts
index e9cda30f0..eddd6afa0 100644
--- a/src/web/src/app/api/community/messages/[id]/route.ts
+++ b/src/web/src/app/api/community/messages/[id]/route.ts
@@ -3,11 +3,10 @@ import { getCloudflareContext } from "@opennextjs/cloudflare"
import { withCommunityActor } from "@/lib/middleware/community-actor"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb, getPrimaryDb } from "@/lib/db"
-import { canManageServer, queries, MAX_MESSAGE_CONTENT_LENGTH, WS_EVENTS } from "@alook/shared"
+import { canManageServer, queries, WS_EVENTS } from "@alook/shared"
import {
requireChannelMember,
requireDMAccess,
- requireDMCommunicationAccess,
requireMessageSurfaceAccess,
requireServerMember,
} from "@/lib/community/permissions"
@@ -15,7 +14,6 @@ import { resolveTargetForMember } from "@/lib/community/resolve-ref"
import { isDmTarget } from "@/lib/community/message-handler"
import {
broadcastToUserSafe,
- fanOutToChannel,
fanOutToServerMembers,
} from "@/lib/community/fanout"
import { readCommunityMessageResource } from "@/lib/community/message-payload"
@@ -61,69 +59,6 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
return handleHumanGet(db, ctx.actor.userId, ctx.params?.id, requestedCommunityContract(req.headers) ?? 1)
})
-/** PATCH /api/community/messages/[id] — edit only the caller's own text.
- * Admin status never grants edit-as-author; attachments are intentionally not
- * part of this contract. */
-export const PATCH = withCommunityActor(async (req: NextRequest, ctx) => {
- if (ctx.actor.kind !== "human") return writeError("human session required", 401)
- const messageId = ctx.params?.id
- if (!messageId || messageId === REF_PLACEHOLDER_ID) return writeError("missing message id", 400)
-
- let raw: unknown
- try {
- raw = await req.json()
- } catch {
- return writeError("invalid request body", 400)
- }
- const content = raw && typeof raw === "object" ? (raw as { content?: unknown }).content : undefined
- if (typeof content !== "string" || content.trim().length === 0) {
- return writeError("content is required", 400)
- }
- if (content.length > MAX_MESSAGE_CONTENT_LENGTH) {
- return writeError(`content must be ≤ ${MAX_MESSAGE_CONTENT_LENGTH} characters`, 400)
- }
-
- // Editing is a communication write. Authorize and mutate in a primary
- // session so a recent unfriend/block cannot be missed by replica lag.
- const db = getPrimaryDb(ctx.env.DB)
- const message = await queries.communityMessage.getMessage(db, messageId)
- if (!message) return writeError("message not found", 404)
-
- const channel = await queries.communityChannel.getChannel(db, message.channelId)
- const channelType = channel?.type ?? null
- const access = channelType === "dm"
- ? await requireDMCommunicationAccess(db, message.channelId, ctx.actor.userId)
- : await requireChannelMember(db, message.channelId, ctx.actor.userId)
- if (!access.ok) return writeError(access.error, access.status)
- if (message.authorId !== ctx.actor.userId) return writeError("only the message author may edit it", 403)
-
- const updated = await queries.communityMessage.updateOwnMessageContent(db, {
- messageId,
- authorId: ctx.actor.userId,
- content,
- })
- if (!updated) return writeError("message not found", 404)
- // Forum openers live in the PARENT forum channel; the child post points back
- // to them via parentMessageId. Resolve through the same indexed relation as
- // the tags route instead of inspecting the parent row's own parentMessageId.
- const openerThread = channelType === "forum"
- ? await queries.communityChannel.getThreadChannelByParentMessage(db, message.channelId, messageId)
- : null
- const isForumOpener = openerThread?.type === "thread"
- await fanOutToChannel(message.channelId, {
- type: WS_EVENTS.MESSAGE_EDITED,
- channelId: isForumOpener ? openerThread.id : message.channelId,
- messageId,
- content,
- ...(isForumOpener
- ? { parentChannelId: message.channelId, serverId: openerThread.serverId }
- : channelType !== "dm" && channel?.serverId
- ? { serverId: channel.serverId }
- : {}),
- })
- return writeJSON({ message: updated })
-})
-
/**
* DELETE /api/community/messages/[id] — delete one canonical forum post.
*
diff --git a/src/web/src/components/community/channels/channel-header.title-dialog.dom.test.ts b/src/web/src/components/community/channels/channel-header.title-dialog.dom.test.ts
index 4d29670df..e67f39aae 100644
--- a/src/web/src/components/community/channels/channel-header.title-dialog.dom.test.ts
+++ b/src/web/src/components/community/channels/channel-header.title-dialog.dom.test.ts
@@ -2,22 +2,9 @@ import { describe, expect, it, vi } from "vitest"
import React from "react"
import { act, fireEvent, render, screen, waitFor } from "@/test/react-dom-harness"
-vi.mock("../settings/create-dialog-shell", async () => {
- const ReactModule = await import("react")
- return {
- CreateDialogShell: ({ title, footer, children }: { title: React.ReactNode; footer?: React.ReactNode; children: React.ReactNode }) => (
- ReactModule.createElement("div", { "data-testid": "create-dialog-shell", role: "dialog" },
- ReactModule.createElement("div", { className: "text-xs font-normal text-muted-foreground" }, title),
- children,
- footer,
- )
- ),
- }
-})
-
import { ChannelHeader } from "./channel-header"
-function renderHeader(onRename?: (name: string) => void | Promise<void>, titleRename = true) {
+function renderHeader(onRename?: (name: string) => void | Promise<void>) {
return render(React.createElement(ChannelHeader, {
channel: "Original title",
kind: "thread",
@@ -25,41 +12,19 @@ function renderHeader(onRename?: (name: string) => void | Promise<void>, titleRe
onToggle: () => {},
tools: { threads: false, pinned: false, members: false },
onRename,
- titleRename,
}))
}
-describe("ChannelHeader — forum title dialog", () => {
- it("gates the title edit affordance to the creator and keeps normal threads on Rename", () => {
- let renderer = renderHeader()
- expect(screen.getByRole("banner")).toBeInTheDocument()
- expect(screen.queryByRole("button", { name: "Edit post title" })).not.toBeInTheDocument()
- renderer.unmount()
-
- renderer = renderHeader(vi.fn())
- expect(screen.getByRole("button", { name: "Edit post title" })).toBeInTheDocument()
- expect(screen.queryByRole("textbox", { name: "Post title" })).not.toBeInTheDocument()
- renderer.unmount()
-
- renderer = renderHeader(vi.fn(), false)
- expect(screen.queryByRole("button", { name: "Edit post title" })).not.toBeInTheDocument()
+describe("ChannelHeader — ordinary thread rename dialog", () => {
+ it("shows Rename only when an ordinary thread provides the action", () => {
+ const view = renderHeader()
+ expect(screen.queryByRole("button", { name: "Rename" })).not.toBeInTheDocument()
+ view.unmount()
+ renderHeader(vi.fn())
expect(screen.getByRole("button", { name: "Rename" })).toBeInTheDocument()
- renderer.unmount()
- })
-
- it("uses the shared create-dialog shell and hero input for post titles", () => {
- const renderer = renderHeader(vi.fn())
- fireEvent.click(screen.getByRole("button", { name: "Edit post title" }))
-
- expect(screen.getByRole("textbox", { name: "Post title" })).toHaveClass("text-[30px]")
- expect(screen.getByText("Edit post title", { selector: "div" }))
- .toHaveClass("text-xs", "font-normal", "text-muted-foreground")
- expect(screen.getByTestId("create-dialog-shell")).toBeInTheDocument()
-
- renderer.unmount()
})
- it("prevents duplicate saves and keeps a failed post-title draft open", async () => {
+ it("prevents duplicate saves and keeps a failed thread-name draft open", async () => {
let rejectRename!: (reason?: unknown) => void
let resolveRename!: () => void
const onRename = vi.fn(() => new Promise<void>((resolve, reject) => {
@@ -67,21 +32,21 @@ describe("ChannelHeader — forum title dialog", () => {
rejectRename = reject
}))
const renderer = renderHeader(onRename)
- fireEvent.click(screen.getByRole("button", { name: "Edit post title" }))
- fireEvent.change(screen.getByRole("textbox", { name: "Post title" }), {
+ fireEvent.click(screen.getByRole("button", { name: "Rename" }))
+ fireEvent.change(screen.getByRole("textbox", { name: "Thread name" }), {
target: { value: "New title" },
})
const save = screen.getByRole("button", { name: "Save" })
fireEvent.click(save)
fireEvent.click(save)
- fireEvent.keyDown(screen.getByRole("textbox", { name: "Post title" }), { key: "Enter" })
+ fireEvent.keyDown(screen.getByRole("textbox", { name: "Thread name" }), { key: "Enter" })
expect(onRename).toHaveBeenCalledOnce()
expect(screen.getByRole("button", { name: "Save" })).toBeDisabled()
await act(async () => { rejectRename(new Error("save failed")) })
await waitFor(() => expect(screen.getByRole("button", { name: "Save" })).toBeEnabled())
- expect(screen.getByRole("textbox", { name: "Post title" })).toHaveValue("New title")
+ expect(screen.getByRole("textbox", { name: "Thread name" })).toHaveValue("New title")
fireEvent.click(screen.getByRole("button", { name: "Save" }))
expect(onRename).toHaveBeenCalledTimes(2)
diff --git a/src/web/src/components/community/channels/channel-header.tsx b/src/web/src/components/community/channels/channel-header.tsx
index 681a40450..c33e39897 100644
--- a/src/web/src/components/community/channels/channel-header.tsx
+++ b/src/web/src/components/community/channels/channel-header.tsx
@@ -18,7 +18,6 @@ import { previewSlug } from "@/lib/community/slug-preview"
import { ServerIcon } from "@/components/community/server-icon"
import type { RightPanel } from "@/components/community/shell/panel-types"
import type { EntityKind } from "@/lib/community/models/navigation"
-import { CreateDialogShell } from "../settings/create-dialog-shell"
import { tid } from "@/lib/community/testids"
import { MessageHeader, MessageHeaderMobileBack } from "./message-header"
import { ThreadPanelActionsFrame } from "./thread-panel-actions"
@@ -89,7 +88,7 @@ export type ChannelNotifLevel = typeof USE_SERVER_DEFAULT | NotifLevel
export function ChannelHeader({
channel, rightPanel, onToggle, notifLevel, onSetNotifLevel,
kind = "text", server, mobileBack, mobileBackDisplay = "viewport", onBack, tools,
- onRename, titleRename, endActions, compactActions,
+ onRename, endActions, compactActions,
}: {
channel: string
kind?: EntityKind
@@ -98,7 +97,6 @@ export function ChannelHeader({
notifLevel?: ChannelNotifLevel
onSetNotifLevel?: (l: ChannelNotifLevel) => void
onRename?: (name: string) => void | Promise<void>
- titleRename?: boolean
server?: { id: string; name: string; icon: string | null }
mobileBack?: () => void
mobileBackDisplay?: "viewport" | "always"
@@ -139,7 +137,6 @@ export function ChannelHeader({
<HeaderRename
label={channel}
onRename={onRename}
- titleMode={titleRename}
className={mobileBack ? "hidden sm:inline-flex" : undefined}
/>
</span>
@@ -279,10 +276,9 @@ function ChannelNotifDropdown({ level, onSetLevel }: {
)
}
-function HeaderRename({ label, onRename, titleMode = false, className = "" }: {
+function HeaderRename({ label, onRename, className = "" }: {
label: string
onRename: (name: string) => void | Promise<void>
- titleMode?: boolean
className?: string
}) {
const [open, setOpen] = useAtom(useCreateAtom(false))
@@ -296,7 +292,7 @@ function HeaderRename({ label, onRename, titleMode = false, className = "" }: {
if (!open) setDraft(label)
}, [label, open, setDraft])
const draftPreview = previewSlug(draft)
- const validDraft = titleMode ? Boolean(draft.trim()) : Boolean(draftPreview.slug)
+ const validDraft = Boolean(draftPreview.slug)
const save = async () => {
if (savingRef.current) return
const trimmed = draft.trim()
@@ -319,35 +315,10 @@ function HeaderRename({ label, onRename, titleMode = false, className = "" }: {
}
return (
<>
- <Button variant="ghost" size="icon-sm" onClick={() => { setDraft(label); setOpen(true) }} className={`text-muted-foreground hover:text-foreground ${className}`} aria-label={titleMode ? "Edit post title" : "Rename"}>
+ <Button variant="ghost" size="icon-sm" onClick={() => { setDraft(label); setOpen(true) }} className={`text-muted-foreground hover:text-foreground ${className}`} aria-label="Rename">
<Pencil className="size-3.5" />
</Button>
{open && (
- titleMode ? (
- <CreateDialogShell
- onClose={() => setOpen(false)}
- title="Edit post title"
- footer={(
- <>
- <Button variant="ghost" size="sm" onClick={() => setOpen(false)} disabled={saving}>Cancel</Button>
- <Button size="sm" onClick={() => void save()} disabled={!validDraft || saving}>Save</Button>
- </>
- )}
- >
- <div className="px-5 pb-5 pt-2">
- <input
- value={draft}
- onChange={(e) => setDraft(e.target.value)}
- onKeyDown={(event) => onEnterSubmit(save)(event)}
- placeholder="Post title"
- aria-label="Post title"
- disabled={saving}
- className="w-full border-0 bg-transparent p-0 text-[30px] font-medium leading-tight tracking-tight shadow-none outline-none placeholder:font-normal placeholder:text-muted-foreground/40 focus-visible:ring-0"
- autoFocus
- />
- </div>
- </CreateDialogShell>
- ) : (
<Dialog open onOpenChange={(o) => { if (!o) setOpen(false) }}>
<DialogContent className="w-105 max-w-[calc(100vw-2rem)] p-0">
<DialogHeader className="border-b border-border px-4 py-4">
@@ -374,7 +345,6 @@ function HeaderRename({ label, onRename, titleMode = false, className = "" }: {
</DialogFooter>
</DialogContent>
</Dialog>
- )
)}
</>
)
diff --git a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts
index 40f714927..26f51deb3 100644
--- a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts
+++ b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts
@@ -322,7 +322,6 @@ vi.mock("@/hooks/community/mutations", () => ({
usePinMessage: () => ({ mutate: vi.fn() }),
useUnpinMessage: () => ({ mutate: vi.fn() }),
useToggleMark: () => vi.fn(),
- useEditMessage: () => ({ mutate: vi.fn(), mutateAsync: vi.fn() }),
useCreateThread: () => ({ mutateAsync: vi.fn() }),
useCreateForumThread: () => ({ mutateAsync: vi.fn() }),
useUpdatePostTags: () => ({ mutate: vi.fn(), isPending: false }),
diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsx
index df609a6e2..6f23fab1e 100644
--- a/src/web/src/components/community/channels/channel-route.tsx
+++ b/src/web/src/components/community/channels/channel-route.tsx
@@ -373,7 +373,6 @@ function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, rou
parentMessageId={currentChannelMeta?.parentMessageId ?? null}
parentIsForum={isForumPostChild}
routeLifecycle={routeCommitted ? routeModel.routeLifecycle : "pending"}
- childCreatorId={currentChannelMeta?.creatorId}
canRenameThread={canManageServer(myRole)}
onNavigateParent={navigateParent}
notificationLevel={(channelNotif[channelId] as ChannelNotifLevel) ?? USE_SERVER_DEFAULT}
diff --git a/src/web/src/components/community/channels/forum-child-header.contract.test.ts b/src/web/src/components/community/channels/forum-child-header.contract.test.ts
index b7f284c8c..3c22d87dc 100644
--- a/src/web/src/components/community/channels/forum-child-header.contract.test.ts
+++ b/src/web/src/components/community/channels/forum-child-header.contract.test.ts
@@ -6,16 +6,14 @@ import { fileURLToPath } from "node:url"
const componentDirectory = path.dirname(fileURLToPath(import.meta.url))
describe("forum child header wiring", () => {
- it("keeps opener/list edit affordances absent and gates title editing to the creator", () => {
+ it("keeps opener/list edit affordances absent and limits renaming to ordinary threads", () => {
const route = fs.readFileSync(path.join(componentDirectory, "channel-route.tsx"), "utf8")
const surface = fs.readFileSync(path.join(componentDirectory, "thread-channel-surface.tsx"), "utf8")
const forumView = fs.readFileSync(path.join(componentDirectory, "forum-view.tsx"), "utf8")
expect(route).toContain("<ThreadChannelSurface")
expect(surface).toContain("parentMessageId && !parentIsForum")
- expect(surface).toContain("childCreatorId === viewer.id")
- expect(surface).toContain("titleRename={parentIsForum}")
- expect(surface).toContain("messageId: parentMessageId")
+ expect(surface).toContain("!parentIsForum && canRenameThread")
expect(forumView).not.toContain("Edit post")
expect(forumView).not.toMatch(/\bonEditPost(?:\?|\s|=)/)
})
diff --git a/src/web/src/components/community/channels/text-channel-surface.dom.test.ts b/src/web/src/components/community/channels/text-channel-surface.dom.test.ts
index de2ed7941..c8570ba38 100644
--- a/src/web/src/components/community/channels/text-channel-surface.dom.test.ts
+++ b/src/web/src/components/community/channels/text-channel-surface.dom.test.ts
@@ -19,7 +19,6 @@ const mutationMocks = vi.hoisted(() => ({
pinMessage: vi.fn(),
unpinMessage: vi.fn(),
toggleMark: vi.fn(),
- editMessage: vi.fn(),
createThread: vi.fn(async () => ({ id: "thread_1" })),
uploadFile: vi.fn(),
}))
@@ -92,7 +91,6 @@ vi.mock("@/hooks/community/mutations", () => ({
usePinMessage: () => ({ mutate: mutationMocks.pinMessage }),
useUnpinMessage: () => ({ mutate: mutationMocks.unpinMessage }),
useToggleMark: () => mutationMocks.toggleMark,
- useEditMessage: () => ({ mutate: mutationMocks.editMessage }),
useCreateThread: () => ({ mutateAsync: mutationMocks.createThread }),
useUploadFile: () => ({ mutateAsync: mutationMocks.uploadFile }),
}))
diff --git a/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts b/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts
index 579aec95e..4c4a2cbba 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts
+++ b/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts
@@ -17,7 +17,6 @@ const mocks = vi.hoisted(() => ({
router: { push: vi.fn(), replace: vi.fn(), back: vi.fn() },
apiFetch: vi.fn(),
toastApiError: vi.fn(),
- editMessage: vi.fn(),
toggleReaction: vi.fn(),
acceptMessage: vi.fn(() => true),
handleTyping: vi.fn(),
@@ -39,7 +38,6 @@ vi.mock("@/hooks/community/use-channel-message-feed", () => ({
useChannelMessageFeed: vi.fn(),
}))
vi.mock("@/hooks/community/mutations", () => ({
- useEditMessage: () => ({ mutateAsync: mocks.editMessage }),
useToggleReactionApi: () => mocks.toggleReaction,
}))
vi.mock("@/components/community/channels/channel-header", () => ({
@@ -109,7 +107,6 @@ vi.mock("@/components/community/messages/message-channel-controller", () => ({
onMark: vi.fn(),
onCreateThread: vi.fn(),
onCopy: vi.fn(),
- onEdit: vi.fn(),
onRetry: vi.fn(),
onPreviewImage: vi.fn(),
},
@@ -121,7 +118,6 @@ vi.mock("@/components/community/messages/message-channel-controller", () => ({
onMark: vi.fn(),
onCreateThread: undefined,
onCopy: vi.fn(),
- onEdit: vi.fn(),
onRetry: vi.fn(),
onPreviewImage: vi.fn(),
},
@@ -180,7 +176,6 @@ function surfaceProps(overrides: Record<string, unknown> = {}) {
parentChannelId: "parent_1",
parentMessageId: "opener_1",
parentIsForum: false,
- childCreatorId: "viewer_1",
canRenameThread: true,
onNavigateParent: vi.fn(),
notificationLevel: "default" as const,
@@ -221,7 +216,6 @@ describe("ThreadChannelSurface ownership", () => {
mockedUseClaimThreadOpenerReadHandoff.mockReset()
mockedUseChannelMessageFeed.mockReturnValue(feed())
mocks.apiFetch.mockResolvedValue({})
- mocks.editMessage.mockResolvedValue({})
})
it("keeps full header fallback while split actions await layout measurement", () => {
@@ -229,7 +223,7 @@ describe("ThreadChannelSurface ownership", () => {
const props = surfaceProps({ splitActions, layoutPending: true, parentIsForum: true })
const renderer = render(React.createElement(ThreadChannelSurface, props))
expect(mockedChannelHeader).toHaveBeenLastCalledWith(expect.objectContaining({
- mobileBack: props.onNavigateParent, compactActions: false, onRename: expect.any(Function),
+ mobileBack: props.onNavigateParent, compactActions: false, onRename: undefined,
endActions: expect.anything(),
}), undefined)
renderer.rerender(React.createElement(ThreadChannelSurface, { ...props, layoutPending: false }))
@@ -238,7 +232,7 @@ describe("ThreadChannelSurface ownership", () => {
}), undefined)
renderer.rerender(React.createElement(ThreadChannelSurface, { ...props, layoutPending: false, splitActions: undefined }))
expect(mockedChannelHeader).toHaveBeenLastCalledWith(expect.objectContaining({
- mobileBack: props.onNavigateParent, compactActions: false, onRename: expect.any(Function),
+ mobileBack: props.onNavigateParent, compactActions: false, onRename: undefined,
endActions: undefined,
}), undefined)
renderer.unmount()
@@ -441,7 +435,6 @@ describe("ThreadChannelSurface ownership", () => {
mobileBack: props.onNavigateParent,
}))
expect(headerProps).toEqual(expect.objectContaining({
- titleRename: false,
onRename: expect.any(Function),
}))
@@ -478,39 +471,12 @@ describe("ThreadChannelSurface ownership", () => {
expect(renderer!.container.querySelector('[data-manage-dialog="true"]')).toBeInTheDocument()
})
- it("uses the forum opener-message rename path only for the post creator", async () => {
- act(() => {
- render(renderSurface({ parentIsForum: true, channelName: "Post title" }))
- })
- let headerProps = mockedChannelHeader.mock.calls.at(-1)![0]
- expect(headerProps).toEqual(expect.objectContaining({
- channel: "Post title",
- kind: "thread",
- titleRename: true,
- onRename: expect.any(Function),
- }))
- expect(mockedMessageList.mock.calls.at(-1)![0].hero).toBeUndefined()
-
- await act(async () => {
- await headerProps.onRename?.("Renamed post")
- })
- expect(mocks.editMessage).toHaveBeenCalledWith({
- serverId: "server_1",
- channelId: "parent_1",
- messageId: "opener_1",
- content: "Renamed post",
- forumChannelId: "parent_1",
- forumThreadId: "thread_1",
- })
-
- act(() => {
- render(renderSurface({ parentIsForum: true, childCreatorId: "other_user" }))
- })
- headerProps = mockedChannelHeader.mock.calls.at(-1)![0]
- expect(headerProps.onRename).toBeUndefined()
+ it("keeps forum title editing absent even for the post creator", () => {
+ act(() => { render(renderSurface({ parentIsForum: true, channelName: "Post title" })) })
+ expect(mockedChannelHeader.mock.calls.at(-1)![0].onRename).toBeUndefined()
})
- it("preserves rename errors for regular threads and forum posts", async () => {
+ it("preserves rename errors for regular threads", async () => {
const threadError = new Error("thread rename failed")
mocks.apiFetch.mockRejectedValueOnce(threadError)
act(() => {
@@ -520,13 +486,6 @@ describe("ThreadChannelSurface ownership", () => {
await expect(threadRename?.("Broken thread")).rejects.toBe(threadError)
expect(mocks.toastApiError).toHaveBeenCalledWith(threadError, "Failed to rename")
- const postError = new Error("post rename failed")
- mocks.editMessage.mockRejectedValueOnce(postError)
- act(() => {
- render(renderSurface({ parentIsForum: true }))
- })
- const postRename = mockedChannelHeader.mock.calls.at(-1)![0].onRename
- await expect(postRename?.("Broken post")).rejects.toBe(postError)
- expect(mocks.toastApiError).toHaveBeenCalledWith(postError, "Failed to edit post")
+
})
})
diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsx
index 52768f1e0..d01d9be4e 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.tsx
+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx
@@ -7,7 +7,7 @@ import { useCommunityRouter } from "@/contexts/community/module-route"
import { toastApiError, apiFetch } from "@/lib/api/client"
import { useBreakpoint } from "@/hooks/use-mobile"
import { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"
-import { useEditMessage, useToggleReactionApi } from "@/hooks/community/mutations"
+import { useToggleReactionApi } from "@/hooks/community/mutations"
import { ChannelHeader, type ChannelNotifLevel } from "@/components/community/channels/channel-header"
import { ChannelShell } from "@/components/community/channels/channel-shell"
import { CommunityPanel } from "@/components/community/shell/community-panel"
@@ -47,7 +47,6 @@ export function ThreadChannelSurface({
parentMessageId,
parentIsForum,
threadOpenerHandoff,
- childCreatorId,
canRenameThread,
onNavigateParent,
notificationLevel,
@@ -76,7 +75,6 @@ export function ThreadChannelSurface({
parentMessageId: string | null
parentIsForum: boolean
threadOpenerHandoff?: ThreadOpenerReadHandoff | null
- childCreatorId?: string | null
canRenameThread: boolean
onNavigateParent: () => void
notificationLevel: ChannelNotifLevel
@@ -109,7 +107,6 @@ export function ThreadChannelSurface({
viewerName: viewer.name,
viewerDiscriminator: viewer.discriminator,
})
- const { mutateAsync: editMessageAsync } = useEditMessage()
const toggleReactionApi = useToggleReactionApi()
const toggleOpenerReaction = useCallback((emoji: string) => {
if (!parentChannelId || !parentMessageId) return
@@ -142,23 +139,7 @@ export function ThreadChannelSurface({
setRightPanel((current) => current === panel ? null : panel)
}, [setRightPanel])
const openPinned = useCallback(() => setRightPanel("pinned"), [setRightPanel])
- const rename = parentIsForum && parentChannelId && parentMessageId && childCreatorId === viewer.id
- ? async (name: string) => {
- try {
- await editMessageAsync({
- serverId,
- channelId: parentChannelId,
- messageId: parentMessageId,
- content: name,
- forumChannelId: parentChannelId,
- forumThreadId: channelId,
- })
- } catch (error) {
- toastApiError(error, "Failed to edit post")
- throw error
- }
- }
- : !parentIsForum && canRenameThread
+ const rename = !parentIsForum && canRenameThread
? async (name: string) => {
try {
await apiFetch(`/api/community/channels/${channelId}`, {
@@ -228,7 +209,6 @@ export function ThreadChannelSurface({
mobileBack={compactActions ? undefined : onNavigateParent}
mobileBackDisplay="always"
tools={{ threads: false }}
- titleRename={parentIsForum}
onRename={parentChannelId && !compactActions ? rename : undefined}
compactActions={compactActions}
endActions={splitActions ? (
diff --git a/src/web/src/components/community/messages/message-channel-controller-actions.test.ts b/src/web/src/components/community/messages/message-channel-controller-actions.test.ts
index 8c2d4c792..abb0546c2 100644
--- a/src/web/src/components/community/messages/message-channel-controller-actions.test.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-actions.test.ts
@@ -36,7 +36,6 @@ function setup() {
const pinMessageMutate = vi.fn()
const toggleMark = vi.fn()
const createThreadAsync = vi.fn(async () => ({ id: "thread_1" }))
- const editMessage = vi.fn()
const runAcceptedIntent = vi.fn(async () => {})
const onOpenThread = vi.fn()
const onOpenPinned = vi.fn()
@@ -75,7 +74,6 @@ function setup() {
pinMessageMutate,
toggleMark,
createThreadAsync,
- editMessage,
messageScope: { kind: "channel", id: "channel_1", serverId: "server_1" },
runAcceptedIntent,
})
@@ -90,7 +88,6 @@ function setup() {
pinMessageMutate,
toggleMark,
createThreadAsync,
- editMessage,
runAcceptedIntent,
onOpenThread,
onOpenPinned,
@@ -149,7 +146,7 @@ describe("createMessageActions", () => {
expect(harness.runAcceptedIntent).toHaveBeenCalledOnce()
})
- it("preserves pin/unpin, thread, copy, and edit guards and callbacks", async () => {
+ it("preserves pin/unpin, thread, copy guards and callbacks", async () => {
const harness = setup()
harness.actions.onPin("m1")
expect(harness.pinMessageMutate).toHaveBeenCalled()
@@ -212,39 +209,7 @@ describe("createMessageActions", () => {
...harness.messages.get()[0], content: "hello",
}])
- vi.stubGlobal("window", { prompt: vi.fn(() => "edited") })
- harness.actions.onEdit("m1")
- expect(harness.editMessage).toHaveBeenCalledWith({
- serverId: "server_1", channelId: "channel_1", messageId: "m1", content: "edited", assertActive: expect.any(Function),
- }, expect.objectContaining({ onError: expect.any(Function) }))
- const editOptions = harness.editMessage.mock.calls[0][1]
- const editFailure = new Error("edit failed")
- editOptions.onError(editFailure)
- expect(mocks.toastApiError).toHaveBeenCalledWith(editFailure, "Failed to edit message", expect.any(Function))
-
- const prompt = vi.mocked(window.prompt)
- prompt.mockReturnValueOnce(null)
- harness.actions.onEdit("m1")
- prompt.mockReturnValueOnce("")
- harness.actions.onEdit("m1")
- prompt.mockReturnValueOnce("hello")
- harness.actions.onEdit("m1")
- expect(harness.editMessage).toHaveBeenCalledOnce()
-
- harness.actions.onEdit("missing")
- harness.messages.setState(() => [{
- ...harness.messages.get()[0], authorId: "peer_1",
- }])
- harness.actions.onEdit("m1")
- harness.messages.setState(() => [{
- ...harness.messages.get()[0], authorId: "viewer_1", seq: undefined,
- }])
- harness.actions.onEdit("m1")
- harness.messages.setState(() => [{
- ...harness.messages.get()[0], seq: 4, content: "",
- }])
- harness.actions.onEdit("m1")
- expect(harness.editMessage).toHaveBeenCalledOnce()
+
})
it("reports clipboard denial once with the original view qualification", async () => {
@@ -345,7 +310,7 @@ describe("createMessageActions", () => {
})
})
- it("uses the complete visible reply body for actions and keeps edits exact", async () => {
+ it("uses the complete visible reply body for actions without changing it", async () => {
const harness = setup()
harness.messages.setState(() => [{
...harness.messages.get()[0],
@@ -367,15 +332,6 @@ describe("createMessageActions", () => {
await harness.actions.onCreateThread("m1")
expect(mocks.deriveThreadName).toHaveBeenCalledWith("@Alice Smith\n> quote\n\nbody", "general")
- vi.stubGlobal("window", { prompt: vi.fn(() => "edited") })
- harness.actions.onEdit("m1")
- expect(window.prompt).toHaveBeenCalledWith("Edit message", "@Alice Smith\n> quote\n\nbody")
- expect(harness.editMessage).toHaveBeenCalledWith({
- serverId: "server_1",
- channelId: "channel_1",
- messageId: "m1",
- content: "edited",
- assertActive: expect.any(Function),
- }, expect.objectContaining({ onError: expect.any(Function) }))
+
})
})
diff --git a/src/web/src/components/community/messages/message-channel-controller-actions.ts b/src/web/src/components/community/messages/message-channel-controller-actions.ts
index 82028b079..4aafab0d4 100644
--- a/src/web/src/components/community/messages/message-channel-controller-actions.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-actions.ts
@@ -46,7 +46,6 @@ export function createMessageActions({
pinMessageMutate,
toggleMark,
createThreadAsync,
- editMessage,
messageScope,
runAcceptedIntent,
}: {
@@ -90,10 +89,6 @@ export function createMessageActions({
name: string
assertActive?: (() => void) & { signal: AbortSignal }
}) => Promise<{ id: string }>
- editMessage: (
- input: { serverId: string; channelId: string; messageId: string; content: string; assertActive?: (() => void) & { signal: AbortSignal } },
- options?: MutationOptions,
- ) => void
messageScope: ChannelMessageScope
runAcceptedIntent: (nonce: string) => Promise<void>
}): MessageActions {
@@ -161,21 +156,6 @@ export function createMessageActions({
try { await navigator.clipboard.writeText(content); original(); toast("Copied to clipboard") }
catch (error) { if (!isAbortError(error)) toastApiError(error, "Failed to copy message", original) }
},
- onEdit: (id) => {
- const original = captureView()
- original()
- const message = getMessage(id)
- if (!message || message.authorId !== viewerUserId || message.seq === undefined) return
- const visibleContent = message.content ?? ""
- if (!visibleContent) return
- const editedContent = window.prompt("Edit message", visibleContent)
- if (!editedContent || editedContent === visibleContent) return
- const content = editedContent
- original()
- editMessage({ serverId, channelId, messageId: id, content, assertActive: original }, {
- onError: (error) => toastApiError(error, "Failed to edit message", original),
- })
- },
onRetry: (id) => {
captureView()()
const message = getMessage(id)
diff --git a/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts b/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts
index 359ede87a..9af85572e 100644
--- a/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts
@@ -28,7 +28,6 @@ type ExpectedMessageActions = {
onMark: (id: string) => void
onCreateThread: (id: string) => Promise<void>
onCopy: (id: string) => void
- onEdit: (id: string) => void
onRetry: (id: string) => void
onDismiss: (id: string) => void
onPreviewImage: (image: ImagePreview) => void
@@ -130,7 +129,6 @@ describe("MessageChannelController facade contract", () => {
"usePinMessage()",
"useUnpinMessage()",
"useToggleMark()",
- "useEditMessage()",
"useCreateThread()",
"useUploadFile()",
"useTypingUsersForScope(`ch:${channelId}`)",
diff --git a/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts b/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts
index 10bb2a35b..a1c1f4e4c 100644
--- a/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts
@@ -23,7 +23,7 @@ const mocks = vi.hoisted(() => {
}
const messageActions = {
onToggleReaction: vi.fn(), onReact: vi.fn(), onReply: vi.fn(), onPin: vi.fn(),
- onMark: vi.fn(), onCreateThread: vi.fn(async () => {}), onCopy: vi.fn(), onEdit: vi.fn(),
+ onMark: vi.fn(), onCreateThread: vi.fn(async () => {}), onCopy: vi.fn(),
onRetry: vi.fn(), onDismiss: vi.fn(), onPreviewImage: vi.fn(),
onPreviewAttachment: vi.fn(),
}
@@ -46,7 +46,6 @@ const mocks = vi.hoisted(() => {
pinMutation: vi.fn(),
unpinMutation: vi.fn(),
markMutation: vi.fn(),
- editMutation: vi.fn(),
threadMutation: vi.fn(),
uploadMutation: vi.fn(),
typingScopes: { users: [] as string[], names: [] as string[] },
@@ -97,7 +96,6 @@ vi.mock("@/hooks/community/mutations", () => ({
usePinMessage: () => { mocks.order.push("pin"); return { mutate: mocks.pinMutation } },
useUnpinMessage: () => { mocks.order.push("unpin"); return { mutate: mocks.unpinMutation } },
useToggleMark: () => { mocks.order.push("mark"); return mocks.markMutation },
- useEditMessage: () => { mocks.order.push("edit"); return { mutate: mocks.editMutation } },
useCreateThread: () => { mocks.order.push("thread"); return { mutateAsync: mocks.threadMutation } },
useUploadFile: () => { mocks.order.push("upload"); return { mutateAsync: mocks.uploadMutation } },
}))
@@ -178,8 +176,8 @@ describe("useMessageChannelController", () => {
const valueProps = props()
let renderer: ReturnType<typeof rtlRender>
act(() => { renderer = rtlRender(React.createElement(Probe, { value: valueProps })) })
- expect(mocks.order.slice(0, 12)).toEqual([
- "send", "reaction", "reaction-add", "pin", "unpin", "mark", "edit", "thread", "upload",
+ expect(mocks.order.slice(0, 11)).toEqual([
+ "send", "reaction", "reaction-add", "pin", "unpin", "mark", "thread", "upload",
"typing-users", "typing-names", "pending-store",
])
expect(mocks.typingScopes.users.length).toBeGreaterThan(0)
@@ -552,7 +550,7 @@ describe("useMessageChannelController", () => {
])
const actionKeys = [
"onToggleReaction", "onReact", "onReply", "onPin", "onMark", "onCreateThread",
- "onCopy", "onEdit", "onRetry", "onDismiss", "onPreviewImage",
+ "onCopy", "onRetry", "onDismiss", "onPreviewImage",
"onPreviewAttachment",
]
expect(Object.keys(latest.messageActions)).toEqual(actionKeys)
diff --git a/src/web/src/components/community/messages/message-channel-controller-state.ts b/src/web/src/components/community/messages/message-channel-controller-state.ts
index 4cac63a2d..ec36cef74 100644
--- a/src/web/src/components/community/messages/message-channel-controller-state.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-state.ts
@@ -28,7 +28,6 @@ import {
import {
useAddReactionApi,
useCreateThread,
- useEditMessage,
usePinMessage,
useSendMessage,
useToggleMark,
@@ -85,7 +84,6 @@ export function useMessageChannelController({
const { mutate: pinMessageMutate } = usePinMessage()
const { mutate: unpinMessageMutate } = useUnpinMessage()
const toggleMark = useToggleMark()
- const { mutate: editMessage } = useEditMessage()
const { mutateAsync: createThreadAsync } = useCreateThread()
const { mutateAsync: uploadFileAsync } = useUploadFile()
const typingUserIds = useTypingUsersForScope(`ch:${channelId}`)
@@ -232,10 +230,9 @@ export function useMessageChannelController({
pinMessageMutate,
toggleMark,
createThreadAsync,
- editMessage,
messageScope,
runAcceptedIntent,
- }), [communityRuntime, actionContext, getMessage, source.capture, serverId, channelId, viewer.id, setReplyTo, toggleReactionApi, addReactionApi, unpinMessageMutate, pinMessageMutate, toggleMark, createThreadAsync, editMessage, messageScope, runAcceptedIntent])
+ }), [communityRuntime, actionContext, getMessage, source.capture, serverId, channelId, viewer.id, setReplyTo, toggleReactionApi, addReactionApi, unpinMessageMutate, pinMessageMutate, toggleMark, createThreadAsync, messageScope, runAcceptedIntent])
const { hasMoreNewer, jumpToPresent } = feed
const acceptMessage = useCallback((
diff --git a/src/web/src/components/community/messages/message-channel-controller-types.ts b/src/web/src/components/community/messages/message-channel-controller-types.ts
index 01c281aa1..9678ddd1a 100644
--- a/src/web/src/components/community/messages/message-channel-controller-types.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-types.ts
@@ -32,7 +32,6 @@ export type MessageActions = {
onMark: (id: string) => void
onCreateThread: (id: string) => Promise<void>
onCopy: (id: string) => void
- onEdit: (id: string) => void
onRetry: (id: string) => void
onDismiss: (id: string) => void
onPreviewImage: (image: ImagePreview) => void
diff --git a/src/web/src/components/community/messages/message-list-facade.contract.test.ts b/src/web/src/components/community/messages/message-list-facade.contract.test.ts
index fde45578a..078d85518 100644
--- a/src/web/src/components/community/messages/message-list-facade.contract.test.ts
+++ b/src/web/src/components/community/messages/message-list-facade.contract.test.ts
@@ -24,7 +24,6 @@ type ExpectedMessageListProps = {
onMark?: (id: string) => void
onCreateThread?: (id: string) => void
onCopy?: (id: string) => void
- onEdit?: (id: string) => void
onRetry?: (id: string) => void
onDismiss?: (id: string) => void
onPreviewImage?: (image: ImagePreview) => void
diff --git a/src/web/src/components/community/messages/message-list-row.dom.test.ts b/src/web/src/components/community/messages/message-list-row.dom.test.ts
index 1da9b3758..b2d6417b3 100644
--- a/src/web/src/components/community/messages/message-list-row.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list-row.dom.test.ts
@@ -46,7 +46,6 @@ const callbacks = {
onMark: vi.fn(),
onCreateThread: vi.fn(),
onCopy: vi.fn(),
- onEdit: vi.fn(),
onRetry: vi.fn(),
onDismiss: vi.fn(),
onPreviewImage: vi.fn(),
@@ -111,7 +110,7 @@ describe("renderMessageListRow", () => {
expect(mockedMessageRow).toHaveBeenCalledOnce()
})
- it("projects every row identity/action prop and gates edit to the viewer", () => {
+ it("projects every supported row identity and action prop", () => {
const message = {
id: "m1",
type: "chat" as const,
@@ -145,7 +144,6 @@ describe("renderMessageListRow", () => {
onMarkId: callbacks.onMark,
onCreateThreadId: callbacks.onCreateThread,
onCopyId: callbacks.onCopy,
- onEditId: callbacks.onEdit,
onRetryId: callbacks.onRetry,
onDismissId: callbacks.onDismiss,
onJumpToId: controller.jumpTo,
@@ -164,7 +162,6 @@ describe("renderMessageListRow", () => {
controller,
0,
))
- expect(mockedMessageRow.mock.calls.at(-1)?.[0].onEditId).toBeUndefined()
expect(mockedMessageRow.mock.calls.at(-1)?.[0].onImageLoad).toBeUndefined()
})
diff --git a/src/web/src/components/community/messages/message-list-row.tsx b/src/web/src/components/community/messages/message-list-row.tsx
index 4600f2ade..c4fa30085 100644
--- a/src/web/src/components/community/messages/message-list-row.tsx
+++ b/src/web/src/components/community/messages/message-list-row.tsx
@@ -77,7 +77,6 @@ export function renderMessageListRow(
onMarkId={props.onMark}
onCreateThreadId={props.onCreateThread}
onCopyId={props.onCopy}
- onEditId={item.m.authorId === props.viewerUserId ? props.onEdit : undefined}
onRetryId={props.onRetry}
onDismissId={props.onDismiss}
onJumpToId={controller.jumpTo}
diff --git a/src/web/src/components/community/messages/message-list-types.ts b/src/web/src/components/community/messages/message-list-types.ts
index a11801c8d..88fe1a288 100644
--- a/src/web/src/components/community/messages/message-list-types.ts
+++ b/src/web/src/components/community/messages/message-list-types.ts
@@ -26,7 +26,6 @@ export type MessageListProps = {
onMark?: (id: string) => void
onCreateThread?: (id: string) => void
onCopy?: (id: string) => void
- onEdit?: (id: string) => void
onRetry?: (id: string) => void
onDismiss?: (id: string) => void
onPreviewImage?: (image: ImagePreview) => void
diff --git a/src/web/src/components/community/messages/message-menu.test.ts b/src/web/src/components/community/messages/message-menu.test.ts
index aa42961a1..c74b6f971 100644
--- a/src/web/src/components/community/messages/message-menu.test.ts
+++ b/src/web/src/components/community/messages/message-menu.test.ts
@@ -22,20 +22,12 @@ describe("messageMenuItems", () => {
expect(onShare).toHaveBeenCalledOnce()
})
- it("keeps Edit Message hidden even when the author-scoped handler is provided", () => {
- expect(messageMenuItems({}).some((it) => it.label === "Edit Message")).toBe(false)
- const onEdit = vi.fn()
- expect(messageMenuItems({ onEdit })).toEqual([])
- expect(hasMessageMenu({ onEdit })).toBe(false)
- expect(onEdit).not.toHaveBeenCalled()
- })
-
it("gives only the high-frequency actions (Reply, Share) an icon; the rest text-only", () => {
// Locked spec (uiux #14): single list; icons only on Reply + Share as
// navigation anchors; low-freq actions are text (icon slot → placeholder).
const items = messageMenuItems({
onReply: () => {}, onShare: () => {}, onAddReaction: () => {},
- onCreateThread: () => {}, onPin: () => {}, onCopy: () => {}, onEdit: () => {},
+ onCreateThread: () => {}, onPin: () => {}, onCopy: () => {},
})
const iconLabels = items.filter((it) => it.icon).map((it) => it.label)
expect(iconLabels).toEqual(["Reply", "Share as Image"])
@@ -48,7 +40,7 @@ describe("messageMenuItems", () => {
it("keeps the original row order — icons don't reorder the list (uiux #19)", () => {
const labels = messageMenuItems({
onReply: () => {}, onShare: () => {}, onAddReaction: () => {},
- onCreateThread: () => {}, onPin: () => {}, onCopy: () => {}, onEdit: () => {},
+ onCreateThread: () => {}, onPin: () => {}, onCopy: () => {},
}).map((it) => it.label)
expect(labels).toEqual(["Add Reaction", "Reply", "Create Thread", "Pin Message", "Copy Text", "Share as Image"])
expect(labels).not.toContain("sep")
diff --git a/src/web/src/components/community/messages/message-menu.tsx b/src/web/src/components/community/messages/message-menu.tsx
index f3ee42faa..a1019d9bd 100644
--- a/src/web/src/components/community/messages/message-menu.tsx
+++ b/src/web/src/components/community/messages/message-menu.tsx
@@ -31,7 +31,6 @@ export function messageMenuItems(handlers: {
marked?: boolean
onCreateThread?: () => void
onCopy?: () => void
- onEdit?: () => void
onShare?: () => void
}): Item[] {
const items: Item[] = []
diff --git a/src/web/src/components/community/messages/message-row.tsx b/src/web/src/components/community/messages/message-row.tsx
index c9d15d47b..d19dfed1d 100644
--- a/src/web/src/components/community/messages/message-row.tsx
+++ b/src/web/src/components/community/messages/message-row.tsx
@@ -32,7 +32,6 @@ export interface MessageRowProps {
onMarkId?: (id: string) => void
onCreateThreadId?: (id: string) => void
onCopyId?: (id: string) => void
- onEditId?: (id: string) => void
onRetryId?: (id: string) => void
onDismissId?: (id: string) => void
onJumpToId?: (id: string) => void
@@ -56,7 +55,7 @@ function MessageRowImpl(props: MessageRowProps) {
const {
m, viewerUserId, hoverCapable, pinned, highlighted, onOpenThread, onOpenProfile,
onToggleReactionId, onReactId, onReplyId, mentionText, onInsertMentionText, onPinId, onMarkId, onCreateThreadId,
- onCopyId, onEditId, onRetryId, onDismissId, onJumpToId, onPreviewImage, onPreviewAttachment,
+ onCopyId, onRetryId, onDismissId, onJumpToId, onPreviewImage, onPreviewAttachment,
resolveUserName, onImageLoad,
selectMode, selected, onToggleSelectId, onEnterSelectId, onShareSingleId,
} = props
@@ -79,7 +78,6 @@ function MessageRowImpl(props: MessageRowProps) {
const onMark = useCallback(() => onMarkId?.(id), [onMarkId, id])
const onCreateThread = useCallback(() => onCreateThreadId?.(id), [onCreateThreadId, id])
const onCopy = useCallback(() => onCopyId?.(id), [onCopyId, id])
- const onEdit = useCallback(() => onEditId?.(id), [onEditId, id])
const onRetry = useCallback(() => onRetryId?.(id), [onRetryId, id])
const onDismiss = useCallback(() => onDismissId?.(id), [onDismissId, id])
const onJumpReply = useCallback(() => { if (replyToId) onJumpToId?.(replyToId) }, [onJumpToId, replyToId])
@@ -110,7 +108,6 @@ function MessageRowImpl(props: MessageRowProps) {
onMark={onMarkId ? onMark : undefined}
onCreateThread={onCreateThreadId ? onCreateThread : undefined}
onCopy={onCopyId ? onCopy : undefined}
- onEdit={onEditId ? onEdit : undefined}
onRetry={onRetryId ? onRetry : undefined}
onDismiss={onDismissId ? onDismiss : undefined}
onPreviewImage={onPreviewImage}
diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsx
index 9d9d5b227..cbf6a288a 100644
--- a/src/web/src/components/community/messages/message.tsx
+++ b/src/web/src/components/community/messages/message.tsx
@@ -171,7 +171,7 @@ export function messageLinkClickUsesMenu({
function MessageImpl({
m, compact, pinned, onOpenThread, onOpenProfile, onJumpReply,
- onToggleReaction, onReact, onReply, onMentionAuthor, onPin, onMark, onCreateThread, onCopy, onEdit, onRetry, onDismiss,
+ onToggleReaction, onReact, onReply, onMentionAuthor, onPin, onMark, onCreateThread, onCopy, onRetry, onDismiss,
onPreviewImage, onPreviewAttachment, highlighted, resolveUserName, onImageLoad,
selectMode, selected, onToggleSelect, onEnterSelect, onShareSingle,
viewerUserId, hoverCapable = true,
@@ -193,7 +193,6 @@ function MessageImpl({
onMark?: () => void
onCreateThread?: () => void
onCopy?: () => void
- onEdit?: () => void
onRetry?: () => void
onDismiss?: () => void
onPreviewImage?: (image: ImagePreview) => void
@@ -291,7 +290,7 @@ function MessageImpl({
onReply, onPin, pinned,
onMark, marked: markedData?.marked ?? false,
onCreateThread: m.thread ? undefined : onCreateThread,
- onCopy, onEdit,
+ onCopy,
// Share: enter multi-select (main list) if wired, else direct single-share
// (context-sheet). Undefined only when the surface wired NEITHER.
onShare: canShare ? (onEnterSelect ?? onShareSingle) : undefined,
@@ -1045,7 +1044,6 @@ function messagePropsEqual(prev: MessageProps, next: MessageProps): boolean {
prev.onMark === next.onMark &&
prev.onCreateThread === next.onCreateThread &&
prev.onCopy === next.onCopy &&
- prev.onEdit === next.onEdit &&
prev.onRetry === next.onRetry &&
prev.onDismiss === next.onDismiss &&
prev.onPreviewImage === next.onPreviewImage &&
diff --git a/src/web/src/components/community/shell/cached-conversation-route.dom.test.tsx b/src/web/src/components/community/shell/cached-conversation-route.dom.test.tsx
index be574b863..861c0f8bb 100644
--- a/src/web/src/components/community/shell/cached-conversation-route.dom.test.tsx
+++ b/src/web/src/components/community/shell/cached-conversation-route.dom.test.tsx
@@ -38,7 +38,7 @@ vi.mock("@/hooks/community/mutations", () => ({
useSendMessage: () => ({mutateAsync: vi.fn()}), useSetChannelNotif: () => ({mutate: vi.fn()}),
useToggleReactionApi: () => vi.fn(), useAddReactionApi: () => vi.fn(),
usePinMessage: () => ({mutate: vi.fn()}), useUnpinMessage: () => ({mutate: vi.fn()}),
- useToggleMark: () => vi.fn(), useEditMessage: () => ({mutate: vi.fn()}),
+ useToggleMark: () => vi.fn(),
useCreateThread: () => ({mutateAsync: vi.fn()}), useUploadFile: () => ({mutateAsync: vi.fn()}),
}))
vi.mock("@/components/community/messages/composer", () => ({ Composer: () => <div data-testid="qualified-composer" />, ComposerSkeleton: () => null }))
diff --git a/src/web/src/hooks/community/community-ws/cache.test.ts b/src/web/src/hooks/community/community-ws/cache.test.ts
index f6524b755..2b2388bad 100644
--- a/src/web/src/hooks/community/community-ws/cache.test.ts
+++ b/src/web/src/hooks/community/community-ws/cache.test.ts
@@ -17,21 +17,20 @@ describe("community WS canonical publication and ID windows", () => {
const { client, registry } = await createCommunityQueryOwner("u_me")
ingestMessages(registry, "ch_1", [{ id: "m_1", content: "one" }])
const row = registry.collections.messages.get("m_1"), cache = pageCache([{ id: "m_1" }])
- projectCommunityWsEventToDb(client, { type: "community:message.edited", channelId: "ch_1", messageId: "missing", content: "New" })
+ projectCommunityWsEventToDb(client, { type: "community:reaction.add", channelId: "ch_1", messageId: "missing", emoji: "👍", userId: "peer" })
expect(registry.collections.messages.get("m_1")).toBe(row)
expect(registry.collections.messages.has("missing")).toBe(false)
expect(removeThreadFromCache(undefined, "missing", "missing")).toBeUndefined()
expect(removeThreadFromCache(cache, "missing", "missing")).toBe(cache)
})
- it("patches canonical approval and content while preserving non-target rows", async () => {
+ it("patches canonical approval while preserving non-target rows", async () => {
const { client, registry } = await createCommunityQueryOwner("u_me")
ingestMessages(registry, "ch_1", [{ id: "m_1", content: "one" }, { id: "m_2", content: "two" }])
const other = registry.collections.messages.get("m_2")
const profile = { id: "u_1", name: "User", discriminator: "0001", image: null, avatarVersion: 0 }
const approval = { friendshipId: "friendship_1", status: "approved" as const, waitingOn: null, otherProfile: profile, botProfile: { ...profile, id: "bot_1" } }
projectCommunityWsEventToDb(client, { type: "community:message.updated", channelId: "ch_1", messageId: "m_1", approval })
- projectCommunityWsEventToDb(client, { type: "community:message.edited", channelId: "ch_1", messageId: "m_1", content: "edited" })
- expect(registry.collections.messages.get("m_1")).toMatchObject({ content: "edited", approval })
+ expect(registry.collections.messages.get("m_1")).toMatchObject({ content: "one", approval })
expect(registry.collections.messages.get("m_2")).toBe(other)
})
it("evicts the proved opener ID across pages without changing sibling windows or page parameters", () => {
diff --git a/src/web/src/hooks/community/community-ws/message-events.dom.test.ts b/src/web/src/hooks/community/community-ws/message-events.dom.test.ts
index 0114f0e88..51e989993 100644
--- a/src/web/src/hooks/community/community-ws/message-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.dom.test.ts
@@ -6,7 +6,6 @@ import { getCapturedRuntime, seedCanonicalStream, seedCanonicalMessages, canonic
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import type {
CommunityMessageCreate,
- CommunityMessageEdited,
CommunityPinAdd,
CommunityReactionAdd,
} from "@alook/shared"
@@ -240,7 +239,7 @@ describe("useCommunityWs — message.create", () => {
},
)
- it("does not touch forum resources for ordinary text-thread create or opener edit", async () => {
+ it("does not touch forum resources for ordinary text-thread creation", async () => {
await mountHook()
seedParent("s1", "text_parent", "text")
const baseKey = communityKeys.forumSidebarThreads("s1")
@@ -266,13 +265,7 @@ describe("useCommunityWs — message.create", () => {
serverId: "s1",
parentChannelId: "text_parent",
} satisfies CommunityMessageCreate)
- capturedOnMessage!({
- type: "community:message.edited",
- channelId: "text_thread",
- messageId: "text_opener",
- content: "Text title",
- parentChannelId: "text_parent",
- } satisfies CommunityMessageEdited)
+
expect(capturedQueryClient.getQueryState(baseKey)?.isInvalidated).toBe(false)
expect([
@@ -1221,101 +1214,7 @@ describe("useCommunityWs — DM message.create", () => {
})
})
-describe("useCommunityWs — message edit refreshes forum opener summary", () => {
- it("invalidates the parent thread list for an opener edit, but not for an ordinary reply", async () => {
- await mountHook()
- seedParent("s1", "forum_1", "forum")
- const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- const opener: CommunityMessageEdited = {
- type: "community:message.edited",
- channelId: "post_1",
- messageId: "opener-post_1",
- content: "new title",
- parentChannelId: "forum_1",
- serverId: "s1",
- }
- capturedQueryClient.setQueryData(communityKeys.message("opener-post_1"), {
- id: "opener-post_1",
- content: "old title",
- })
- const allKey = communityKeys.channelMessages("forum_1")
- const bugKey = [...allKey, "tag", "bug"] as const
- const forumPage = { pages: [{ messages: [{ id: "opener-post_1", content: "old title" }] }], pageParams: [null] }
- capturedQueryClient.setQueryData(allKey, forumPage)
- capturedQueryClient.setQueryData(bugKey, forumPage)
- const sidebarKey = communityKeys.forumSidebarThreads("s1")
- seedCanonicalForumSidebar("s1")
- capturedQueryClient.setQueryData(communityKeys.threads("forum_1"), {
- parentType: "forum",
- serverId: "s1",
- parentChannelId: "forum_1",
- threads: [{ id: "post_1", name: "old title", openerMessageId: "opener-post_1" }],
- })
- capturedOnMessage!(opener)
- expect(capturedQueryClient.getQueryData<{ content: string }>(
- communityKeys.message("opener-post_1"),
- )?.content).toBe("old title")
- await vi.waitFor(() => expect(invalidateSpy).toHaveBeenCalledWith({
- queryKey: communityKeys.threads("forum_1"), exact: true,
- }))
- expect(capturedQueryClient.getQueryState(allKey)?.isInvalidated).toBe(false)
- expect(capturedQueryClient.getQueryState(bugKey)?.isInvalidated).toBe(false)
- expect(capturedQueryClient.getQueryData<{ pages: { messages: { content: string }[] }[] }>(allKey)?.pages[0].messages[0].content).toBe("old title")
- expect(capturedQueryClient.getQueryData<{ pages: { messages: { content: string }[] }[] }>(bugKey)?.pages[0].messages[0].content).toBe("old title")
- expect(canonicalMessage("opener-post_1")?.content).toBe("new title")
- expect(canonicalForumSidebar("s1").threads[0]?.title).toBe("new title")
-
- invalidateSpy.mockClear()
- capturedOnMessage!({
- type: "community:message.edited",
- channelId: "post_1",
- messageId: "reply_1",
- content: "edited reply",
- } satisfies CommunityMessageEdited)
- expect(invalidateSpy).not.toHaveBeenCalled()
- })
-
- it("patches loaded ordinary channel copies and only the matching stream scope", async () => {
- await mountHook()
- const matchingScope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }
- const otherScope = { kind: "channel" as const, id: "ch_2", serverId: "s1" }
- const message = {
- id: "m_1",
- seq: 4,
- type: "chat" as const,
- content: "old",
- }
- await act(async () => { capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
- pages: [{ messages: [message], hasMore: false }],
- pageParams: [null],
- }) })
- await act(async () => { seedCanonicalStream(matchingScope, {
- type: "wsMessage",
- message,
- }) })
- await act(async () => { seedCanonicalStream(otherScope, {
- type: "wsMessage",
- message: { ...message, id: "m_2" },
- }) })
-
- await act(async () => { capturedOnMessage!({
- type: "community:message.edited",
- channelId: "ch_1",
- messageId: "m_1",
- content: "new",
- } satisfies CommunityMessageEdited) })
-
- expect(capturedQueryClient.getQueryData<{
- pages: { messages: { content: string }[] }[]
- }>(communityKeys.channelMessages("ch_1"))?.pages[0].messages[0].content).toBe("old")
- expect(getMessageStreamState(capturedQueryClient, matchingScope).liveIds).toContain("m_1")
- expect(canonicalMessage("m_1")?.content).toBe("new")
- expect(getMessageStreamState(capturedQueryClient, otherScope).liveIds).toContain("m_2")
- expect(canonicalMessage("m_2")?.content).toBe("old")
- })
-})
-
-describe("canonical message refresh and edit ownership", () => {
+describe("canonical message refresh ownership", () => {
it("keeps the newest 500 live rows when dispatch precedes canonical publication", async () => {
const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }
getCapturedRuntime().ui.actions.setCurrentServerId(scope.serverId)
@@ -1362,57 +1261,6 @@ describe("canonical message refresh and edit ownership", () => {
expect(getMessageStreamState(capturedQueryClient, scope).liveIds).toContain(event.message.id)
expect(canonicalMessage(event.message.id)?.attachments).toEqual([{ ...attachments[0], kind: "file", size: "1.0 KB" }])
})
-
- it("refreshes only an existing live fallback and never absorbs outbox", async () => {
- await mountHook()
- const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }
- seedCanonicalMessages(scope.id, [{ id: "m1", content: "ignored" }])
- expect(getMessageStreamState(capturedQueryClient, scope).liveIds.length).toBe(0)
- await act(async () => {
- seedCanonicalStream(scope, { type: "wsMessage", message: { id: "m1", seq: 11, type: "chat", content: "original", authorId: "u1", clientNonce: "n1" } })
- getCapturedRuntime().messageStream.actions.accept(scope, { nonce: "n2", tempId: "temp_n2", message: { type: "chat", content: "pending", authorId: "u1" }, localUploads: [] })
- capturedOnMessage!({ type: "community:message.edited", channelId: scope.id, messageId: "m1", content: "refreshed" } satisfies CommunityMessageEdited)
- })
- const overlay = getMessageStreamState(capturedQueryClient, scope)
- expect(overlay.liveIds).toContain("m1")
- expect(canonicalMessage("m1")?.content).toBe("refreshed")
- expect(overlay.outboxByNonce.get("n2")?.message.content).toBe("pending")
- })
-
- it("does not refresh a live row from a peer row with the same nonce", async () => {
- await mountHook()
- const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }
- await act(async () => {
- seedCanonicalStream(scope, { type: "wsMessage", message: { id: "m1", seq: 11, type: "chat", content: "original", authorId: "u1", clientNonce: "same" } })
- seedCanonicalMessages(scope.id, [{ id: "m2", seq: 12, content: "peer", authorId: "u2", clientNonce: "same" }])
- capturedOnMessage!({ type: "community:message.edited", channelId: scope.id, messageId: "m2", content: "edited peer" } satisfies CommunityMessageEdited)
- })
- const overlay = getMessageStreamState(capturedQueryClient, scope)
- expect(overlay.liveIds).toContain("m1")
- expect(canonicalMessage("m1")?.content).toBe("original")
- expect(overlay.liveIds.includes("m2")).toBe(false)
- expect(canonicalMessage("m2")?.content).toBe("edited peer")
- })
-
- it("patches edited content across live and acknowledged sends in their canonical owner", async () => {
- await mountHook()
- const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }
- await act(async () => {
- getCapturedRuntime().messageStream.actions.accept(scope, { nonce: "n1", tempId: "temp_n1", message: { type: "chat", content: "pending", authorId: "u1" }, localUploads: [] })
- const sent = { id: "m1", seq: 11, type: "chat" as const, content: "sent", authorId: "u1", clientNonce: "n1" }
- seedCanonicalMessages(scope.id, [sent])
- seedCanonicalStream(scope, { type: "postAck", nonce: "n1", message: sent })
- seedCanonicalStream(scope, { type: "wsMessage", message: { id: "m2", seq: 12, type: "chat", content: "before", authorId: "u1", clientNonce: "n2" } })
- capturedOnMessage!({ type: "community:message.edited", channelId: scope.id, messageId: "m1", content: "outbox edit" } satisfies CommunityMessageEdited)
- capturedOnMessage!({ type: "community:message.edited", channelId: scope.id, messageId: "m2", content: "live edit" } satisfies CommunityMessageEdited)
- })
- const overlay = getMessageStreamState(capturedQueryClient, scope)
- expect(overlay.outboxByNonce.size).toBe(0)
- expect(overlay.liveIds).toContain("m1")
- expect(canonicalMessage("m1")?.content).toBe("outbox edit")
- expect(overlay.liveIds).toContain("m2")
- expect(canonicalMessage("m2")?.content).toBe("live edit")
- })
})
describe("useCommunityWs — does NOT auto-mark-read on WS message.create", () => {
diff --git a/src/web/src/hooks/community/community-ws/message-events.ts b/src/web/src/hooks/community/community-ws/message-events.ts
index 814b783ed..522d0c319 100644
--- a/src/web/src/hooks/community/community-ws/message-events.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.ts
@@ -8,7 +8,6 @@ import type {
CommunityPinRemove,
CommunityReactionAdd,
CommunityReactionRemove,
- CommunityWsEvent,
} from "@alook/shared"
import {
@@ -17,7 +16,6 @@ import {
isForumSidebarParent,
patchForumSidebarActivityExact,
} from "@/hooks/community/use-forum-sidebar-threads"
-import { reconcileForumOpenerTitle } from "@/hooks/community/forum-opener-title-reconciliation"
import { clearTypingIndicator, typingScopeKey } from "@/hooks/community/community-ws/typing"
import type { CommunityWsHandlerContext } from "@/hooks/community/community-ws/handler-context"
import { scheduleFocusedMessageGapRepair } from "@/hooks/community/community-ws/reconnect-messages"
@@ -36,11 +34,6 @@ import {
import { channelMetadataOptions } from "@/hooks/community/channel-metadata"
import { projectCommunityWsEventToDb } from "@/lib/community-db/sync"
-type CommunityMessageEdited = Extract<
- CommunityWsEvent,
- { type: "community:message.edited" }
->
-
function warmLiveForumChildOwner(
queryClient: CommunityWsHandlerContext["queryClient"],
event: CommunityMessageCreate,
@@ -189,23 +182,3 @@ export function handleMessageUpdated(
invalidateFriends(context.projection)
}
}
-
-export function handleMessageEdited(
- event: CommunityMessageEdited,
- context: CommunityWsHandlerContext,
-) {
- const { queryClient } = context
- if (event.parentChannelId) {
- if (!event.serverId) return
- void reconcileForumOpenerTitle(queryClient, {
- serverId: event.serverId,
- forumChannelId: event.parentChannelId,
- childChannelId: event.channelId,
- openerMessageId: event.messageId,
- content: event.content,
- })
- return
- }
- void event
- void context
-}
diff --git a/src/web/src/hooks/community/community-ws/registry.test.ts b/src/web/src/hooks/community/community-ws/registry.test.ts
index cea64f189..9187a78a9 100644
--- a/src/web/src/hooks/community/community-ws/registry.test.ts
+++ b/src/web/src/hooks/community/community-ws/registry.test.ts
@@ -27,7 +27,6 @@ vi.mock("./server-rail-reconciliation", () => ({ handleServerRailChanged: handle
vi.mock("./message-events", () => ({
handleMessageCreate: handlers.handleMessageCreate,
- handleMessageEdited: handlers.handleMessageEdited,
handleMessageUpdated: handlers.handleMessageUpdated,
handlePinEvent: handlers.handlePinEvent,
handleReactionEvent: handlers.handleReactionEvent,
@@ -92,7 +91,7 @@ describe("community WebSocket registry", () => {
it("has exactly one entry for each runtime event type", () => {
const eventTypes = Object.values(WS_EVENTS).sort()
const registryTypes = Object.keys(communityWsRegistry).sort()
- expect(eventTypes).toHaveLength(49)
+ expect(eventTypes).toHaveLength(48)
expect(registryTypes).toEqual(eventTypes)
})
diff --git a/src/web/src/hooks/community/community-ws/registry.ts b/src/web/src/hooks/community/community-ws/registry.ts
index 6eca5b92e..8e19e9c80 100644
--- a/src/web/src/hooks/community/community-ws/registry.ts
+++ b/src/web/src/hooks/community/community-ws/registry.ts
@@ -14,7 +14,6 @@ import type {
import { runCommunityWsProjectionTransaction } from "@/hooks/community/community-ws/projection-transaction"
import {
handleMessageCreate,
- handleMessageEdited,
handleMessageUpdated,
handlePinEvent,
handleReactionEvent,
@@ -71,7 +70,6 @@ type CommunityWsRegistry = { [T in CommunityEventType]: RegistryEntry<T> }
export const communityWsRegistry = {
"community:message.create": { handler: handleMessageCreate, reconnectPolicies: ["focused-messages", "inbox-dms"] },
"community:message.updated": { handler: handleMessageUpdated, reconnectPolicies: ["focused-messages", "friends"] },
- "community:message.edited": { handler: handleMessageEdited, reconnectPolicies: ["focused-messages", "focused-opener", "focused-threads", "all-cached-servers"] },
"community:reaction.add": { handler: handleReactionEvent, reconnectPolicies: ["focused-messages", "focused-opener"] },
"community:reaction.remove": { handler: handleReactionEvent, reconnectPolicies: ["focused-messages", "focused-opener"] },
"community:pin.add": { handler: handlePinEvent, reconnectPolicies: ["focused-messages", "focused-pins"] },
diff --git a/src/web/src/hooks/community/forum-opener-title-reconciliation.test.ts b/src/web/src/hooks/community/forum-opener-title-reconciliation.test.ts
deleted file mode 100644
index 96c9b7c43..000000000
--- a/src/web/src/hooks/community/forum-opener-title-reconciliation.test.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import { QueryClient } from "@tanstack/react-query"
-import { communityKeys } from "@/lib/query-keys"
-import { reconcileForumOpenerTitle } from "./forum-opener-title-reconciliation"
-import {
- createCommunityDbRegistry,
- registerCommunityDbRegistry,
- type CommunityDbRegistry,
-} from "@/lib/community-db/collections"
-import {
- captureCommunityLiveSnapshotToken,
- getCanonicalCommunityMessages,
- ingestServerDetail,
- publishCommunityForumSidebar,
- projectCommunityWsEventToDb,
-} from "@/lib/community-db/sync"
-import { getForumSidebarBase } from "./use-forum-sidebar-threads"
-
-const identity = {
- serverId: "server_1",
- forumChannelId: "forum_1",
- childChannelId: "post_1",
- openerMessageId: "opener_1",
- content: "Full new title",
-}
-
-let queryClient: QueryClient
-let registry: CommunityDbRegistry
-let unregister: () => void
-
-beforeEach(async () => {
- queryClient = new QueryClient()
- registry = createCommunityDbRegistry(queryClient, "viewer")
- await registry.preload()
- unregister = registerCommunityDbRegistry(registry)
-})
-
-afterEach(async () => {
- unregister()
- await registry.cleanup()
-})
-
-function seedCanonicalCaches() {
- ingestServerDetail(registry, { id: "server_1", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "viewer", categories: [{ id: "category", name: "Channels", channels: [{ id: "forum_1", name: "Forum", type: "forum", active: false, unread: false }] }] })
- publishCommunityForumSidebar(queryClient, {
- serverId: "server_1",
- channels: [{
- id: "post_1", name: "Post", parentChannelId: "forum_1",
- parentMessageId: "opener_1", activityAt: "2026-09-26T00:00:00.000Z",
- unread: false, type: "thread",
- }],
- openers: [{ id: "opener_1", channelId: "forum_1", content: "Old title", type: "chat" }],
- proof: {
- token: captureCommunityLiveSnapshotToken(queryClient),
- signal: undefined,
- },
- })
- for (const id of ["forum_1", "post_1"]) queryClient.setQueryData(communityKeys.channelMessages(id), {
- pages: [{ messages: [{ id: "opener_1" }], hasMore: false }], pageParams: [null],
- })
- queryClient.setQueryData(communityKeys.inboxUnreads(), { servers: [], dms: [] })
- queryClient.setQueryData(communityKeys.threads("forum_1"), ["post_1"])
- queryClient.setQueryData(communityKeys.forumFeed("forum_1", null), {
- pages: [{ serverId: "server_1", parentType: "forum", threads: [{ id: "post_1", openerMessageId: "opener_1", participantIds: [] }], hasMore: false }], pageParams: [null],
- })
-}
-
-describe("reconcileForumOpenerTitle", () => {
- it("uses the already published canonical opener and repairs only exact network reads", async () => {
- seedCanonicalCaches()
- const feedKey = communityKeys.forumFeed("forum_1", null)
- const cancel = vi.spyOn(queryClient, "cancelQueries")
- const invalidate = vi.spyOn(queryClient, "invalidateQueries")
-
- const windows = [communityKeys.channelMessages("forum_1"), communityKeys.channelMessages("post_1"), feedKey].map((key) => queryClient.getQueryData(key))
- projectCommunityWsEventToDb(queryClient, { type: "community:message.edited", channelId: "forum_1", messageId: "opener_1", content: identity.content })
- await reconcileForumOpenerTitle(queryClient, identity)
-
- expect(cancel).not.toHaveBeenCalled()
- expect(invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.inboxUnreads(), exact: true })
- expect(invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.threads("forum_1"), exact: true })
- expect(queryClient.getQueryState(feedKey)?.isInvalidated).toBe(false)
-
- ;[communityKeys.channelMessages("forum_1"), communityKeys.channelMessages("post_1"), feedKey].forEach((key, index) => expect(queryClient.getQueryData(key)).toBe(windows[index]))
- expect(invalidate.mock.calls).toHaveLength(2)
- expect(getForumSidebarBase(queryClient, "server_1").threads[0]?.title).toBe("Full new title")
- expect(getCanonicalCommunityMessages(queryClient)
- .find(({ id }) => id === "opener_1")?.content).toBe("Full new title")
- })
-
- it("is idempotent and leaves title caches unchanged for every mismatched identity", async () => {
- seedCanonicalCaches()
- const mismatches = [
- { ...identity, serverId: "wrong" },
- { ...identity, forumChannelId: "wrong" },
- { ...identity, childChannelId: "wrong" },
- { ...identity, openerMessageId: "wrong" },
- ]
- for (const mismatch of mismatches) {
- await reconcileForumOpenerTitle(queryClient, mismatch)
- await reconcileForumOpenerTitle(queryClient, mismatch)
- }
-
- expect(getCanonicalCommunityMessages(queryClient).find(({ id }) => id === "opener_1")?.content).toBe("Old title")
- expect(getForumSidebarBase(queryClient, "server_1").threads[0]?.title).toBe("Old title")
- })
-
- it("never rewrites a text-thread name", async () => {
- queryClient.setQueryData(communityKeys.threads("forum_1"), {
- parentType: "text",
- serverId: "server_1",
- parentChannelId: "forum_1",
- threads: [{ id: "post_1", name: "Custom thread", openerMessageId: "opener_1" }],
- })
- await reconcileForumOpenerTitle(queryClient, identity)
- expect(queryClient.getQueryData<any>(communityKeys.threads("forum_1")).threads[0].name).toBe("Custom thread")
- })
-})
diff --git a/src/web/src/hooks/community/forum-opener-title-reconciliation.ts b/src/web/src/hooks/community/forum-opener-title-reconciliation.ts
deleted file mode 100644
index e37c9c0e5..000000000
--- a/src/web/src/hooks/community/forum-opener-title-reconciliation.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-"use client"
-
-import type { QueryClient } from "@tanstack/react-query"
-import { communityKeys } from "@/lib/query-keys"
-import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotTokenCurrent, getCanonicalCommunityChannels } from "@/lib/community-db/sync"
-
-export type ForumOpenerTitleIdentity = {
- serverId: string
- forumChannelId: string
- childChannelId: string
- openerMessageId: string
- content: string
-}
-
-export async function reconcileForumOpenerTitle(queryClient: QueryClient, identity: ForumOpenerTitleIdentity) {
- const token = captureCommunityLiveSnapshotToken(queryClient)
- try { assertCommunityLiveSnapshotTokenCurrent(queryClient, token, undefined) } catch { return }
- const child = getCanonicalCommunityChannels(queryClient).find((row) => row.id === identity.childChannelId)
- if (child?.serverId !== identity.serverId
- || child.parentChannelId !== identity.forumChannelId
- || child.parentMessageId !== identity.openerMessageId) return
- await Promise.all([
- queryClient.invalidateQueries({ queryKey: communityKeys.threads(identity.forumChannelId), exact: true }),
- queryClient.invalidateQueries({ queryKey: communityKeys.inboxUnreads(), exact: true }),
- ])
-}
diff --git a/src/web/src/hooks/community/forum-preview-live-edit.dom.test.ts b/src/web/src/hooks/community/forum-preview-live-edit.dom.test.ts
deleted file mode 100644
index 7441f4222..000000000
--- a/src/web/src/hooks/community/forum-preview-live-edit.dom.test.ts
+++ /dev/null
@@ -1,209 +0,0 @@
-import { createElement, type PropsWithChildren } from "react"
-import { describe, expect, it, vi } from "vitest"
-import { act, renderHook, waitFor } from "@/test/react-dom-harness"
-import { CommunityTestProvider } from "@/test/community-owner-fixture"
-import { createCommunityQueryOwner } from "@/test/community-query-owner"
-import { dispatchCommunityWsEvent } from "./community-ws/registry"
-import { captureCommunityLiveSnapshotToken, publishCommunityForumFeed, publishCommunityMessages, publishCommunityMessageFields } from "@/lib/community-db/sync"
-import { normalizeThreadResources } from "./forum-feed-window"
-import { forumConversationEntryFixture } from "@/test/conversation-entry-fixtures"
-import { conversationEntryOptions, publishConversationEntry } from "@/lib/community/conversation-entry"
-import { communityKeys } from "@/lib/query-keys"
-
-const apiFetch = vi.hoisted(() => vi.fn())
-vi.mock("@/lib/api/client", () => ({ apiFetch }))
-vi.mock("./use-channel-panels", () => ({
- useForumTags: () => ({ data: { tags: [] }, isSuccess: true }),
-}))
-import { useForumFeed } from "./use-forum-feed"
-import { useEditMessage } from "./mutations/messages"
-
-const original = "original first body ".repeat(34)
-const edited = "edited first body with complete content ".repeat(29)
-const date = "2026-10-01T00:00:00.000Z"
-
-function channel(id: string, type: "forum" | "thread", parentMessageId: string | null = null) {
- return { id, type, serverId: "server", categoryId: null, name: id, topic: "",
- parentChannelId: type === "thread" ? "forum" : null, parentMessageId, creatorId: "author",
- position: 0, archived: false, createdAt: date, lastMessageAt: date, messageCount: 2 }
-}
-function message(id: string, channelId: string, seq: number, content: string) {
- return { id, channelId, seq, content, authorId: "author", authorName: "Ada",
- authorAvatar: "A", authorAvatarVersion: 0, createdAt: date, type: "chat" as const,
- replyToId: null, clientNonce: null, attachments: [] }
-}
-function page(contractVersion: 2 | 3, firstSeq = 1) {
- return { contractVersion, channelId: "forum", channel: channel("forum", "forum"),
- threads: [channel("post", "thread", "title"), channel("other", "thread", "other-title")],
- included: { messages: [
- message("title", "forum", 104, "Original title"),
- message("first", "post", firstSeq, original),
- message("other-title", "forum", 105, "Other title"),
- message("other-first", "other", 1, "Other original"),
- ], members: [], profiles: [], tags: [], participantCounts: [] },
- page: { hasMore: false, nextCursor: null } }
-}
-async function mount(contractVersion: 2 | 3 = 2, firstSeq = 1) {
- const owner = await createCommunityQueryOwner()
- apiFetch.mockReset()
- apiFetch.mockResolvedValue(page(contractVersion, firstSeq))
- const entry = forumConversationEntryFixture("forum", "server", true)
- const target = { channelId: "forum", serverId: "server" }
- owner.client.setQueryData(conversationEntryOptions(owner.client, target).queryKey, publishConversationEntry(owner.client, target, entry, { token: captureCommunityLiveSnapshotToken(owner.client, "forum") }))
- owner.client.setQueryData(communityKeys.forumFeed("forum", null), data => data, { updatedAt: 1 })
- function Wrapper({ children }: PropsWithChildren) {
- return createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry }, children)
- }
- const view = renderHook(() => ({ ...useForumFeed("server", "forum"), editCommand: useEditMessage() }), { wrapper: Wrapper })
- await waitFor(() => expect(view.result.current.posts.find((post) => post.id === "post")?.preview).toBe(original))
- const context = { contract: contractVersion, deliveryMode: "single" as const,
- queryClient: owner.client, communityStore: owner.runtime.ui, wsStore: owner.runtime.ws,
- sub: { channelId: "forum" }, viewerUserIdRef: { current: "viewer" },
- matchesFocus: () => false }
- function edit(channelId: string, messageId: string, content: string, title = false) {
- act(() => dispatchCommunityWsEvent({ type: "community:message.edited", serverId: "server",
- channelId, messageId, content, ...(title ? { parentChannelId: "forum" } : {}) }, context))
- }
- return { ...owner, ...view, edit, preview: (id = "post") => view.result.current.posts.find((post) => post.id === id)?.preview }
-}
-
-describe("Forum first body through the actual edited dispatcher", () => {
- it("keeps the same forum window and confirms its exact first-body preview after HTTP edit without self WS", async () => {
- const view = await mount(3, 7)
- const key = communityKeys.forumFeed("forum", null)
- const window = view.client.getQueryData(key)
- let resolve!: (value: unknown) => void
- let command!: Promise<unknown>
- apiFetch.mockImplementation((_path: string, options?: { method?: string }) => options?.method === "PATCH"
- ? new Promise(done => { resolve = done })
- : Promise.resolve(page(3, 7)))
- try {
- expect(view.registry.collections.channels.get("post")?.firstMessageId).toBe("first")
- expect(view.registry.collections.messages.get("first")?.seq).toBe(7)
- act(() => { command = view.result.current.editCommand.mutateAsync({ serverId: "server", channelId: "post", messageId: "first", content: edited }) })
- await waitFor(() => expect(resolve).toBeTypeOf("function"))
- expect(view.registry.collections.messages.get("first")?.content).toBe(edited)
- await waitFor(() => expect(view.preview()).toBe(edited))
- expect(view.client.getQueryData(key)).toBe(window)
- await act(async () => { resolve(undefined); await command })
- expect(view.registry.collections.messages.get("first")?.content).toBe(edited)
- expect(view.client.getQueryData(key)).toBe(window)
- expect(view.preview("other")).toBe("Other original")
- expect(apiFetch.mock.calls.filter(([, options]) => options?.method === "PATCH")).toHaveLength(1)
- expect(view.preview()).toBe(edited)
- } finally {
- resolve?.(undefined)
- await command?.catch(() => undefined)
- view.unmount()
- }
- })
-
- it.each(["rollback", "WS then success", "WS then failure"] as const)("keeps first-body preview under the original edit transaction: %s", async outcome => {
- const view = await mount(3, 7)
- const key = communityKeys.forumFeed("forum", null), window = view.client.getQueryData(key)
- let resolve!: (value: unknown) => void, reject!: (reason: Error) => void
- apiFetch.mockImplementation((_path: string, options?: { method?: string }) => options?.method === "PATCH"
- ? new Promise((done, fail) => { resolve = done; reject = fail }) : Promise.resolve(page(3, 7)))
- let command!: Promise<unknown>
- try {
- act(() => { command = view.result.current.editCommand.mutateAsync({ serverId: "server", channelId: "post", messageId: "first", content: edited }).catch(error => error) })
- await waitFor(() => expect(resolve).toBeTypeOf("function"))
- await waitFor(() => expect(view.preview()).toBe(edited))
- if (outcome !== "rollback") view.edit("post", "first", "newer WS content")
- await act(async () => { if (outcome === "WS then success") resolve(undefined); else reject(new Error("edit denied")); await command })
- const expected = outcome === "rollback" ? original : "newer WS content"
- await waitFor(() => expect(view.preview()).toBe(expected))
- expect(view.registry.collections.messages.get("first")?.content).toBe(expected)
- expect(view.preview("other")).toBe("Other original")
- expect(view.client.getQueryData(key)).toBe(window)
- } finally { resolve?.(undefined); await command?.catch(() => undefined); view.unmount() }
- })
-
- it("does not mirror rejected content when another HTTP field is accepted", async () => {
- const view = await mount(3, 7)
- try {
- const token = captureCommunityLiveSnapshotToken(view.client, "post")
- view.edit("post", "first", "newer WS content")
- let published = false
- act(() => { published = publishCommunityMessageFields(view.client, "first", { content: "old HTTP content", authorName: "HTTP author" }, { token }) })
- expect(published).toBe(true)
- expect(view.registry.collections.messages.get("first")?.authorName).toBe("HTTP author")
- expect(view.registry.collections.messages.get("first")?.content).toBe("newer WS content")
- await waitFor(() => expect(view.preview()).toBe("newer WS content"))
- } finally { view.unmount() }
- })
-
- it.each([{ contract: 2 as const, firstSeq: 1 }, { contract: 3 as const, firstSeq: 7 }])(
- "updates the existing full preview from contract$contract first-body identity, not a sequence guess",
- async ({ contract, firstSeq }) => {
- const view = await mount(contract, firstSeq)
- view.edit("post", "first", edited)
- expect(view.registry.collections.messages.get("first")?.content).toBe(edited)
- await waitFor(() => expect(view.preview()).toBe(edited))
- expect(view.result.current.posts.find((post) => post.id === "post")?.parent.text).toBe(edited)
- expect(view.registry.collections.messages.get("first")?.content).toBe(edited)
- expect(apiFetch).toHaveBeenCalledTimes(1)
- },
- )
-
- it("keeps later reply and title edits out of the first-body preview", async () => {
- const view = await mount()
- act(() => publishCommunityMessages(view.client, { channelId: "post",
- messages: [message("later-reply", "post", 2, "Original later reply")],
- proof: { token: captureCommunityLiveSnapshotToken(view.client, "post"), signal: undefined } }))
- view.edit("post", "later-reply", "later reply edit")
- expect(view.registry.collections.messages.get("later-reply")?.content).toBe("later reply edit")
- view.edit("post", "title", "New title", true)
- await waitFor(() => expect(view.result.current.posts.find((post) => post.id === "post")?.name).toBe("New title"))
- expect(view.preview()).toBe(original)
- expect(view.preview("other")).toBe("Other original")
- expect(apiFetch).toHaveBeenCalledTimes(1)
- })
-
- it("updates another post only through that post's known first body", async () => {
- const view = await mount()
- view.edit("other", "other-first", edited)
- expect(view.registry.collections.messages.get("other-first")?.content).toBe(edited)
- await waitFor(() => expect(view.preview("other")).toBe(edited))
- expect(view.preview()).toBe(original)
- expect(apiFetch).toHaveBeenCalledTimes(1)
- })
-
- it("retains an edited preview over the original older HTTP feed", async () => {
- const view = await mount()
- const token = captureCommunityLiveSnapshotToken(view.client, "forum")
- view.edit("post", "first", edited)
- expect(view.registry.collections.messages.get("first")?.content).toBe(edited)
- act(() => publishCommunityForumFeed(view.client, "forum",
- normalizeThreadResources("forum", page(2)), { token, signal: undefined }))
- await waitFor(() => expect(view.preview()).toBe(edited))
- expect(view.registry.collections.messages.get("first")?.content).toBe(edited)
- })
-
- it("rejects an old account response before it can rewrite preview ownership", async () => {
- const view = await mount()
- view.runtime.ws.actions.activateProfileAccount("old-account")
- const token = captureCommunityLiveSnapshotToken(view.client, "forum")
- view.runtime.ws.actions.activateProfileAccount("new-account")
- expect(() => publishCommunityForumFeed(view.client, "forum",
- normalizeThreadResources("forum", page(2)), { token, signal: undefined }))
- .toThrow(expect.objectContaining({ name: "AbortError" }))
- expect(view.preview()).toBe(original)
- })
-
- it("does not invent first-body identity from an unaddressed legacy preview", async () => {
- const view = await mount()
- act(() => publishCommunityForumFeed(view.client, "forum", normalizeThreadResources("forum", {
- serverId: "server", parentType: "forum", threads: [
- { id: "post", name: "Original title", creatorId: "author", parentMessageId: "title",
- messageCount: 2, createdAt: date, lastMessageAt: date, activityAt: date },
- ], included: { parentMessages: [{ ...message("title", "forum", 104, "Original title"), authorImage: null }],
- firstMessages: [{ channelId: "post", content: original }], tags: [], participants: [] },
- hasMore: false,
- }), { token: captureCommunityLiveSnapshotToken(view.client, "forum"), signal: undefined }))
- view.edit("post", "first", edited)
- expect(view.registry.collections.messages.get("first")?.content).toBe(edited)
- expect(view.preview()).toBe(original)
- expect(apiFetch).toHaveBeenCalledTimes(1)
- })
-})
diff --git a/src/web/src/hooks/community/message-surface-ownership.test.ts b/src/web/src/hooks/community/message-surface-ownership.test.ts
index fdbe0b571..2dc844100 100644
--- a/src/web/src/hooks/community/message-surface-ownership.test.ts
+++ b/src/web/src/hooks/community/message-surface-ownership.test.ts
@@ -44,7 +44,7 @@ describe("embedded message surface ownership", () => {
expect(materializeCanonicalMessage(transport, new Map([["m1", canonical]]))).toBe(canonical)
})
- it("publishes an empty first load once and projects WS edit/delete across every surface", async () => {
+ it("publishes an empty first load once and projects WS deletion across every surface", async () => {
const queryClient = new QueryClient()
registry = createCommunityDbRegistry(queryClient, "viewer")
await registry.preload()
@@ -137,21 +137,6 @@ describe("embedded message surface ownership", () => {
threads: ["initial"],
})
- projectCommunityWsEventToDb(queryClient, {
- type: "community:message.edited",
- serverId: "s1",
- channelId: "c1",
- messageId: "m1",
- content: "edited",
- } as CommunityWsEvent)
- expect(projectEverySurface()).toEqual({
- rows: {
- mentions: ["edited"], marked: ["edited"], pins: ["edited"], context: ["edited"],
- },
- forum: ["edited"],
- threads: ["edited"],
- })
-
projectCommunityWsEventToDb(queryClient, {
type: "community:channel.delete",
serverId: "s1",
diff --git a/src/web/src/hooks/community/mutations/message-field-owner.dom.test.tsx b/src/web/src/hooks/community/mutations/message-field-owner.dom.test.tsx
index 670ab0adf..c28e38db9 100644
--- a/src/web/src/hooks/community/mutations/message-field-owner.dom.test.tsx
+++ b/src/web/src/hooks/community/mutations/message-field-owner.dom.test.tsx
@@ -9,10 +9,8 @@ import { clearAllPersistedCaches } from "@/lib/query-persister"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { useCanonicalMessagesById } from "@/lib/community-db/projections"
import * as projections from "@/lib/community-db/projections"
-import { projectCommunityWsEventToDb } from "@/lib/community-db/sync"
import { communityKeys } from "@/lib/query-keys"
import { useMessage } from "../use-message"
-import { useEditMessage } from "./messages"
import { dispatchCommunityWsEvent } from "../community-ws/registry"
import { getCommunityRuntime } from "@/stores/community/runtime"
const api = vi.hoisted(() => vi.fn())
@@ -21,20 +19,16 @@ vi.mock("@/lib/api/client", () => ({ apiFetch: api, toastApiError: vi.fn() }))
vi.mock("@/lib/auth-client", () => { const sessionSDK = { useSession: () => ({ data: { user: { id: sdk.id } }, isPending: false, error: null }) }; return { ...sessionSDK, currentSessionViewer: () => { const value = sessionSDK.useSession(); return !value || value.isPending || value.error ? undefined : value.data?.user.id ?? null } } })
vi.mock("next/navigation", () => ({ useRouter: () => ({ refresh: vi.fn(), replace: vi.fn() }) }))
vi.mock("@tanstack/react-query-devtools", () => ({ ReactQueryDevtools: () => null }))
-let client: QueryClient, edit: ReturnType<typeof useEditMessage>
+let client: QueryClient
function Probe({ messageId = "m1" }: { messageId?: string | null }) {
- const currentClient = useQueryClient(), command = useEditMessage(); useLayoutEffect(() => { client = currentClient; edit = command })
+ const currentClient = useQueryClient(); useLayoutEffect(() => { client = currentClient })
const exact = useMessage(messageId), rows = useCanonicalMessagesById()
return <><output data-testid="exact">{exact.message?.content ?? "missing"}</output><output data-testid="canonical">{rows?.get("m1")?.content ?? "missing"}</output></>
}
function Root({ id = sdk.id, messageId }: { id?: string; messageId?: string | null }) { return <QueryProvider userId={id}><Probe messageId={messageId} /></QueryProvider> }
-const args = { serverId: "s1", channelId: "c1", messageId: "m1", content: "requested" }
async function mount() {
- let resolve!: (value: unknown) => void, reject!: (error: Error) => void
- const held = new Promise<unknown>((done, fail) => { resolve = done; reject = fail })
const seen = new Set<string>()
api.mockImplementation((path: string, options: { method?: string; authenticationAccount: string; signal?: AbortSignal }) => {
- if (options.method === "PATCH") return held
const key = `${options.authenticationAccount}:${path}`
if (seen.has(key)) return new Promise((_, fail) => options.signal?.addEventListener("abort", () => fail(new DOMException("aborted", "AbortError")), { once: true }))
seen.add(key)
@@ -42,12 +36,10 @@ async function mount() {
})
const view = render(<Root />)
await waitFor(() => expect(screen.getByTestId("canonical").textContent).toBe("original"))
- return { view, resolve, reject, original: client }
+ return { view, original: client }
}
-function command() { return edit.mutateAsync(args).catch((error) => error) }
-async function pending() { await waitFor(() => expect(api.mock.calls.some(([, options]) => options.method === "PATCH")).toBe(true)) }
beforeEach(async () => { await clearAllPersistedCaches(); api.mockReset(); sdk.id = "A" })
-describe("actual canonical message field command", () => {
+describe("canonical message identity and reaction publication", () => {
it("subscribes the exact message to its ID and selects no rows without an ID", async () => {
const subscription = vi.spyOn(projections, "useCanonicalMessagesById")
try {
@@ -62,50 +54,11 @@ describe("actual canonical message field command", () => {
expect(api.mock.calls).toHaveLength(requests)
} finally { subscription.mockRestore() }
})
- it.each(["edit", "reaction"] as const)("WS %s updates canonical facts without overwriting the exact-message ID transport", async (kind) => {
+ it("WS reactions update canonical facts without overwriting the exact-message ID transport", async () => {
const { original } = await mount(), runtime = getCommunityRuntime(original)
- act(() => dispatchCommunityWsEvent(kind === "edit"
- ? { type: "community:message.edited", messageId: "m1", channelId: "c1", content: "newer-ws" }
- : { type: "community:reaction.add", messageId: "m1", channelId: "c1", emoji: "👍", userId: "peer" },
+ act(() => dispatchCommunityWsEvent({ type: "community:reaction.add", messageId: "m1", channelId: "c1", emoji: "👍", userId: "peer" },
{ deliveryMode: "single", queryClient: original, communityStore: runtime.ui, wsStore: runtime.ws, sub: {}, viewerUserIdRef: { current: "A" }, matchesFocus: () => false }))
expect(original.getQueryData(communityKeys.message("m1"))).toBe("m1")
- if (kind === "edit") expect(screen.getByTestId("exact").textContent).toBe("newer-ws")
- else expect(getCommunityDbRegistry(original)!.collections.messages.get("m1")?.reactions).toMatchObject([{ emoji: "👍", userIds: ["peer"] }])
- })
- it("shows native optimistic content in both consumers and commits HTTP success without self WS", async () => {
- const { resolve, original } = await mount()
- let result!: Promise<unknown>; act(() => { result = command() })
- await pending()
- expect(screen.getByTestId("exact").textContent).toBe("requested")
- expect(getCommunityDbRegistry(original)!.collections.messages.get("m1")?.content).toBe("requested")
- await act(async () => { resolve(undefined); expect(await result).toBeUndefined() })
- expect(screen.getByTestId("canonical").textContent).toBe("requested")
- expect(original.getQueryData(communityKeys.message("m1"))).toBe("m1")
- })
- it.each(["success", "failure"] as const)("preserves newer WS content after command %s", async (outcome) => {
- const { resolve, reject, original } = await mount()
- let result!: Promise<unknown>; act(() => { result = command() }); await pending()
- act(() => projectCommunityWsEventToDb(original, { type: "community:message.edited", messageId: "m1", channelId: "c1", serverId: "s1", content: "newer-ws" }))
- await act(async () => { if (outcome === "success") resolve(undefined); else reject(new Error("denied")); await result })
- expect(screen.getByTestId("canonical").textContent).toBe("newer-ws")
- expect(screen.getByTestId("exact").textContent).toBe("newer-ws")
- })
- it("confirms content independently of a newer reaction event", async () => {
- const { resolve, original } = await mount()
- let result!: Promise<unknown>; act(() => { result = command() }); await pending()
- act(() => projectCommunityWsEventToDb(original, { type: "community:reaction.add", messageId: "m1", channelId: "c1", emoji: "👍", userId: "peer" }))
- await act(async () => { resolve(undefined); await result })
- expect(screen.getByTestId("canonical").textContent).toBe("requested")
expect(getCommunityDbRegistry(original)!.collections.messages.get("m1")?.reactions).toMatchObject([{ emoji: "👍", userIds: ["peer"] }])
})
- it.each(["success", "failure"] as const)("rejects old account %s without recreating its caches", async (outcome) => {
- const { resolve, reject, original, view } = await mount()
- let result!: Promise<unknown>; act(() => { result = command() }); await pending()
- act(() => { sdk.id = "B"; view.rerender(<Root id="B" />) })
- await waitFor(() => expect(client).not.toBe(original))
- await waitFor(() => expect(screen.getByTestId("canonical").textContent).toBe("original"))
- await act(async () => { if (outcome === "success") resolve(undefined); else reject(new Error("old failure")); expect(await result).toMatchObject({ name: "AbortError" }) })
- expect(original.getQueryCache().getAll()).toHaveLength(0)
- expect(screen.getByTestId("canonical").textContent).toBe("original")
- })
})
diff --git a/src/web/src/hooks/community/mutations/messages.dom.test.ts b/src/web/src/hooks/community/mutations/messages.dom.test.ts
index 2cb7a0a4a..ebfc17b9f 100644
--- a/src/web/src/hooks/community/mutations/messages.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/messages.dom.test.ts
@@ -152,89 +152,6 @@ async function canonicalSidebar() {
return getForumSidebarBase(capturedQc, "s1")
}
-describe("useEditMessage", () => {
- it("optimistically patches content and rolls back when PATCH fails", async () => {
- const key = communityKeys.channelMessages("ch_1")
- const messageKey = communityKeys.message("m1")
- capturedQc.setQueryData(key, makeCache([{ id: "m1", content: "old" }]))
- capturedQc.setQueryData(messageKey, "m1")
- ingestMessages(canonicalRegistry, "ch_1", [{ id: "m1", type: "chat", content: "old" }])
- apiFetchMock.mockRejectedValueOnce(new Error("boom"))
- const mod = await loadMod()
- mountHook(() => mod.useEditMessage())
-
- await runMutation({ serverId: "s1", channelId: "ch_1", messageId: "m1", content: "new" }).catch(() => {})
-
- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/messages/m1", expect.objectContaining({
- method: "PATCH",
- body: JSON.stringify({ content: "new" }),
- assertActive: expect.any(Function), authenticationAccount: "u_me",
- }))
- expect(canonicalRegistry.collections.messages.get("m1")?.content).toBe("old")
- expect(capturedQc.getQueryData(messageKey)).toBe("m1")
- expect(capturedQc.getQueryData(key)).toEqual(makeCache([{ id: "m1" }]))
- }, 60_000)
-
- it("optimistically patches the single-message cache used by a post header", async () => {
- const messageKey = communityKeys.message("opener_1")
- capturedQc.setQueryData(messageKey, "opener_1")
- ingestMessages(canonicalRegistry, "forum_1", [{ id: "opener_1", type: "chat", content: "Old title" }])
- apiFetchMock.mockResolvedValueOnce(undefined)
- const mod = await loadMod()
- mountHook(() => mod.useEditMessage())
-
- await runMutation({
- serverId: "s1", channelId: "forum_1", messageId: "opener_1", content: "New title", forumChannelId: "forum_1",
- })
-
- expect(canonicalRegistry.collections.messages.get("opener_1")?.content).toBe("New title")
- expect(capturedQc.getQueryData(messageKey)).toBe("opener_1")
- })
-
- it("updates the canonical opener without invalidating unrelated feed transports", async () => {
- const threads = communityKeys.threads("forum_1")
- const feed = communityKeys.forumFeed("forum_1", "bug")
- const inbox = communityKeys.inboxUnreads()
- capturedQc.setQueryData(threads, { serverId: "s1", parentType: "forum", parentChannelId: "forum_1", threads: [] })
- capturedQc.setQueryData(feed, { pages: [], pageParams: [] })
- capturedQc.setQueryData(inbox, { servers: [], dms: [] })
- await seedCanonicalSidebar()
- apiFetchMock.mockResolvedValueOnce(undefined)
- const mod = await loadMod()
- mountHook(() => mod.useEditMessage())
-
- await runMutation({
- serverId: "s1", channelId: "forum_1", messageId: "opener_1", content: "new",
- forumChannelId: "forum_1", forumThreadId: "post_1",
- })
-
- expect(canonicalRegistry.collections.messages.get("opener_1")?.content).toBe("new")
- expect((await canonicalSidebar()).threads[0]?.title).toBe("new")
- expect(capturedQc.getQueryState(threads)?.isInvalidated).toBe(false)
- expect(capturedQc.getQueryState(inbox)?.isInvalidated).toBe(false)
- expect(capturedQc.getQueryState(feed)?.isInvalidated).toBe(false)
- })
-
- it("patches a loaded forum-sidebar title after the opener edit succeeds", async () => {
- apiFetchMock.mockResolvedValueOnce(undefined)
- const mod = await loadMod()
- await installCanonicalRegistry()
- await seedCanonicalSidebar()
- mountHook(() => mod.useEditMessage())
-
- await runMutation({
- serverId: "s1",
- channelId: "forum_1",
- messageId: "opener_1",
- content: "New title",
- forumChannelId: "forum_1",
- forumThreadId: "post_1",
- })
-
- expect((await canonicalSidebar()).threads[0]?.title).toBe("New title")
- })
-})
-
// ── useSendMessage ────────────────────────────────────────────────────────
describe("useSendMessage — happy path", () => {
@@ -1006,10 +923,10 @@ describe("useMarkAllInboxRead", () => {
await waitFor(() => expect(canonicalRegistry.collections.attentionScopes.get("channel")).toBeUndefined())
ingestMessages(canonicalRegistry!, "other", [{ id: "event", type: "chat", content: "old" }])
projectCommunityWsEventToDb(capturedQc, {
- type: "community:message.edited",
+ type: "community:reaction.add",
channelId: "other",
messageId: "event",
- content: "new",
+ emoji: "👍", userId: "peer",
} as never)
await act(async () => { fail(new Error("account read-all failed")); await pending })
@@ -1145,10 +1062,10 @@ describe("useDeleteMention — rollback", () => {
await waitFor(() => expect(canonicalRegistry.collections.attentionItems.get("mention:men_1")).toBeUndefined())
ingestMessages(canonicalRegistry!, "other", [{ id: "event", type: "chat", content: "old" }])
projectCommunityWsEventToDb(capturedQc, {
- type: "community:message.edited",
+ type: "community:reaction.add",
channelId: "other",
messageId: "event",
- content: "new",
+ emoji: "👍", userId: "peer",
} as never)
await act(async () => { fail(new Error("dismiss failed")); await pending })
diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.ts
index e5cd50855..be82b9aa1 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -13,11 +13,10 @@ import { getCommunityRuntime } from "@/stores/community/runtime"
import { useMutation, useQueryClient } from "@tanstack/react-query"
import { toast } from "sonner"
-import { apiFetch, toastApiError } from "@/lib/api/client"
+import { toastApiError } from "@/lib/api/client"
import { ApiError, isAbortError } from "@/lib/errors"
import { communityKeys } from "@/lib/query-keys"
-import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"
-import { captureCommunityLiveSnapshotToken, publishCommunityMessageFields, publishCommunityMessages, publishCommunityCreatedChannel, updateCommunityMessageContentOptimistically } from "@/lib/community-db/sync"
+import { captureCommunityLiveSnapshotToken, publishCommunityMessages, publishCommunityCreatedChannel } from "@/lib/community-db/sync"
import { presentMessageAttachment } from "@/lib/community/attachment-presentation"
import { attachmentThumbnailUrl, attachmentUrl } from "@/lib/community/storage"
import {
@@ -58,55 +57,6 @@ import {
type OriginalView = (() => void) & { signal: AbortSignal }
-type EditMessageArgs = {
- assertActive?: OriginalView
- serverId: string
- channelId: string
- messageId: string
- content: string
- forumChannelId?: string
- forumThreadId?: string
-}
-
-export function useEditMessage() {
- const origin = useCommunityMutationOrigin()
- const queryClient = useQueryClient()
- type Intent = EditMessageArgs & { original: ReturnType<typeof origin.begin>["token"] }
- const native = useMutation<void, Error, Intent>({ meta: { observabilityAction: "message.edit" },
- scope: { id: "community-message-field-commands" },
- mutationFn: async ({ channelId, messageId, content, original: token, assertActive }) => {
- origin.assert(token); assertActive?.()
- const registry = origin.registry
- await registry?.ready
- origin.assert(token); assertActive?.()
- await Promise.all([registry!.collections.messages.preload(), registry!.collections.channels.preload()])
- origin.assert(token); assertActive?.()
- await Promise.all([
- queryClient.cancelQueries({ queryKey: communityKeys.channelMessages(channelId) }),
- queryClient.cancelQueries({ queryKey: communityKeys.message(messageId), exact: true }),
- ])
- origin.assert(token); assertActive?.()
- const persist = async () => {
- try {
- await apiFetch(`/api/community/messages/${messageId}`, {
- method: "PATCH",
- body: JSON.stringify({ content }),
- ...communityRequestOptions(queryClient, token, assertActive?.signal, () => { origin.assert(token); assertActive?.() }),
- })
- origin.assert(token); assertActive?.()
- publishCommunityMessageFields(queryClient, messageId, { content }, { token, signal: assertActive?.signal })
- } catch (error) { origin.assert(token); throw error }
- }
- const transaction = registry!.dbClient.createTransaction({ autoCommit: false, mutationFn: persist })
- transaction.mutate(() => updateCommunityMessageContentOptimistically(registry!, messageId, content))
- try { if (transaction.mutations.length) await transaction.commit(); else await persist() } catch (error) { origin.assert(token); throw error }
- },
- })
- const capture = useCallback((input: EditMessageArgs): Intent => { input.assertActive?.(); return { ...input, original: origin.begin().token } }, [origin])
- const assertCurrent = useCallback((args: Intent) => { origin.assert(args.original); args.assertActive?.() }, [origin])
- return useNativeMutationFacade(native, capture, assertCurrent)
-}
-
/**
* Materialize the attachment view-model from the API attachment shape.
* Mirrors the old context's conversion at `postWithOptimisticInsert`.
diff --git a/src/web/src/hooks/community/read-coordinator.test.ts b/src/web/src/hooks/community/read-coordinator.test.ts
index 4ef6a9e0a..5bece0d3a 100644
--- a/src/web/src/hooks/community/read-coordinator.test.ts
+++ b/src/web/src/hooks/community/read-coordinator.test.ts
@@ -438,15 +438,15 @@ describe("read coordinator", () => {
await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
ingestMessages(registry, "other", [{ id: "event", type: "chat", content: "old" }])
projectCommunityWsEventToDb(queryClient, {
- type: "community:message.edited",
+ type: "community:reaction.add",
channelId: "other",
messageId: "event",
- content: "new",
+ emoji: "👍", userId: "peer",
})
rejectPut(new ApiError("forbidden", 403))
await vi.waitFor(() => expect(registry.collections.attentionScopes.get("channel-1")?.lastUnreadSeq).toBe(4))
- expect(registry.collections.messages.get("event")?.content).toBe("new")
+ expect(registry.collections.messages.get("event")?.reactions).toMatchObject([{ emoji: "👍", userIds: ["peer"] }])
expect(reconcileAccountAttention).not.toHaveBeenCalled()
} finally {
disposeReadCoordinator(queryClient)
@@ -646,10 +646,10 @@ describe("read coordinator", () => {
if (conflict) {
ingestMessages(registry, "other", [{ id: "event", type: "chat", content: "old" }])
projectCommunityWsEventToDb(queryClient, {
- type: "community:message.edited",
+ type: "community:reaction.add",
channelId: "other",
messageId: "event",
- content: "new",
+ emoji: "👍", userId: "peer",
})
}
@@ -657,7 +657,7 @@ describe("read coordinator", () => {
expect(cancelInboxProjectionTicket(ticket)).toBe(true)
expect(registry.collections.attentionScopes.get("channel-1")?.lastUnreadSeq).toBe(4)
expect(reconcileAccountAttention).not.toHaveBeenCalled()
- if (conflict) expect(registry.collections.messages.get("event")?.content).toBe("new")
+ if (conflict) expect(registry.collections.messages.get("event")?.reactions).toMatchObject([{ emoji: "👍", userIds: ["peer"] }])
} finally {
disposeInboxReadReservation(queryClient)
unregister()
diff --git a/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx b/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx
index d18dd4087..29e8580ed 100644
--- a/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx
+++ b/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx
@@ -36,7 +36,7 @@ vi.mock("./mutations", () => ({
useSendMessage: () => ({ mutateAsync: vi.fn() }),
useToggleReactionApi: () => vi.fn(), useAddReactionApi: () => vi.fn(),
usePinMessage: () => ({ mutate: vi.fn() }), useUnpinMessage: () => ({ mutate: vi.fn() }),
- useToggleMark: () => vi.fn(), useEditMessage: () => ({ mutate: vi.fn() }),
+ useToggleMark: () => vi.fn(),
useCreateThread: () => ({ mutateAsync: vi.fn() }), useUploadFile: () => ({ mutateAsync: vi.fn() }),
}))
diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts
index eb1ce5e82..0843ac015 100644
--- a/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts
+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts
@@ -838,7 +838,7 @@ describe("forum sidebar canonical projection", () => {
await invalidateForumSidebarBaseExact(queryClient, "server-1")
})
- it("publishes an HTTP response once and renders later WS edits from the same rows", async () => {
+ it("publishes the HTTP opener title from canonical rows", async () => {
const { queryClient, wrapper } = await setup()
apiFetchMock.mockResolvedValue(envelope())
const rendered = renderHook(
@@ -848,13 +848,7 @@ describe("forum sidebar canonical projection", () => {
await waitFor(() => expect(rendered.result.current.threads[0]?.title)
.toBe("Canonical title"))
- act(() => projectCommunityWsEventToDb(queryClient, {
- type: "community:message.edited",
- channelId: "forum-1",
- messageId: "opener-1",
- content: "WS title",
- }))
- await waitFor(() => expect(rendered.result.current.threads[0]?.title).toBe("WS title"))
+
})
it("normalizes a persisted default opener before one successful canonical publish", async () => {
diff --git a/src/web/src/lib/community-db/restore.test.ts b/src/web/src/lib/community-db/restore.test.ts
index d85bd1229..b6752e8ea 100644
--- a/src/web/src/lib/community-db/restore.test.ts
+++ b/src/web/src/lib/community-db/restore.test.ts
@@ -69,10 +69,11 @@ describe("canonical disk input precedence", () => {
it("preserves a WS patch that arrived before its disk row and a current message over old disk", async () => {
const { client, registry } = owner()
publishCommunityMessages(client, { channelId: "c1", messages: [message("current", "c1", "RSC")], proof: { token: captureCommunityLiveSnapshotToken(client) } })
- projectCommunityWsEventToDb(client, { type: "community:message.edited", serverId: "s1", channelId: "c1", messageId: "pending", content: "WS" })
+ projectCommunityWsEventToDb(client, { type: "community:reaction.add", serverId: "s1", channelId: "c1", messageId: "pending", emoji: "👍", userId: "peer" })
await restoreCommunityCollections(registry, input({ messages: [message("current"), message("pending"), message("uncovered", "other")] }))
const rows = client.getQueryData<Array<ReturnType<typeof message>>>(communityKeys.communityDbCollection("viewer", "messages"))!
- expect(rows.map((row) => [row.id, row.content])).toEqual([["current", "RSC"], ["pending", "WS"], ["uncovered", "Disk"]])
+ expect(rows.map((row) => [row.id, row.content])).toEqual([["current", "RSC"], ["pending", "Disk"], ["uncovered", "Disk"]])
+ expect(registry.queryClient.getQueryData<Array<{ reactions?: unknown }>>(communityKeys.communityDbCollection("viewer", "messages"))?.[1].reactions).toMatchObject([{ emoji: "👍", userIds: ["peer"] }])
expect(rows[1].createdAt).toBe(message("pending").createdAt)
})
diff --git a/src/web/src/lib/community-db/sync.test.ts b/src/web/src/lib/community-db/sync.test.ts
index b40fd3418..d06f461c3 100644
--- a/src/web/src/lib/community-db/sync.test.ts
+++ b/src/web/src/lib/community-db/sync.test.ts
@@ -581,7 +581,7 @@ describe("community DB sync", () => {
expect(db.collections.profiles.get("peer")).toMatchObject({ name: "Peer" })
})
- it("preserves a same-entity WS message edit over an older HTTP response", async () => {
+ it("preserves a same-entity WS message reaction over an older HTTP response", async () => {
const db = await registry()
const staleMessage = {
id: "m1",
@@ -594,10 +594,10 @@ describe("community DB sync", () => {
const token = captureCommunityLiveSnapshotToken(db.queryClient)
projectCommunityWsEventToDb(db.queryClient, {
- type: "community:message.edited",
+ type: "community:reaction.add",
channelId: "c1",
messageId: "m1",
- content: "new WS value",
+ emoji: "👍", userId: "viewer",
} as CommunityWsEvent)
publishCommunityMessages(db.queryClient, {
channelId: "c1",
@@ -605,7 +605,7 @@ describe("community DB sync", () => {
proof: { token, signal: undefined },
})
- expect(db.collections.messages.get("m1")?.content).toBe("new WS value")
+ expect(db.collections.messages.get("m1")?.reactions).toMatchObject([{ emoji: "👍", userIds: ["viewer"] }])
})
it("preserves a local canonical message patch over an older HTTP response", async () => {
@@ -636,15 +636,15 @@ describe("community DB sync", () => {
])
})
- it("merges a WS message edit for an absent row into an older HTTP response", async () => {
+ it("merges a WS message reaction for an absent row into an older HTTP response", async () => {
const db = await registry()
const token = captureCommunityLiveSnapshotToken(db.queryClient)
projectCommunityWsEventToDb(db.queryClient, {
- type: "community:message.edited",
+ type: "community:reaction.add",
channelId: "c1",
messageId: "m1",
- content: "new WS value",
+ emoji: "👍", userId: "viewer",
} as CommunityWsEvent)
publishCommunityMessages(db.queryClient, {
channelId: "c1",
@@ -658,7 +658,7 @@ describe("community DB sync", () => {
proof: { token, signal: undefined },
})
- expect(db.collections.messages.get("m1")?.content).toBe("new WS value")
+ expect(db.collections.messages.get("m1")?.reactions).toMatchObject([{ emoji: "👍", userIds: ["viewer"] }])
db.collections.messages.utils.writeDelete("m1")
db.queryClient.setQueryData(
@@ -691,10 +691,10 @@ describe("community DB sync", () => {
const token = captureCommunityLiveSnapshotToken(db.queryClient)
for (let index = 0; index < 100; index += 1) {
projectCommunityWsEventToDb(db.queryClient, {
- type: "community:message.edited",
+ type: "community:reaction.add",
channelId: "c1",
messageId: "m1",
- content: `edit ${index}`,
+ emoji: "👍", userId: "viewer",
} as CommunityWsEvent)
}
@@ -2732,7 +2732,7 @@ describe("community DB sync", () => {
await anonymous["cleanup"]()
projectCommunityWsEventToDb(new QueryClient(), {
- type: "community:message.edited", channelId: "missing", messageId: "missing", content: "noop",
+ type: "community:reaction.add", channelId: "missing", messageId: "missing", emoji: "👍", userId: "viewer",
} as CommunityWsEvent)
})
@@ -3060,10 +3060,10 @@ describe("community DB sync", () => {
expect([...db.collections.messages.keys()]).toEqual([])
ingestMessages(db, "c1", [message("pin", "pin")])
projectCommunityWsEventToDb(db.queryClient, {
- type: "community:message.edited",
+ type: "community:reaction.add",
channelId: "c1",
messageId: "pin",
- content: "edited",
+ emoji: "👍", userId: "viewer",
} as CommunityWsEvent)
projectCommunityWsEventToDb(db.queryClient, {
type: "community:reaction.add",
@@ -3073,7 +3073,7 @@ describe("community DB sync", () => {
emoji: "👍",
} as CommunityWsEvent)
expect(db.collections.messages.get("pin")).toMatchObject({
- content: "edited",
+ content: "pin",
reactions: [{ emoji: "👍", count: 1, me: true, userIds: ["viewer"] }],
})
db.queryClient.setQueryData(communityKeys.message("pin"), message("pin", "stale"))
@@ -3144,10 +3144,10 @@ describe("community DB sync", () => {
content: "cold opener",
})
projectCommunityWsEventToDb(db.queryClient, {
- type: "community:message.edited",
+ type: "community:reaction.add",
channelId: "forum1",
messageId: "opener",
- content: "edited opener",
+ emoji: "👍", userId: "viewer",
} as CommunityWsEvent)
projectCommunityWsEventToDb(db.queryClient, {
type: "community:reaction.add",
@@ -3157,7 +3157,7 @@ describe("community DB sync", () => {
emoji: "👍",
} as CommunityWsEvent)
expect(db.collections.messages.get("opener")).toMatchObject({
- content: "edited opener",
+ content: "cold opener",
reactions: [{ emoji: "👍", count: 1, me: true, userIds: ["viewer"] }],
})
uninstall()
diff --git a/src/web/src/lib/community-db/sync.ts b/src/web/src/lib/community-db/sync.ts
index 16b327585..16afdfa48 100644
--- a/src/web/src/lib/community-db/sync.ts
+++ b/src/web/src/lib/community-db/sync.ts
@@ -2142,16 +2142,6 @@ function patchMessageFirstPreview(registry: CommunityDbRegistry, channelId: stri
[channelId], ["preview"])
}
-export function updateCommunityMessageContentOptimistically(registry: CommunityDbRegistry, messageId: string, content: string) {
- const message = registry.collections.messages.get(messageId)
- if (!message) return
- registry.collections.messages.update(messageId, (row) => { row.content = content })
- const channel = firstMessageChannel(registry, message.channelId, messageId)
- if (channel && registry.collections.channels.has(channel.id)) {
- registry.collections.channels.update(channel.id, (row) => { row.preview = content })
- }
-}
-
export function publishCommunityServerFields(
queryClient: QueryClient,
serverId: string,
@@ -2649,18 +2639,6 @@ export function projectCommunityWsEventToDb(
}
return projected
}
- case "community:message.edited": {
- patchRows(
- registry,
- "messages",
- (row) => ({ ...row, content: event.content }),
- (row) => row.id === event.messageId,
- [event.messageId],
- ["content"],
- )
- patchMessageFirstPreview(registry, event.channelId, event.messageId, event.content)
- return
- }
case "community:message.updated": {
const changes = {
...(event.approval !== undefined ? { approval: event.approval } : {}),
diff --git a/src/web/src/lib/observability/client-document-restore-import.dom.test.ts b/src/web/src/lib/observability/client-document-restore-import.dom.test.ts
index e9c6c24f8..cb71ef297 100644
--- a/src/web/src/lib/observability/client-document-restore-import.dom.test.ts
+++ b/src/web/src/lib/observability/client-document-restore-import.dom.test.ts
@@ -35,7 +35,7 @@ it("does not install or backfill a document generation whose SDK import resolves
const initial = navigationForHref("/")!
expect(initial).toBeDefined()
const generation = telemetryGeneration()
- const retired = startAction("message.edit")!
+ const retired = startAction("message.mark")!
emitTelemetry("business.result", { action_id: retired.id, outcome: "success" })
await act(async () => { window.dispatchEvent(new PageTransitionEvent("pagehide", { persisted: true })) })
document.cookie = "alook_analytics_consent=v1.denied; path=/"
diff --git a/src/web/src/lib/observability/client-document-restore.dom.test.tsx b/src/web/src/lib/observability/client-document-restore.dom.test.tsx
index 2c3523c91..4058b6eb9 100644
--- a/src/web/src/lib/observability/client-document-restore.dom.test.tsx
+++ b/src/web/src/lib/observability/client-document-restore.dom.test.tsx
@@ -74,7 +74,7 @@ it("retires the old document before native resume, then exports one original Bac
expect(sent.flatMap(body => body.events ?? []).filter(event => event.name === "navigation.ready")).toHaveLength(1)
const generation = telemetryGeneration()
- const retired = startAction("message.edit")!
+ const retired = startAction("message.mark.command")!
collectorStatus = 429
const beforeRetry = sent.length
emitTelemetry("business.result", { action_id: retired.id, outcome: "success" })
diff --git a/src/web/src/lib/observability/client-reload.dom.test.ts b/src/web/src/lib/observability/client-reload.dom.test.ts
index c07dfa77b..b1ae2540c 100644
--- a/src/web/src/lib/observability/client-reload.dom.test.ts
+++ b/src/web/src/lib/observability/client-reload.dom.test.ts
@@ -36,7 +36,7 @@ it("resumes the actual previous SDK document and preserves its initial session_r
await act(async () => {
bootstrapObservability("web")
initialGeneration = telemetryGeneration()
- early = startAction("message.edit")
+ early = startAction("message.mark")
emitTelemetry("business.result", { ...actionAttributes(early), outcome: "success" })
vi.setSystemTime(earlyTimestamp + 400)
})
@@ -55,7 +55,7 @@ it("resumes the actual previous SDK document and preserves its initial session_r
expect(sent.some(body => body.events?.some(event => event.name === "business.result"))).toBe(true)
const earlyExport = sent.flatMap(body => (body.events ?? []).filter(event => event.attributes?.action_id === early!.id).map(event => ({ event, meta: body.meta })))
expect(earlyExport.map(record => record.event.name)).toEqual(["action.start", "business.result", "action.finish"])
- for (const { event, meta } of earlyExport) expect(event.attributes).toMatchObject({ action_id: early!.id, action_name: "message.edit", session_id: meta.session.id, start_ms: String(early!.start) })
+ for (const { event, meta } of earlyExport) expect(event.attributes).toMatchObject({ action_id: early!.id, action_name: "message.mark", session_id: meta.session.id, start_ms: String(early!.start) })
expect(Date.parse(earlyExport[0]!.event.timestamp)).toBe(earlyTimestamp)
expect(Date.parse(earlyExport[1]!.event.timestamp)).toBe(earlyTimestamp)
for (const body of sent) expect(body).toMatchObject({ meta: { sdk: { name: "faro-web", version: faroPackage.version }, session: { id: prior.sessionId } } })
diff --git a/src/web/src/lib/observability/client.dom.test.ts b/src/web/src/lib/observability/client.dom.test.ts
index 56be7fa29..9af4d4b83 100644
--- a/src/web/src/lib/observability/client.dom.test.ts
+++ b/src/web/src/lib/observability/client.dom.test.ts
@@ -85,7 +85,7 @@ it("real Faro sessions align after interrupted import, regrant, account changes,
expect(JSON.stringify(sent.slice(beforeRecovery))).not.toContain("delivery_failure_count")
controls.remove()
const generation = telemetryGeneration()
- emitTelemetry("business.result", { action_name: "message.edit", outcome: "success" })
+ emitTelemetry("business.result", { action_name: "message.mark", outcome: "success" })
const beforeAccount = sent.length
setTelemetryUser("account-c")
await vi.waitFor(() => {
@@ -97,7 +97,7 @@ it("real Faro sessions align after interrupted import, regrant, account changes,
expect(telemetryGeneration()).toBeGreaterThan(generation)
emitTelemetry("business.result", { action_name: "message.pin", outcome: "success" })
await vi.advanceTimersByTimeAsync(1500)
- expect(JSON.stringify(sent.slice(beforeAccount))).not.toContain("message.edit")
+ expect(JSON.stringify(sent.slice(beforeAccount))).not.toContain("message.mark")
expect(JSON.stringify(sent.slice(beforeAccount))).toContain("message.pin")
expect((native.vitals as { initialize: unknown }).initialize).toBe(native.initialize)
expect(native.faro!.instrumentations.instrumentations.filter(item => item.name.endsWith("instrumentation-web-vitals"))).toHaveLength(1)
@@ -133,7 +133,7 @@ it("real Faro sessions align after interrupted import, regrant, account changes,
expect(spans.some(span => span.name === "navigation" && JSON.stringify(span).includes(first.id) && JSON.stringify(span).includes(extended))).toBe(true)
const { apiFetchResponse } = await import("@/lib/api/client")
const beforeRequests = sent.length
- const one = startAction("message.edit")!, two = startAction("message.pin")!
+ const one = startAction("message.mark")!, two = startAction("message.pin")!
const firstContext = one.span!.spanContext(), secondContext = two.span!.spanContext()
await Promise.all([
apiFetchResponse("/api/community/bots", { observation: { action: one, reason: "command" } }),
diff --git a/src/web/src/lib/observability/context.test.ts b/src/web/src/lib/observability/context.test.ts
index fe38b6140..d75a05531 100644
--- a/src/web/src/lib/observability/context.test.ts
+++ b/src/web/src/lib/observability/context.test.ts
@@ -31,7 +31,7 @@ describe("original observation ownership", () => {
retireTelemetry(); clearActions(); configureTelemetry({ session_id: "account-b" }, true); installTelemetrySink(event => events.push(event))
return { end } as unknown as Span
})
- expect(startAction("message.edit")).toBeUndefined()
+ expect(startAction("message.mark")).toBeUndefined()
expect(end).toHaveBeenCalledTimes(1)
expect(events.filter(event => event.name.startsWith("action."))).toEqual([])
})
@@ -55,7 +55,7 @@ describe("original observation ownership", () => {
})
it("keeps concurrent commands and their requests on their original tokens", async () => {
const one = { original: {} }, two = { original: {} }
- const a = startAction("message.edit")!, b = startAction("message.pin")!
+ const a = startAction("message.mark")!, b = startAction("message.pin")!
bindCommandAction(one, a); bindCommandAction(two, b)
const request = startRequest("/api/community/messages/private", { method: "PATCH", observation: commandObservation(one.original) })
const response = new Response("{}", { headers: { "cf-ray": "a".repeat(16) + "-SJC" } })
@@ -68,7 +68,7 @@ describe("original observation ownership", () => {
expect(JSON.stringify(events)).not.toContain("private")
})
it("rejects old parsed responses, actions and command contexts after retirement", async () => {
- const intent = { original: {} }, action = startAction("message.edit")!
+ const intent = { original: {} }, action = startAction("message.mark")!
bindCommandAction(intent, action)
const request = startRequest("/api/community/messages/private", { observation: commandObservation(intent.original) })
const response = new Response("{}")
@@ -112,7 +112,7 @@ describe("original observation ownership", () => {
it("preserves an accepted unsent intent, request ownership and timestamp across initial native identity alignment", async () => {
retireTelemetry(); clearActions(); configureTelemetry({ session_id: "provisional" }, true)
const generation = telemetryGeneration(), timestamp = Date.now()
- const action = startAction("message.edit")!
+ const action = startAction("message.mark")!
const request = startRequest("/api/community/messages/private", { observation: { action, reason: "command" } })
const response = new Response("{}")
vi.setSystemTime(timestamp + 500)
diff --git a/src/web/src/lib/observability/coverage.test.ts b/src/web/src/lib/observability/coverage.test.ts
index 37e67ef27..33a1de668 100644
--- a/src/web/src/lib/observability/coverage.test.ts
+++ b/src/web/src/lib/observability/coverage.test.ts
@@ -174,11 +174,6 @@ const mutationCoverage = [
"owner": "useReactionIntent",
"action": "message.reaction.command"
},
- {
- "file": "src/web/src/hooks/community/mutations/messages.ts",
- "owner": "useEditMessage",
- "action": "message.edit"
- },
{
"file": "src/web/src/hooks/community/mutations/messages.ts",
"owner": "useSendMessage",
diff --git a/src/web/src/lib/observability/coverage.ts b/src/web/src/lib/observability/coverage.ts
index 15fbc3f9e..d69d28130 100644
--- a/src/web/src/lib/observability/coverage.ts
+++ b/src/web/src/lib/observability/coverage.ts
@@ -235,7 +235,6 @@ export const actionNames = [
"machine.update",
"mention.dismiss",
"message.compose.send",
- "message.edit",
"message.export",
"message.mark",
"message.mark.command",
diff --git a/src/web/src/lib/observability/page-visit.dom.test.ts b/src/web/src/lib/observability/page-visit.dom.test.ts
index bd9442112..46f12f2ee 100644
--- a/src/web/src/lib/observability/page-visit.dom.test.ts
+++ b/src/web/src/lib/observability/page-visit.dom.test.ts
@@ -104,7 +104,7 @@ it("keeps post-ready commands and their requests on the visited page, captures o
finishAction(pageA, "success", { phase: "primary", region: "bots" })
const loadEnd = exporter.getFinishedSpans().find(s => s.name === "navigation")!.endTime
expect(currentPageObservation()).toBe(pageA)
- const command = startAction("message.edit")!
+ const command = startAction("message.mark")!
const pending = startRequest("/api/community/bots", { observation: { action: command, reason: "command" } })!
const pageB = beginNavigation(b)!
expect(currentPageObservation()).toBe(pageA)
diff --git a/src/web/src/lib/observability/query-observer.test.ts b/src/web/src/lib/observability/query-observer.test.ts
index 8d5223c7d..3b40881c3 100644
--- a/src/web/src/lib/observability/query-observer.test.ts
+++ b/src/web/src/lib/observability/query-observer.test.ts
@@ -36,7 +36,7 @@ it("uses native mutation pending/terminal events once and binds each original re
expect(commandObservation(input.original)?.action?.name).toBe(name)
await waiting
} })
- const a = build("message.edit").execute(one), b = build("message.pin").execute(two)
+ const a = build("message.mark").execute(one), b = build("message.pin").execute(two)
await Promise.resolve()
expect(events.filter(event => event.name === "action.start")).toHaveLength(2)
resolve(); await Promise.all([a, b])
diff --git a/src/ws-do/src/community-browser-event-ingress.test.ts b/src/ws-do/src/community-browser-event-ingress.test.ts
index 49087d734..ede330568 100644
--- a/src/ws-do/src/community-browser-event-ingress.test.ts
+++ b/src/ws-do/src/community-browser-event-ingress.test.ts
@@ -69,9 +69,9 @@ function worstEscapingTarget(index: number) {
}
describe("community browser event ingress", () => {
- it("normalizes all 49 current fixtures without a contract version field", () => {
+ it("normalizes all 48 current fixtures without a contract version field", () => {
const fixtures = Object.values(communityWsEventFixtures)
- expect(fixtures).toHaveLength(49)
+ expect(fixtures).toHaveLength(48)
for (const fixture of fixtures) {
const normalized = normalizeCommunityBrowserEvent(fixture)
expect(normalized).toMatchObject({ ok: true, event: fixture, envelope: fixture })
diff --git a/src/ws-do/src/community-content-access.ts b/src/ws-do/src/community-content-access.ts
index 74cdb3ec9..f863bad8a 100644
--- a/src/ws-do/src/community-content-access.ts
+++ b/src/ws-do/src/community-content-access.ts
@@ -5,7 +5,6 @@ type AccessKind = "channel" | "child-create" | "child-update" | "channel-create"
export const communityContentAccessKinds = {
"community:message.create": "channel",
"community:message.updated": "channel",
- "community:message.edited": "channel",
"community:reaction.add": "channel",
"community:reaction.remove": "channel",
"community:pin.add": "channel",
@@ -93,7 +92,6 @@ export async function canDeliverCommunityContent(
scopes.push({ id: event.channel.id, serverId: event.serverId })
break
case "community:message.create":
- case "community:message.edited":
scopes.push({ id: event.channelId, serverId: event.serverId,
parentChannelId: event.parentChannelId })
break