Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix: refresh forum tags and preserve UI context (#428)
Gener5b8e49b6303d
diff --git a/src/daemon/src/drivers/codexEventNormalizer.test.ts b/src/daemon/src/drivers/codexEventNormalizer.test.tsindex 9d262811e..604f34d2c 100644--- a/src/daemon/src/drivers/codexEventNormalizer.test.ts+++ b/src/daemon/src/drivers/codexEventNormalizer.test.ts@@ -17,12 +17,64 @@ describe("CodexEventNormalizer — tool_call/tool_output symmetry", () => {it("fileChange: item/started then item/completed emits tool_call then tool_output", () => {const n = new CodexEventNormalizer();const started = n.normalizeLine(notify("item/started", { item: { type: "fileChange" } }));- expect(started).toEqual([{ kind: "tool_call", name: "file_change", input: { type: "fileChange" } }]);+ expect(started).toEqual([{ kind: "tool_call", name: "file_change", input: {} }]);const completed = n.normalizeLine(notify("item/completed", { item: { type: "fileChange" } }));expect(completed).toEqual([{ kind: "tool_output", name: "file_change" }]);});+ it("fileChange consumes raw changes at the adapter boundary and emits only an ordered-unique flat path", () => {+ const n = new CodexEventNormalizer();+ const started = n.normalizeLine(notify("item/started", {+ item: {+ type: "fileChange",+ changes: [+ { path: " a.ts ", diff: "secret-a" },+ { path: "" },+ { path: 42 },+ { path: "b.ts", content: "secret-b" },+ { path: "a.ts" },+ ],+ path: "ignored-fallback.ts",+ diff: "top-secret",+ content: "top-secret-content",+ },+ }));++ expect(started).toEqual([+ { kind: "tool_call", name: "file_change", input: { path: "a.ts, b.ts" } },+ ]);+ expect(JSON.stringify(started)).not.toContain("changes");+ expect(JSON.stringify(started)).not.toContain("secret");++ const completed = n.normalizeLine(notify("item/completed", { item: { type: "fileChange" } }));+ expect(completed).toEqual([{ kind: "tool_output", name: "file_change" }]);+ });++ it("fileChange flattens a legacy top-level path when changes are absent", () => {+ const started = new CodexEventNormalizer().normalizeLine(notify("item/started", {+ item: { type: "fileChange", path: " legacy.ts ", diff: "secret" },+ }));++ expect(started).toEqual([+ { kind: "tool_call", name: "file_change", input: { path: "legacy.ts" } },+ ]);+ });++ it("fileChange falls back to a valid top-level path when changes contain no valid paths", () => {+ const started = new CodexEventNormalizer().normalizeLine(notify("item/started", {+ item: {+ type: "fileChange",+ changes: [{ path: " " }, { path: 42 }, { diff: "secret" }],+ path: "fallback.ts",+ },+ }));++ expect(started).toEqual([+ { kind: "tool_call", name: "file_change", input: { path: "fallback.ts" } },+ ]);+ });+it("webSearch: item/started then item/completed emits tool_call then tool_output", () => {const n = new CodexEventNormalizer();const started = n.normalizeLine(notify("item/started", { item: { type: "webSearch" } }));diff --git a/src/daemon/src/drivers/codexEventNormalizer.ts b/src/daemon/src/drivers/codexEventNormalizer.tsindex 9a773c362..1e308943d 100644--- a/src/daemon/src/drivers/codexEventNormalizer.ts+++ b/src/daemon/src/drivers/codexEventNormalizer.ts@@ -15,6 +15,26 @@ import type { ParsedEvent } from "../types.js";import { mapCodexTelemetry } from "./codexTelemetrySidecar.js";import { tryParseJsonLine } from "./utils.js";+function normalizeFileChangeInput(item: any): { path?: string } {+ const paths: string[] = [];+ const seen = new Set<string>();+ const changePaths = Array.isArray(item?.changes)+ ? item.changes.map((change: any) => change?.path)+ : [];+ for (const candidate of changePaths) {+ if (typeof candidate !== "string") continue;+ const path = candidate.trim();+ if (!path || seen.has(path)) continue;+ seen.add(path);+ paths.push(path);+ }+ if (paths.length === 0 && typeof item?.path === "string") {+ const path = item.path.trim();+ if (path) paths.push(path);+ }+ return paths.length > 0 ? { path: paths.join(", ") } : {};+}+export class CodexEventNormalizer {private threadId: string | null = null;/**@@ -149,7 +169,7 @@ export class CodexEventNormalizer {case "enteredReviewMode":return [{ kind: "review_started" }];case "fileChange":- return [{ kind: "tool_call", name: "file_change", input: params?.item }];+ return [{ kind: "tool_call", name: "file_change", input: normalizeFileChangeInput(params?.item) }];case "mcpToolCall":return [{ kind: "tool_call", name: `mcp_${params?.item?.name ?? "tool"}`, input: params?.item }];case "webSearch":diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.tsindex 081b5f88d..53803288a 100644--- a/src/daemon/src/manager/managerRuntime.test.ts+++ b/src/daemon/src/manager/managerRuntime.test.ts@@ -1668,10 +1668,10 @@ describe("extractToolAudit — file-target class", () => {suppressed: false,});});- it("codex file_change → edit + path (already-unwrapped params.item)", () => {- expect(extractToolAudit("file_change", { path: "src/x.ts" })).toEqual({+ it("codex file_change → edit + adapter-flattened ordered paths", () => {+ expect(extractToolAudit("file_change", { path: "a.ts, b.ts" })).toEqual({name: "edit",- target: "src/x.ts",+ target: "a.ts, b.ts",suppressed: false,});});@@ -1829,7 +1829,7 @@ describe("extractToolAudit — driver coverage matrix", () => {{ driver: "codex", rawName: "shell", rawInput: { command: "pnpm test" }, expected: { name: "bash", target: "pnpm test", suppressed: false } },{ driver: "codex", rawName: "shell", rawInput: { command: ["bash", "-lc", "rm tmp"] }, expected: { name: "bash", target: "bash -lc rm tmp", suppressed: false } },- { driver: "codex", rawName: "file_change", rawInput: { path: "/x" }, expected: { name: "edit", target: "/x", suppressed: false } },+ { driver: "codex", rawName: "file_change", rawInput: { path: "a.ts, b.ts" }, expected: { name: "edit", target: "a.ts, b.ts", suppressed: false } },{ driver: "codex", rawName: "web_search", rawInput: { query: "cats" }, expected: { name: "web_search", target: "cats", suppressed: false } },{ driver: "codex", rawName: "mcp_search", rawInput: { query: "foo" }, expected: { name: "mcp_search", target: "foo", suppressed: false } },{ driver: "codex", rawName: "collab_tool_call", rawInput: { name: "x" }, expected: { name: "collab_tool_call", target: "x", suppressed: false } },@@ -1879,7 +1879,7 @@ describe("onBotAuditEvent — integration through onRuntimeEvent (T9/T10)", () ={ name: "edit", input: { path: "x" }, expect: { name: "edit", target: "x" } },{ name: "Grep", input: { pattern: "TODO" }, expect: { name: "grep", target: "TODO" } },{ name: "shell", input: { command: "pnpm test" }, expect: { name: "bash", target: "pnpm test" } },- { name: "file_change", input: { path: "src/x.ts" }, expect: { name: "edit", target: "src/x.ts" } },+ { name: "file_change", input: { path: "a.ts, b.ts" }, expect: { name: "edit", target: "a.ts, b.ts" } },];for (const c of combos) {diff --git a/src/shared/src/constants/community.test.ts b/src/shared/src/constants/community.test.tsindex c4aba0c50..11a982c05 100644--- a/src/shared/src/constants/community.test.ts+++ b/src/shared/src/constants/community.test.ts@@ -6,6 +6,8 @@ import {ICON_CROP_OUTPUT_SIZE,MAX_ICON_SOURCE_FILE_SIZE_BYTES,ALLOWED_ICON_SOURCE_MIME_TYPES,+ MESSAGE_PREVIEW_LENGTH,+ truncateMessagePreview,} from "./community"describe("icon-crop constants", () => {@@ -36,3 +38,29 @@ describe("icon-crop constants", () => {expect(alook.ALLOWED_ICON_SOURCE_MIME_TYPES).toEqual(ALLOWED_ICON_SOURCE_MIME_TYPES)})})++describe("truncateMessagePreview", () => {+ it("keeps previews at or below the limit unchanged", () => {+ const exact = "x".repeat(MESSAGE_PREVIEW_LENGTH)+ expect(truncateMessagePreview(exact)).toBe(exact)+ expect(truncateMessagePreview("short")).toBe("short")+ })++ it("replaces the final code unit with an ellipsis only when the preview exceeds the limit", () => {+ const result = truncateMessagePreview("x".repeat(MESSAGE_PREVIEW_LENGTH + 1))+ expect(result).toBe(`${"x".repeat(MESSAGE_PREVIEW_LENGTH - 1)}…`)+ expect(result.length).toBe(MESSAGE_PREVIEW_LENGTH)+ })++ it("does not split a surrogate pair at the truncation boundary", () => {+ const result = truncateMessagePreview(`${"x".repeat(MESSAGE_PREVIEW_LENGTH - 2)}😀tail`)+ expect(result).toBe(`${"x".repeat(MESSAGE_PREVIEW_LENGTH - 2)}…`)+ expect(result.length).toBeLessThanOrEqual(MESSAGE_PREVIEW_LENGTH)+ const beforeEllipsis = result.charCodeAt(result.length - 2)+ expect(beforeEllipsis < 0xd800 || beforeEllipsis > 0xdbff).toBe(true)+ })++ it("round-trips through the @alook/shared index re-export", () => {+ expect(alook.truncateMessagePreview).toBe(truncateMessagePreview)+ })+})diff --git a/src/shared/src/constants/community.ts b/src/shared/src/constants/community.tsindex 6c661b54e..feb724499 100644--- a/src/shared/src/constants/community.ts+++ b/src/shared/src/constants/community.ts@@ -70,6 +70,22 @@ export const UNCATEGORIZED_CATEGORY_ID = "__uncategorized__"// Previewsexport const MESSAGE_PREVIEW_LENGTH = 120+export function truncateMessagePreview(text: string): string {+ if (text.length <= MESSAGE_PREVIEW_LENGTH) return text+ let end = MESSAGE_PREVIEW_LENGTH - 1+ const lastIncluded = text.charCodeAt(end - 1)+ const firstExcluded = text.charCodeAt(end)+ if (+ lastIncluded >= 0xd800+ && lastIncluded <= 0xdbff+ && firstExcluded >= 0xdc00+ && firstExcluded <= 0xdfff+ ) {+ end -= 1+ }+ return `${text.slice(0, end)}…`+}+// Inbox / unreadsexport const DEFAULT_INBOX_PAGE_SIZE = 100export const MAX_INBOX_PAGE_SIZE = 200diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex b5740e9b6..be884d38e 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -151,6 +151,7 @@ export {MAX_ACTIVE_INVITES_PER_SERVER,UNCATEGORIZED_CATEGORY_ID,MESSAGE_PREVIEW_LENGTH,+ truncateMessagePreview,DEFAULT_INBOX_PAGE_SIZE,MAX_INBOX_PAGE_SIZE,PRESENCE_MEMBER_CAP,diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsxindex adb64c658..12478d67c 100644--- a/src/web/src/app/c/channels/layout.tsx+++ b/src/web/src/app/c/channels/layout.tsx@@ -277,6 +277,10 @@ export default function ServerLayout({ children }: { children: ReactNode }) {setServerSettingsOpen(true)}, [])+ const onRailOpenActiveInvite = useCallback(() => {+ setInvitePopoverOpen(true)+ }, [])+const onBlockedCreate = useCallback(() => {toast("Only admins can create channels in a private category")}, [])@@ -488,6 +492,8 @@ export default function ServerLayout({ children }: { children: ReactNode }) {setMobileZone={setMobileZone}sidebar={sidebar}extraDialogs={<>{serverSettingsDialog}{iconCropDialog}</>}+ onOpenActiveServerSettings={onSidebarOpenSettings}+ onOpenActiveServerInvite={onRailOpenActiveInvite}goHome={goHome}goServer={goServer}>diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsxindex bf62d5c6f..c84a07d4b 100644--- a/src/web/src/app/c/me/[dmId]/page.tsx+++ b/src/web/src/app/c/me/[dmId]/page.tsx@@ -3,7 +3,6 @@import { useCallback, useEffect, useMemo, useState } from "react"import { useParams, useSearchParams } from "next/navigation"import { toast } from "sonner"-import { MESSAGE_PREVIEW_LENGTH } from "@alook/shared"import { useBreakpoint } from "@/hooks/use-mobile"import { DmHeader, DmHeaderSkeleton } from "@/components/community/dm-header"import { Avatar } from "@/components/community/avatar"@@ -309,9 +308,7 @@ function DmView() {const receipt = acceptDmMessage({dmId,content: markdown,- replyTo: replyTo- ? { ...replyTo, text: replyTo.text.slice(0, MESSAGE_PREVIEW_LENGTH) }- : undefined,+ replyTo: replyTo ?? undefined,attachments,author: {id: currentUser.id,diff --git a/src/web/src/components/community/message-channel-controller.tsx b/src/web/src/components/community/message-channel-controller.tsxindex 1db7ad3c8..7664e2ee3 100644--- a/src/web/src/components/community/message-channel-controller.tsx+++ b/src/web/src/components/community/message-channel-controller.tsx@@ -3,7 +3,7 @@import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react"import { useRouter, useSearchParams } from "next/navigation"import { toast } from "sonner"-import { deriveThreadName, MESSAGE_PREVIEW_LENGTH, type MentionType } from "@alook/shared"+import { deriveThreadName, type MentionType } from "@alook/shared"import { apiFetch, toastApiError } from "@/lib/api/client"import { avatarInitial } from "@/lib/community/avatar"import type { Msg } from "@/components/community/_types"@@ -15,6 +15,7 @@ import {useTypingUsersForScope,} from "@/stores/community"import { useMessageStreamStore } from "@/stores/community/message-stream"+import { toOptimisticReplyPreview } from "@/lib/community/reply-preview"import {sendNonce,tempMessageId,@@ -403,7 +404,7 @@ export function MessageChannelController({authorAvatar: viewer.avatar,content: markdown,createdAt: new Date().toISOString(),- ...(replyTo ? { replyTo: { ...replyTo, text: replyTo.text.slice(0, MESSAGE_PREVIEW_LENGTH) } } : {}),+ ...(replyTo ? { replyTo: toOptimisticReplyPreview(replyTo) } : {}),},localUploads: attachments?.map((attachment) => {const previewObjectUrl = attachment.previewObjectUrl ?? URL.createObjectURL(attachment.file)diff --git a/src/web/src/components/community/server-rail-actions.test.ts b/src/web/src/components/community/server-rail-actions.test.tsnew file mode 100644index 000000000..e11ce3a87--- /dev/null+++ b/src/web/src/components/community/server-rail-actions.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from "vitest"+import { resolveServerRailOverlayAction } from "./server-rail-actions"++describe("resolveServerRailOverlayAction", () => {+ it.each(["settings", "invite"] as const)(+ "opens active-server %s directly without producing a navigation target",+ (overlay) => {+ expect(resolveServerRailOverlayAction({+ targetServerId: "server_1",+ activeServerId: "server_1",+ overlay,+ hasActiveOpener: true,+ })).toEqual({ kind: "open-active" })+ },+ )++ it.each(["settings", "invite"] as const)(+ "keeps the existing other-server %s URL",+ (overlay) => {+ expect(resolveServerRailOverlayAction({+ targetServerId: "server_2",+ activeServerId: "server_1",+ overlay,+ hasActiveOpener: true,+ })).toEqual({+ kind: "navigate",+ href: `/c/channels/server_2?${overlay}=1`,+ })+ },+ )++ it("falls back to the existing URL when the active layout has no direct opener", () => {+ expect(resolveServerRailOverlayAction({+ targetServerId: "server_1",+ activeServerId: "server_1",+ overlay: "settings",+ hasActiveOpener: false,+ })).toEqual({+ kind: "navigate",+ href: "/c/channels/server_1?settings=1",+ })+ })+})diff --git a/src/web/src/components/community/server-rail-actions.ts b/src/web/src/components/community/server-rail-actions.tsnew file mode 100644index 000000000..c97f5e89b--- /dev/null+++ b/src/web/src/components/community/server-rail-actions.ts@@ -0,0 +1,25 @@+export type ServerRailOverlay = "settings" | "invite"++export type ServerRailOverlayAction =+ | { kind: "open-active" }+ | { kind: "navigate"; href: string }++export function resolveServerRailOverlayAction({+ targetServerId,+ activeServerId,+ overlay,+ hasActiveOpener,+}: {+ targetServerId: string+ activeServerId?: string+ overlay: ServerRailOverlay+ hasActiveOpener: boolean+}): ServerRailOverlayAction {+ if (targetServerId === activeServerId && hasActiveOpener) {+ return { kind: "open-active" }+ }+ return {+ kind: "navigate",+ href: `/c/channels/${targetServerId}?${overlay}=1`,+ }+}diff --git a/src/web/src/components/community/server-rail.tsx b/src/web/src/components/community/server-rail.tsxindex 387ceefc5..775092878 100644--- a/src/web/src/components/community/server-rail.tsx+++ b/src/web/src/components/community/server-rail.tsx@@ -148,6 +148,8 @@ export const ServerRail = memo(function ServerRail({server={{ id: fs.id, name: fs.name, initial: fs.initial, icon: fs.icon, active: false, mentions: 0, isOwner: false }}active={view !== "dm" && activeId === sid}onClick={() => pickServer(sid)}+ onOpenSettings={() => onOpenSettings?.(sid)}+ onOpenInvitePopover={onOpenInvitePopover ? () => onOpenInvitePopover(sid) : undefined}inFolderdragging={dragActiveId === sid}/>diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsxindex 6304a37de..e282bb13b 100644--- a/src/web/src/components/community/shell-frame.tsx+++ b/src/web/src/components/community/shell-frame.tsx@@ -19,6 +19,7 @@ import {desktopUserBarOverlayWidth,} from "./shell-frame-geometry"import { ServerRail } from "./server-rail"+import { resolveServerRailOverlayAction } from "./server-rail-actions"import { UserBar } from "./user-bar"import { markVoluntaryLeave, pickPostEjectDestination } from "./eject-server"import { InboxPopover } from "./community-inbox-popover"@@ -83,6 +84,8 @@ export function ShellFrame({sidebar,children,extraDialogs,+ onOpenActiveServerSettings,+ onOpenActiveServerInvite,goHome,goServer,}: {@@ -93,6 +96,8 @@ export function ShellFrame({sidebar: (opts?: { noHeader?: boolean }) => ReactNodechildren: ReactNodeextraDialogs?: ReactNode+ onOpenActiveServerSettings?: () => void+ onOpenActiveServerInvite?: () => voidgoHome: () => voidgoServer: () => void}) {@@ -238,15 +243,31 @@ export function ShellFrame({)const onRailOpenSettings = useCallback((id?: string) => {- if (id) router.push(`/c/channels/${id}?settings=1`)+ if (!id) return+ const action = resolveServerRailOverlayAction({+ targetServerId: id,+ activeServerId,+ overlay: "settings",+ hasActiveOpener: !!onOpenActiveServerSettings,+ })+ if (action.kind === "open-active") onOpenActiveServerSettings?.()+ else router.push(action.href)},- [router],+ [activeServerId, onOpenActiveServerSettings, router],)const onRailOpenInvitePopover = useCallback((id?: string) => {- if (id) router.push(`/c/channels/${id}?invite=1`)+ if (!id) return+ const action = resolveServerRailOverlayAction({+ targetServerId: id,+ activeServerId,+ overlay: "invite",+ hasActiveOpener: !!onOpenActiveServerInvite,+ })+ if (action.kind === "open-active") onOpenActiveServerInvite?.()+ else router.push(action.href)},- [router],+ [activeServerId, onOpenActiveServerInvite, router],)const onRailUngroupFolder = useCallback((fId: string) => {diff --git a/src/web/src/hooks/community/mutations/forum.test.ts b/src/web/src/hooks/community/mutations/forum.test.tsindex 3b5c3ab79..339a4c9ca 100644--- a/src/web/src/hooks/community/mutations/forum.test.ts+++ b/src/web/src/hooks/community/mutations/forum.test.ts@@ -135,12 +135,13 @@ describe("useCreateForumThread", () => {})describe("useUpdatePostTags", () => {- it("PUTs normalized tags and invalidates every message-feed variant", async () => {+ it("PUTs normalized tags and invalidates every message-feed variant plus the forum tag list", async () => {const { useUpdatePostTags } = await load()useUpdatePostTags()capturedQc.setQueryData(communityKeys.channelMessages("forum_1"), { pages: [], pageParams: [] })const bugKey = [...communityKeys.channelMessages("forum_1"), "tag", "bug"] as constcapturedQc.setQueryData(bugKey, { pages: [], pageParams: [] })+ capturedQc.setQueryData(communityKeys.forumTags("forum_1"), { tags: ["bug", "p0"] })apiFetchMock.mockResolvedValueOnce({ tags: ["bug", "p0"] })await runMutation({@@ -156,6 +157,29 @@ describe("useUpdatePostTags", () => {})expect(capturedQc.getQueryState(communityKeys.channelMessages("forum_1"))?.isInvalidated).toBe(true)expect(capturedQc.getQueryState(bugKey)?.isInvalidated).toBe(true)+ expect(capturedQc.getQueryState(communityKeys.forumTags("forum_1"))?.isInvalidated).toBe(true)+ })++ it("leaves both the message feeds and forum tag list untouched when the PUT fails", async () => {+ const { useUpdatePostTags } = await load()+ useUpdatePostTags()+ const feedBefore = { pages: [{ messages: [{ id: "m_p2" }] }], pageParams: [null] }+ const tagsBefore = { tags: ["bug"] }+ capturedQc.setQueryData(communityKeys.channelMessages("forum_1"), feedBefore)+ capturedQc.setQueryData(communityKeys.forumTags("forum_1"), tagsBefore)+ apiFetchMock.mockRejectedValueOnce(new Error("500"))++ await runMutationExpectError({+ forumChannelId: "forum_1",+ threadId: "p2",+ openerMessageId: "m_p2",+ tags: [],+ })++ expect(capturedQc.getQueryData(communityKeys.channelMessages("forum_1"))).toEqual(feedBefore)+ expect(capturedQc.getQueryData(communityKeys.forumTags("forum_1"))).toEqual(tagsBefore)+ expect(capturedQc.getQueryState(communityKeys.channelMessages("forum_1"))?.isInvalidated).toBe(false)+ expect(capturedQc.getQueryState(communityKeys.forumTags("forum_1"))?.isInvalidated).toBe(false)})})diff --git a/src/web/src/hooks/community/mutations/forum.ts b/src/web/src/hooks/community/mutations/forum.tsindex 35cd7e4d8..49f10233d 100644--- a/src/web/src/hooks/community/mutations/forum.ts+++ b/src/web/src/hooks/community/mutations/forum.ts@@ -81,6 +81,7 @@ export function useUpdatePostTags() {// This is required when the edited// post loses the currently-selected tag and must leave that result set.void queryClient.invalidateQueries({ queryKey: communityKeys.channelMessages(args.forumChannelId) })+ void queryClient.invalidateQueries({ queryKey: communityKeys.forumTags(args.forumChannelId) })},})}diff --git a/src/web/src/hooks/community/use-dm-message-sender.test.ts b/src/web/src/hooks/community/use-dm-message-sender.test.tsindex e8a9afa04..39228cd04 100644--- a/src/web/src/hooks/community/use-dm-message-sender.test.ts+++ b/src/web/src/hooks/community/use-dm-message-sender.test.ts@@ -1,6 +1,7 @@import { beforeEach, describe, expect, it, vi } from "vitest"import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"import { materializeMessageStream } from "@/lib/community/message-stream"+import { MESSAGE_PREVIEW_LENGTH } from "@alook/shared"vi.mock("react", () => ({useCallback: (fn: Function) => fn,@@ -123,6 +124,33 @@ describe("useDmMessageSender", () => {)})+ it("bounds a DM optimistic reply and preserves the exact preview through retry", async () => {+ postMock+ .mockRejectedValueOnce(new Error("offline"))+ .mockRejectedValueOnce(new Error("still offline"))+ const { useDmMessageSender } = await import("./use-dm-message-sender")+ const sender = useDmMessageSender()+ const receipt = sender.accept({+ dmId: "dm_1",+ content: "replying",+ replyTo: {+ id: "prior",+ authorName: "Peer",+ text: "x".repeat(MESSAGE_PREVIEW_LENGTH + 1),+ },+ author: { id: "u_me", name: "Me", avatar: "M" },+ })++ if (!receipt.accepted) throw new Error("expected accepted receipt")+ await expect(receipt.committed).resolves.toEqual({ ok: false, error: expect.any(Error) })+ const expected = `${"x".repeat(MESSAGE_PREVIEW_LENGTH - 1)}…`+ expect(getMessageOverlay({ kind: "dm", id: "dm_1" }).outboxByNonce.get("fresh_nonce")?.message.replyTo?.text).toBe(expected)++ await expect(sender.retry("dm_1", "fresh_nonce")).resolves.toEqual({ ok: false, error: expect.any(Error) })+ expect(getMessageOverlay({ kind: "dm", id: "dm_1" }).outboxByNonce.get("fresh_nonce")?.message.replyTo?.text).toBe(expected)+ expect(postMock).toHaveBeenNthCalledWith(2, expect.objectContaining({ replyToId: "prior", nonce: "fresh_nonce" }))+ })+it("reuses settled remote attachments on retry without uploading twice", async () => {uploadMock.mockResolvedValueOnce({id: "att_x",diff --git a/src/web/src/hooks/community/use-dm-message-sender.ts b/src/web/src/hooks/community/use-dm-message-sender.tsindex 481185b77..f8a9e1cac 100644--- a/src/web/src/hooks/community/use-dm-message-sender.ts+++ b/src/web/src/hooks/community/use-dm-message-sender.ts@@ -4,6 +4,7 @@ import { useCallback } from "react"import type { Msg } from "@/components/community/_types"import type { SendAttachment } from "@/components/community/composer"import { toastApiError } from "@/lib/api/client"+import { toOptimisticReplyPreview } from "@/lib/community/reply-preview"import { useMessageStreamStore } from "@/stores/community/message-stream"import {sendNonce,@@ -126,7 +127,7 @@ export function useDmMessageSender() {authorAvatar: args.author.avatar,content: args.content,createdAt: new Date().toISOString(),- ...(args.replyTo ? { replyTo: args.replyTo } : {}),+ ...(args.replyTo ? { replyTo: toOptimisticReplyPreview(args.replyTo) } : {}),},localUploads: args.attachments?.map((attachment) => {const previewObjectUrl = attachment.previewObjectUrl ?? URL.createObjectURL(attachment.file)diff --git a/src/web/src/lib/community/message-payload.test.ts b/src/web/src/lib/community/message-payload.test.tsindex 4db5ffe1e..0acc883f9 100644--- a/src/web/src/lib/community/message-payload.test.ts+++ b/src/web/src/lib/community/message-payload.test.ts@@ -71,11 +71,14 @@ describe("mapMessageForApi", () => {expect(out.replyTo).toEqual({ id: "m-gone", authorName: "Unknown", text: "", deleted: true })})- it("truncates reply preview text to MESSAGE_PREVIEW_LENGTH", () => {+ it("gives API and WS projections the same ellipsized reply preview", () => {const long = "x".repeat(500)const replyMap = new Map([["m0", { id: "m0", authorName: "Bob", content: long }]])- const out = mapMessageForApi({ ...baseRow, replyToId: "m0" }, { ...emptyApiCtx, replyMap })- expect(out.replyTo?.text.length).toBeLessThan(500)+ const apiOut = mapMessageForApi({ ...baseRow, replyToId: "m0" }, { ...emptyApiCtx, replyMap })+ const wsOut = mapMessageForWs({ ...baseRow, replyToId: "m0" }, { ...emptyWsCtx, replyMap })+ const expected = `${"x".repeat(119)}…`+ expect(apiOut.replyTo?.text).toBe(expected)+ expect(wsOut.replyTo?.text).toBe(expected)})it("omits attachments/reactions when there are none", () => {diff --git a/src/web/src/lib/community/message-payload.ts b/src/web/src/lib/community/message-payload.tsindex aa8dc84af..8ec522233 100644--- a/src/web/src/lib/community/message-payload.ts+++ b/src/web/src/lib/community/message-payload.ts@@ -14,7 +14,7 @@* embeds pass-through, and mentionType projection so adding/removing a* field on the wire is one edit, not four.*/-import { MESSAGE_PREVIEW_LENGTH, type MentionType } from "@alook/shared"+import { truncateMessagePreview, type MentionType } from "@alook/shared"import type { FriendApprovalPayload } from "@alook/shared"import { avatarInitial } from "@/lib/community/avatar"@@ -94,7 +94,7 @@ function resolveReply(row: MessageRow, replyMap: Map<string, ReplyTargetRow>): Rreturn {id: target.id,authorName: target.authorName,- text: (target.content ?? "").slice(0, MESSAGE_PREVIEW_LENGTH),+ text: truncateMessagePreview(target.content ?? ""),}}diff --git a/src/web/src/lib/community/reply-preview.test.ts b/src/web/src/lib/community/reply-preview.test.tsnew file mode 100644index 000000000..26a710857--- /dev/null+++ b/src/web/src/lib/community/reply-preview.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from "vitest"+import { MESSAGE_PREVIEW_LENGTH } from "@alook/shared"+import { toOptimisticReplyPreview } from "./reply-preview"++describe("toOptimisticReplyPreview", () => {+ it("gives channel and DM optimistic sends the same bounded preview shape", () => {+ const reply = { id: "m1", authorName: "Alice", text: "x".repeat(MESSAGE_PREVIEW_LENGTH + 1) }+ expect(toOptimisticReplyPreview(reply)).toEqual({+ id: "m1",+ authorName: "Alice",+ text: `${"x".repeat(MESSAGE_PREVIEW_LENGTH - 1)}…`,+ })+ })++ it("uses the shared surrogate-safe boundary", () => {+ const reply = {+ id: "m1",+ authorName: "Alice",+ text: `${"x".repeat(MESSAGE_PREVIEW_LENGTH - 2)}😀tail`,+ }+ expect(toOptimisticReplyPreview(reply).text).toBe(`${"x".repeat(MESSAGE_PREVIEW_LENGTH - 2)}…`)+ })+})diff --git a/src/web/src/lib/community/reply-preview.ts b/src/web/src/lib/community/reply-preview.tsnew file mode 100644index 000000000..52f7343b9--- /dev/null+++ b/src/web/src/lib/community/reply-preview.ts@@ -0,0 +1,5 @@+import { truncateMessagePreview } from "@alook/shared"++export function toOptimisticReplyPreview<T extends { text: string }>(reply: T): T {+ return { ...reply, text: truncateMessagePreview(reply.text) }+}diff --git a/vitest.config.ts b/vitest.config.tsindex 117828a75..296bb9bd8 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -2,7 +2,7 @@ import { defineConfig } from "vitest/config"export default defineConfig({test: {- projects: ["src/shared", "src/web", "src/cli", "src/email-worker", "src/ws-do", "src/app", "tests/utils"],+ projects: ["src/shared", "src/web", "src/cli", "src/daemon", "src/email-worker", "src/ws-do", "src/app", "tests/utils"],coverage: {provider: "v8",include: ["src/**/*.{ts,tsx,js,jsx}"],