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
refactor(web): organize community components (#472)
Gener0436185c2159
diff --git a/scripts/ci/community-architecture-contract.test.ts b/scripts/ci/community-architecture-contract.test.tsnew file mode 100644index 000000000..34d1ad5e3--- /dev/null+++ b/scripts/ci/community-architecture-contract.test.ts@@ -0,0 +1,382 @@+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"+import { tmpdir } from "node:os"+import { dirname, relative, resolve, sep } from "node:path"+import ts from "typescript"+import { describe, expect, it } from "vitest"++type DependencyKind = "static" | "dynamic" | "type"++type ModuleDependency = {+ kind: DependencyKind+ specifier: string+}++type ModuleEdge = {+ kind: DependencyKind+ target: string+}++type CyclicComponent = {+ nodes: string[]+ edges: string[]+}++const repositoryRoot = resolve(import.meta.dirname, "../..")+const webSourceRoot = resolve(repositoryRoot, "src/web/src")+const communityComponentRoot = resolve(webSourceRoot, "components/community")+const guardedLayerRoots = [+ resolve(webSourceRoot, "lib/community"),+ resolve(webSourceRoot, "hooks/community"),+ resolve(webSourceRoot, "stores/community"),+]+const communityModuleRoots = [communityComponentRoot, ...guardedLayerRoots]+const sourceExtensionPattern = /\.(?:ts|tsx)$/+const testFilePattern = /\.(?:test|spec)\.(?:ts|tsx)$/+const testDirectoryPattern = /(?:^|\/)(?:__tests__|test|tests)(?:\/|$)/++function toPosixPath(path: string) {+ return path.split(sep).join("/")+}++function toRepositoryPath(path: string) {+ return toPosixPath(relative(repositoryRoot, path))+}++function isWithin(path: string, root: string) {+ const child = relative(root, path)+ return child === "" || (!child.startsWith("..") && !child.startsWith(sep))+}++function isProductionSource(path: string) {+ const normalized = toPosixPath(path)+ return (+ sourceExtensionPattern.test(normalized) &&+ !testFilePattern.test(normalized) &&+ !testDirectoryPattern.test(normalized) &&+ !normalized.endsWith("/test-harness.ts")+ )+}++function listProductionSources(root: string): string[] {+ return readdirSync(root, { withFileTypes: true })+ .flatMap((entry) => {+ const path = resolve(root, entry.name)+ return entry.isDirectory() ? listProductionSources(path) : isProductionSource(path) ? [path] : []+ })+ .sort()+}++function stringLiteralText(node: ts.Node | undefined) {+ return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))+ ? node.text+ : null+}++function importDeclarationKind(node: ts.ImportDeclaration): DependencyKind {+ const clause = node.importClause+ if (clause?.isTypeOnly) return "type"+ if (+ clause &&+ !clause.name &&+ clause.namedBindings &&+ ts.isNamedImports(clause.namedBindings) &&+ clause.namedBindings.elements.every((element) => element.isTypeOnly)+ ) return "type"+ return "static"+}++function exportDeclarationKind(node: ts.ExportDeclaration): DependencyKind {+ if (node.isTypeOnly) return "type"+ if (+ node.exportClause &&+ ts.isNamedExports(node.exportClause) &&+ node.exportClause.elements.every((element) => element.isTypeOnly)+ ) return "type"+ return "static"+}++function collectModuleDependencies(source: string) {+ const sourceFile = ts.createSourceFile("contract.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)+ const dependencies: ModuleDependency[] = []++ function visit(node: ts.Node) {+ if (ts.isImportDeclaration(node)) {+ const specifier = stringLiteralText(node.moduleSpecifier)+ if (specifier) {+ dependencies.push({ kind: importDeclarationKind(node), specifier })+ }+ } else if (ts.isExportDeclaration(node)) {+ const specifier = stringLiteralText(node.moduleSpecifier)+ if (specifier) {+ dependencies.push({ kind: exportDeclarationKind(node), specifier })+ }+ } else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {+ const specifier = stringLiteralText(node.moduleReference.expression)+ if (specifier) {+ dependencies.push({ kind: node.isTypeOnly ? "type" : "static", specifier })+ }+ } else if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument)) {+ const specifier = stringLiteralText(node.argument.literal)+ if (specifier) {+ dependencies.push({ kind: "type", specifier })+ }+ } else if (+ ts.isCallExpression(node) &&+ node.expression.kind === ts.SyntaxKind.ImportKeyword+ ) {+ const specifier = stringLiteralText(node.arguments[0])+ if (specifier) {+ dependencies.push({ kind: "dynamic", specifier })+ }+ }++ ts.forEachChild(node, visit)+ }++ visit(sourceFile)+ return dependencies+}++function resolveModule(importer: string, specifier: string, sourceRoot: string) {+ let unresolved: string+ if (specifier.startsWith("@/")) {+ unresolved = resolve(sourceRoot, specifier.slice(2))+ } else if (specifier.startsWith(".")) {+ unresolved = resolve(dirname(importer), specifier)+ } else {+ return null+ }++ if (!isWithin(unresolved, sourceRoot)) {+ return null+ }++ const withoutRuntimeExtension = unresolved.replace(/\.(?:js|jsx|mjs|cjs)$/, "")+ const candidates = [+ unresolved,+ `${unresolved}.ts`,+ `${unresolved}.tsx`,+ withoutRuntimeExtension,+ `${withoutRuntimeExtension}.ts`,+ `${withoutRuntimeExtension}.tsx`,+ resolve(unresolved, "index.ts"),+ resolve(unresolved, "index.tsx"),+ ]++ return candidates.find((candidate) => existsSync(candidate) && statSync(candidate).isFile()) ?? null+}++function readDependencies(path: string, sourceRoot = webSourceRoot) {+ return collectModuleDependencies(readFileSync(path, "utf8"))+ .map((dependency) => ({+ ...dependency,+ target: resolveModule(path, dependency.specifier, sourceRoot),+ }))+ .filter((dependency): dependency is ModuleDependency & { target: string } => Boolean(dependency.target))+}++function collectReverseDependencies(+ layerRoots = guardedLayerRoots,+ componentRoot = communityComponentRoot,+ sourceRoot = webSourceRoot,+) {+ const edges = layerRoots.flatMap((root) =>+ listProductionSources(root).flatMap((source) =>+ readDependencies(source, sourceRoot)+ .filter((dependency) => isWithin(dependency.target, componentRoot))+ .map((dependency) => `${dependency.kind} | ${toRepositoryPath(source)} -> ${toRepositoryPath(dependency.target)}`),+ ),+ )+ return [...new Set(edges)].sort()+}++function buildModuleGraph(+ roots: string[],+ sourceRoot: string,+ includedKinds: ReadonlySet<DependencyKind> = new Set(["static", "dynamic", "type"]),+) {+ const sources = roots.flatMap(listProductionSources)+ const sourceSet = new Set(sources)+ return new Map(+ sources.map((source) => [+ toRepositoryPath(source),+ [...new Map(+ readDependencies(source, sourceRoot)+ .filter((dependency) => includedKinds.has(dependency.kind) && sourceSet.has(dependency.target))+ .map((dependency) => {+ const edge = { kind: dependency.kind, target: toRepositoryPath(dependency.target) }+ return [`${edge.kind}:${edge.target}`, edge] as const+ }),+ ).values()].sort((left, right) =>+ `${left.kind}:${left.target}`.localeCompare(`${right.kind}:${right.target}`),+ ),+ ]),+ )+}++function collectCyclicComponents(graph: ReadonlyMap<string, readonly ModuleEdge[]>) {+ let nextIndex = 0+ const indices = new Map<string, number>()+ const lowLinks = new Map<string, number>()+ const stack: string[] = []+ const onStack = new Set<string>()+ const components: CyclicComponent[] = []++ function visit(node: string) {+ indices.set(node, nextIndex)+ lowLinks.set(node, nextIndex)+ nextIndex += 1+ stack.push(node)+ onStack.add(node)++ for (const edge of graph.get(node) ?? []) {+ if (!indices.has(edge.target)) {+ visit(edge.target)+ lowLinks.set(node, Math.min(lowLinks.get(node)!, lowLinks.get(edge.target)!))+ } else if (onStack.has(edge.target)) {+ lowLinks.set(node, Math.min(lowLinks.get(node)!, indices.get(edge.target)!))+ }+ }++ if (lowLinks.get(node) !== indices.get(node)) return++ const nodes: string[] = []+ let member: string+ do {+ member = stack.pop()!+ onStack.delete(member)+ nodes.push(member)+ } while (member !== node)+ nodes.sort()++ const nodeSet = new Set(nodes)+ const hasSelfLoop = nodes.some((source) =>+ (graph.get(source) ?? []).some((edge) => edge.target === source),+ )+ const edges = nodes.flatMap((source) =>+ (graph.get(source) ?? [])+ .filter((edge) => nodeSet.has(edge.target))+ .map((edge) => `${source} -[${edge.kind}]-> ${edge.target}`),+ ).sort()+ if (nodes.length > 1 || hasSelfLoop) {+ components.push({ nodes, edges })+ }+ }++ for (const node of [...graph.keys()].sort()) {+ if (!indices.has(node)) {+ visit(node)+ }+ }++ return components.sort((left, right) => left.nodes.join("\n").localeCompare(right.nodes.join("\n")))+}++const allowedReverseDependencies: string[] = []+const allowedFullDependencyComponents: CyclicComponent[] = []+const allowedRuntimeDependencyComponents: CyclicComponent[] = []++describe("community architecture contract", () => {+ it("recognizes every supported module dependency syntax", () => {+ expect(+ collectModuleDependencies(`+ import value from "@/components/community/value"+ import type { Model } from "@/components/community/model"+ export { view } from "@/components/community/view"+ export type { Model as ExportedModel } from "@/components/community/export-model"+ type LazyModel = import("@/components/community/lazy-model").LazyModel+ const lazy = import("@/components/community/lazy")+ `),+ ).toEqual([+ { kind: "static", specifier: "@/components/community/value" },+ { kind: "type", specifier: "@/components/community/model" },+ { kind: "static", specifier: "@/components/community/view" },+ { kind: "type", specifier: "@/components/community/export-model" },+ { kind: "type", specifier: "@/components/community/lazy-model" },+ { kind: "dynamic", specifier: "@/components/community/lazy" },+ ])+ })++ it("detects dynamic cycles and changes the signature when a chord is added", () => {+ const fixtureRoot = mkdtempSync(resolve(tmpdir(), "community-architecture-"))+ try {+ writeFileSync(resolve(fixtureRoot, "a.ts"), 'import "./b"\n')+ writeFileSync(resolve(fixtureRoot, "b.ts"), 'export { value } from "@/c"\n')+ writeFileSync(resolve(fixtureRoot, "c.ts"), 'void import("./a")\nexport const value = 1\n')++ const a = toRepositoryPath(resolve(fixtureRoot, "a.ts"))+ const b = toRepositoryPath(resolve(fixtureRoot, "b.ts"))+ const c = toRepositoryPath(resolve(fixtureRoot, "c.ts"))+ const withoutChord = collectCyclicComponents(buildModuleGraph([fixtureRoot], fixtureRoot))+ expect(withoutChord).toEqual([{+ nodes: [a, b, c],+ edges: [+ `${a} -[static]-> ${b}`,+ `${b} -[static]-> ${c}`,+ `${c} -[dynamic]-> ${a}`,+ ].sort(),+ }])++ writeFileSync(resolve(fixtureRoot, "a.ts"), 'import "./b"\nvoid import("./c")\n')+ const withChord = collectCyclicComponents(buildModuleGraph([fixtureRoot], fixtureRoot))+ expect(withChord).toEqual([{+ nodes: [a, b, c],+ edges: [+ `${a} -[dynamic]-> ${c}`,+ `${a} -[static]-> ${b}`,+ `${b} -[static]-> ${c}`,+ `${c} -[dynamic]-> ${a}`,+ ].sort(),+ }])+ expect(withChord).not.toEqual(withoutChord)+ } finally {+ rmSync(fixtureRoot, { recursive: true, force: true })+ }+ })++ it("changes the reverse-edge signature when a type import becomes runtime", () => {+ const fixtureRoot = mkdtempSync(resolve(tmpdir(), "community-reverse-edge-"))+ const components = resolve(fixtureRoot, "components/community")+ const hooks = resolve(fixtureRoot, "hooks/community")+ try {+ mkdirSync(components, { recursive: true })+ mkdirSync(hooks, { recursive: true })+ const target = resolve(components, "model.ts")+ const importer = resolve(hooks, "use-model.ts")+ writeFileSync(target, "export type Model = { id: string }\nexport const value = 1\n")+ writeFileSync(importer, 'import type { Model } from "@/components/community/model"\nexport type Result = Model\n')++ const typeOnly = collectReverseDependencies([hooks], components, fixtureRoot)+ expect(typeOnly).toEqual([+ `type | ${toRepositoryPath(importer)} -> ${toRepositoryPath(target)}`,+ ])++ writeFileSync(importer, 'import { value } from "@/components/community/model"\nexport const result = value\n')+ const runtime = collectReverseDependencies([hooks], components, fixtureRoot)+ expect(runtime).toEqual([+ `static | ${toRepositoryPath(importer)} -> ${toRepositoryPath(target)}`,+ ])+ expect(runtime).not.toEqual(typeOnly)+ } finally {+ rmSync(fixtureRoot, { recursive: true, force: true })+ }+ })++ it("does not add lower-layer imports from community components", () => {+ expect(collectReverseDependencies()).toEqual(allowedReverseDependencies)+ })++ it("does not add production community dependency cycles", () => {+ expect(collectCyclicComponents(buildModuleGraph(communityModuleRoots, webSourceRoot))).toEqual(+ allowedFullDependencyComponents,+ )+ })++ it("does not add production community runtime dependency cycles", () => {+ expect(+ collectCyclicComponents(+ buildModuleGraph(communityModuleRoots, webSourceRoot, new Set(["static", "dynamic"])),+ ),+ ).toEqual(allowedRuntimeDependencyComponents)+ })+})diff --git a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsxindex 07dba70f2..3fb3aafb2 100644--- a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx+++ b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx@@ -1,7 +1,7 @@"use client"import { useParams } from "next/navigation"-import { ChannelRoute } from "@/components/community/channel-route"+import { ChannelRoute } from "@/components/community/channels/channel-route"export default function ChannelPage() {const params = useParams<{ serverId: string; channelId: string }>()diff --git a/src/web/src/app/c/channels/[serverId]/page.tsx b/src/web/src/app/c/channels/[serverId]/page.tsxindex f7f689787..0dd2f2567 100644--- a/src/web/src/app/c/channels/[serverId]/page.tsx+++ b/src/web/src/app/c/channels/[serverId]/page.tsx@@ -2,7 +2,7 @@import { useEffect } from "react"import { useParams, useRouter } from "next/navigation"-import { MessageList } from "@/components/community/message-list"+import { MessageList } from "@/components/community/messages/message-list"import { Skeleton } from "@/components/ui/skeleton"import { useServer } from "@/hooks/community/use-servers"import { getLastChannel, pickServerLandingChannel } from "@/lib/community/last-channel"diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsxindex f8c00d71a..4173a5dac 100644--- a/src/web/src/app/c/channels/layout.tsx+++ b/src/web/src/app/c/channels/layout.tsx@@ -9,15 +9,16 @@ import { communityKeys } from "@/lib/query-keys"import { markSwitch } from "@/lib/perf/switch-mark"import { Dialog, DialogContent } from "@/components/ui/dialog"import { useBreakpoint } from "@/hooks/use-mobile"-import { useChannelTree } from "@/components/community/use-channel-tree"+import { useChannelTree } from "@/components/community/channels/use-channel-tree"import { patchChannelUnread } from "@/hooks/community/server-detail-cache"import type { ServerDetail } from "@/hooks/community/use-servers"-import { ShellFrame } from "@/components/community/shell-frame"-import { ChannelSidebar } from "@/components/community/channel-sidebar"-import { ServerSettings } from "@/components/community/server-settings"+import { ShellFrame } from "@/components/community/shell/shell-frame"+import { ChannelSidebar } from "@/components/community/channels/channel-sidebar"+import { ServerSettings } from "@/components/community/settings/server-settings"import { ImageCropDialog } from "@/components/community/image-crop-dialog"import { validateIconSourceFile } from "@/lib/community/image-crop"-import type { MobileZone, SettingsSection } from "@/components/community/_types"+import type { MobileZone } from "@/components/community/shell/mobile-zone"+import type { SettingsSection } from "@/components/community/settings/settings-types"import { canManageServer, isForum, notifLevelDisplay, type ChannelType } from "@alook/shared"import { resolveRowPresence } from "@/lib/community/presence"import {@@ -31,7 +32,7 @@ import { useServerMembers } from "@/hooks/community/use-server-members"import {consumeVoluntaryLeave,runAuthoritativeServerEject,-} from "@/components/community/eject-server"+} from "@/lib/community/eject-server"import { clearLastChannel } from "@/lib/community/last-channel"import { getLastMeLeaf, pickMeLandingLocation } from "@/lib/community/last-me-location"import { usePresence } from "@/hooks/community/use-server-panels"diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsxindex 9fca16697..0f8f6fbd9 100644--- a/src/web/src/app/c/me/[dmId]/page.tsx+++ b/src/web/src/app/c/me/[dmId]/page.tsx@@ -4,12 +4,13 @@ import { useCallback, useEffect, useMemo, useState } from "react"import { useParams, useSearchParams } from "next/navigation"import { toast } from "sonner"import { useBreakpoint } from "@/hooks/use-mobile"-import { DmHeader, DmHeaderSkeleton } from "@/components/community/dm-header"+import { DmHeader, DmHeaderSkeleton } from "@/components/community/channels/dm-header"import { Avatar } from "@/components/community/avatar"-import { MessageList } from "@/components/community/message-list"-import { MessageContextSheet } from "@/components/community/message-context-sheet"-import { Composer, ComposerSkeleton, type SendAttachment } from "@/components/community/composer"-import type { FileAttachment, ImagePreview, OpenProfile } from "@/components/community/_types"+import { MessageList } from "@/components/community/messages/message-list"+import { MessageContextSheet } from "@/components/community/messages/message-context-sheet"+import { Composer, ComposerSkeleton, type SendAttachment } from "@/components/community/messages/composer"+import type { FileAttachment, ImagePreview } from "@/lib/community/models/message"+import type { OpenProfile } from "@/components/community/social/profile-types"import {useCommunityStore,useCurrentChannelId,diff --git a/src/web/src/app/c/me/layout.tsx b/src/web/src/app/c/me/layout.tsxindex 7aba31cd6..d26907e62 100644--- a/src/web/src/app/c/me/layout.tsx+++ b/src/web/src/app/c/me/layout.tsx@@ -4,9 +4,9 @@ import { useCallback, useEffect, useMemo, useState, type ReactNode } from "reactimport { useQueryClient } from "@tanstack/react-query"import { usePathname, useRouter, useParams } from "next/navigation"import { useBreakpoint } from "@/hooks/use-mobile"-import { ShellFrame } from "@/components/community/shell-frame"-import { DmSidebar } from "@/components/community/dm-sidebar"-import type { MobileZone } from "@/components/community/_types"+import { ShellFrame } from "@/components/community/shell/shell-frame"+import { DmSidebar } from "@/components/community/channels/dm-sidebar"+import type { MobileZone } from "@/components/community/shell/mobile-zone"import { useCommunityStore, useCurrentChannelId } from "@/stores/community"import { useDms } from "@/hooks/community/use-dms"import { useFriends, useFriendsPresence } from "@/hooks/community/use-friends"diff --git a/src/web/src/app/c/me/page.tsx b/src/web/src/app/c/me/page.tsxindex 9ee149974..3850e5779 100644--- a/src/web/src/app/c/me/page.tsx+++ b/src/web/src/app/c/me/page.tsx@@ -2,7 +2,7 @@import { useRouter } from "next/navigation"import { useBreakpoint } from "@/hooks/use-mobile"-import { FriendsPage } from "@/components/community/friends-page"+import { FriendsPage } from "@/components/community/social/friends-page"import { useMemo } from "react"import { useFriends } from "@/hooks/community/use-friends"import { useUiHandlers } from "@/stores/community"diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.tsdeleted file mode 100644index 101ea4934..000000000--- a/src/web/src/components/community/_types.ts+++ /dev/null@@ -1,420 +0,0 @@-/**- * Shared view models for the community UI.- *- * These are render-ready shapes — denormalized and formatted for display, not raw DB- * rows. The query layer produces them by joining the underlying tables (e.g. an author- * id → name/avatar, reactions aggregated per message). Field names align with the- * schema columns so the same components work for both mock and live data.- *- * Per-component `*Props` interfaces do NOT live here — they stay in each component- * file. Only types shared across two or more components belong in this file.- */--import type React from "react"-import type { ChannelType, CommunityRole, MentionKind } from "@alook/shared"-import type { EntityKind } from "./entity-icon"--// ── Presence / enums ───────────────────────────────────────────────────────-export type Presence = "online" | "offline"--export type RightPanel = "members" | "pinned" | "search" | "threads" | null-export type MobileZone = "nav" | "messages"-export type View = "server" | "dm" | "settings"-export type MessagePerspective = "sender" | "recipient" | "neutral"-export type SettingsSection =- | "overview"- | "members"- | "invites"- | "notifications"--// ── Servers / rail ───────────────────────────────────────────────────────────-export type Server = {- id: string // nanoid- name: string- discriminator?: string- initial: string- active: boolean- mentions: number- isOwner?: boolean- icon?: string | null-}--export type FolderServer = {- id: string- initial: string- name: string- icon?: string | null-}--export type CommunityFolder = {- id: string- name: string- position: number- servers: FolderServer[]-}--// ── Channels / categories ────────────────────────────────────────────────────-export type Channel = {- id: string // nanoid- name: string- active: boolean- unread: boolean- muted?: boolean- type?: ChannelType- tags?: string[]- creatorId?: string | null- // Optimistic placeholder row — non-interactive until the create resolves.- pending?: boolean-}--export type Category = {- id: string- name: string- channels: Channel[]- private?: number | boolean- creatorId?: string | null- // Optimistic placeholder category — reconciled when the create resolves.- pending?: boolean-}--// ── Messages ───────────────────────────────────────────────────────────────-type AttachmentMetadata = {- name: string- url: string- contentType?: string- sizeBytes?: number-}--export type FileAttachment = AttachmentMetadata & { kind: "file"; size: string }--export type Attachment =- | (AttachmentMetadata & { kind: "image"; thumbnailUrl?: string; width?: number; height?: number })- | FileAttachment--export type ImagePreview = { originalUrl: string; thumbnailUrl?: string; name: string }--type Embed = {- provider?: string- url?: string- title: string- desc?: string- color?: string- image?: { url: string; width?: number; height?: number }- thumbnail?: { url: string }- fields?: { name: string; value: string; inline?: boolean }[]- footer?: { text: string; iconUrl?: string }- author?: { name: string; url?: string; iconUrl?: string }-}--export type Reaction = { emoji: string; count: number; me: boolean; userIds: string[] }--export type Msg = {- id: string // nanoid- // Exhaustive discriminator (#12 — was `type?: "system"`, an incomplete- // partial discriminator that let `!m.type` silently misclassify a future- // third kind as an ordinary chat message). `mapMessageForApi`/`mapMessageForWs`- // always emit one of these two values now — never `undefined`.- type: "chat" | "system"- // Only ever set alongside `type: "system"` for a thread-creation system- // message (see `message-payload.ts`'s `splitType`). The `"join"` value- // that used to be part of this type is removed — no code path has ever- // produced it (join notifications are pure WS events with no persisted- // message row, and stay that way — see the debt-record's Out of scope).- systemKind?: "thread"- // Author's user id — populated by `mapMessageForApi` / WS message-create,- // consumed by `useChannelWatermark` to skip self-authored messages when- // advancing the read pointer. Optional to keep optimistic rows valid- // before the server response reconciles.- authorId?: string- authorName?: string- color?: string- seq?: number // Per-scope (channel/DM) monotonic sequence number- createdAt?: string // ISO 8601 timestamp — the UI formats for display- authorAvatar?: string- failed?: boolean- // Idempotency nonce (mutation-idempotency plan). Stamped on optimistic rows- // this client created and echoed back on the WS message-create, so a- // 500-after-commit send that the user never retried self-heals: the WS row- // reconciles the failed optimistic row by nonce instead of appearing twice.- clientNonce?: string- content?: string- embeds?: Embed[]- attachments?: Attachment[]- reactions?: Reaction[]- replyTo?: { id: string; authorName: string; text: string; deleted?: boolean }- thread?: {- id: string- name: string- messageCount: number- lastReplyAt?: string- tags?: string[]- preview?: string- participants?: { id: string; name: string; avatar: string }[]- participantCount?: number- }- // Present only on a friend-approval DM card. Its presence (not the message- // `type`) is the discriminator for rendering <BotApprovalCard>.- approval?: import("@alook/shared").FriendApprovalPayload-}--// `grouped` is a RENDER-TIME decision (computed by `message-list.tsx`'s-// cluster-building `useMemo`, based on adjacent messages' author/timestamp)-// — never a fact about a message itself, so it never belonged on `Msg`-// (#7). `<Message>` and any other consumer that needs the clustering-// decision takes a `RenderMsg`, not a bare `Msg` with `grouped` spread on.-export type RenderMsg = Msg & { grouped: boolean }--// ── Threads / forum ──────────────────────────────────────────────────────────-// Child-thread summaries shown in side panels and forum lists. Actual-// message content for a thread or post is loaded into `ctx.messages` once the-// user navigates into the child channel — these summaries don't carry messages.-export type Thread = {- id: string // nanoid- name: string- messageCount: number- lastMessageAt: string- parent: { authorName: string; text: string }- // The root message's per-channel seq, when the thread was created from a- // parent message (omitted only for legacy rootless threads).- // Used by `channel-ref-pill.tsx` to match a `/server/channel/#N` ref.- parentSeq?: number- // Stable opener identity used to reconcile forum-title edits without- // accidentally patching a same-named or re-rooted child.- openerMessageId?: string-}--export type ForumThread = Thread & {- authorId: string- authorAvatar: string- openerMessageId: string- tags: string[]- preview: string- // The post's participant (notify) set — creator first, then whoever- // spoke/was mentioned/was added. Drives the card's AvatarGroup. Always- // present (empty for a post with no participant rows yet, e.g. one created- // before the notify-scope change shipped).- participants: { id: string; name: string; avatar: string }[]- // Total participant rows before the card-preview cap is applied.- participantCount: number-}--// ── Members / friends / DMs ──────────────────────────────────────────────────-export type Role = CommunityRole--export { canManageServer, isServerOwner, ROLES, isPresenceOnline, isPresenceOffline } from "@alook/shared"--// Identity fields shared by every community user view-model (member / friend /-// DM). All three are required `string`: `user.name`/`user.discriminator` are-// NOT NULL columns always projected on live payloads. Requiring `discriminator`-// here (in one place) moves the "a mention target always has a tag" guarantee-// to compile time — see plans/mandatory-mention-discriminator.md. `userId` is-// NOT part of the core: it's required on Member/DM but optional on Friend, so-// each type declares it. Only types whose identity fields are identically-// shaped extend this — AddableMember/ThreadParticipant (nullable projections),-// Profile/UserProfile (renamed/merged shapes) intentionally stay standalone.-export type CommunityUserCore = {- name: string- discriminator: string- avatar: string-}--export type Member = CommunityUserCore & {- id: string- userId: string- status: Presence- sub: string- role: Role- // Custom status (emoji + short term) — see `Profile.statusEmoji`/`statusText`.- statusEmoji?: string | null- statusText?: string | null- // Populated only when the drawer shows a private channel/post roster or a- // thread participant set — drives the row's Leave/Remove right-click menu.- // - isCreator: this user owns the unit (row locked — never removable/leaveable).- // - source: for a channel/post, only "explicit" rows are removable (an- // admin-by-role or inherited public member isn't an explicit roster row).- // Thread participants are always "explicit"-equivalent (a real row).- isCreator?: boolean- source?: "explicit" | "inherited" | "admin"-}--export type Friend = CommunityUserCore & {- id: string- // Optional here (unlike Member/DM) — some friend rows predate a resolved- // userId; that's the one field that keeps Friend from a plain intersection.- userId?: string- status: Presence- sub: string- // Custom status (emoji + short term) — see `Profile.statusEmoji`/`statusText`.- statusEmoji?: string | null- statusText?: string | null-}--export type PendingRequest = {- id: string- userId: string- name: string- avatar: string- kind: "incoming" | "outgoing"- // The gating owner id while a bot-touched row is pending; null once- // unlocked. Drives whether Approve/Reject buttons render.- needsOwnerApproval?: string | null-}--export type BlockedUser = { id: string; userId?: string; name: string; avatar: string }--// DM summary shown in the DM sidebar. Actual conversation history is loaded-// into `ctx.messages` once the user opens the DM — DM summaries don't carry-// inline messages.-export type DM = CommunityUserCore & {- id: string // DM conversation nanoid — NOT the peer's user id (that's `userId`)- userId: string- status: Presence- preview: string- unread?: boolean-}--// ── Profile ──────────────────────────────────────────────────────────────────-export type Profile = {- name: string- // Stable user id of the profile's owner — the exact-match key for DM-target- // resolution and self-detection (never match by non-unique display name).- // Optional so mock/older Profile-constructing sites keep type-checking.- userId?: string- // Variable-width (≥4-digit) decimal discriminator derived from user.id- // (`"0042"`, widens on collision) — undefined while the profile fetch is in- // flight. Shown at its true width, never re-padded. See computeDiscriminator- // in @alook/shared.- discriminator?: string- avatar: string- contextLabel?: string- about: string- mutual: number- // Live online/offline dot on the card's avatar — undefined when no- // member/friend match could be resolved (e.g. a stale mention). See- // `resolveProfilePresence` in shell-frame.tsx.- presence?: Presence-}--// ── Settings rows ──────────────────────────────────────────────────────────-export type InviteRow = {- code: string- uses: number- maxUses: number | null // null = unlimited- expiresAt: string | null // ISO timestamp or null = never- by: string- creatorId: string | null-}---// ── Mentions / inbox ─────────────────────────────────────────────────────────-export type Mention = {- id: string- // "mention" (@-mention) vs "reply" (reply to your message). Drives the row- // label ("mentioned you" vs "replied to you"). Optional for back-compat with- // any cached payload written before the field existed.- kind?: MentionKind- server: string- serverId?: string- channel: string- channelId?: string- m: Msg-}--// A single per-user saved ("marked") message, as returned by-// `/api/community/users/me/marks`. Cross-channel newest-first — each row carries-// the serverId + channelId + seq needed to deep-link back to the message-// (unlike a Mention, which only opens the channel, a Marked row jumps to the-// exact message via the `?msg=<id>` deep-link). `id` is the mark row's own id,-// used to unmark from the list.-export type Marked = {- id: string // the mark row id (for DELETE / list removal)- // A DM has no server: `serverId` is null and `server` may be the peer's name- // or empty. The null serverId is the discriminator the jump uses — server- // rows deep-link via `?msg=`, DM rows navigate to `/c/me/<channelId>` and- // open the context sheet.- server: string- serverId: string | null- channel: string- // For a server message this is the channel id; for a DM it's the DM channel- // id, which is also the frontend `/c/me/<id>` route param.- channelId: string- m: Msg-}--// A single unread child thread nested under its parent channel.-type UnreadChild = {- channelId: string- channelName: string- // Raw stored channel type — drives the inbox entity icon (thread →- // MessagesSquare). Optional for backward-compat with cached responses.- type?: EntityKind- lastMessageAt: string- mentionCount: number- // Present when this row projects an unread opener from the parent forum.- // The child id remains the navigation target; this opener id is the parent- // channel's progressive-read target.- openerMessageId?: string-}--// "Unreads" — channels with unread messages, grouped by server. Each channel-// may carry `children` (unread child threads) rendered as indented-// sub-rows; a parent can appear solely to host unread children.-export type UnreadServer = {- serverId: string- serverName: string- channels: Array<{- channelId: string- channelName: string- // Raw stored channel type — drives the inbox entity icon so a forum- // channel shows the forum glyph, not a generic hash.- type?: EntityKind- lastMessageAt: string- mentionCount: number- children: UnreadChild[]- }>-}--// "Unreads" — DMs with unread messages, rendered as a flat sibling section-// under the same Unreads tab as channels.-export type UnreadDm = {- // The DM's channel id (a DM is a channel now). Kept as the row's stable key- // and the value passed to `onOpenDm` / the `/c/me/:id` route.- channelId: string- otherUserId: string- otherUserName: string- otherUserAvatar: string- lastMessageAt: string-}--// Shared callback signature for opening a user's profile card at a click point.-// `userId` is the exact-match disambiguator — pass it whenever the caller-// already has the clicked person's userId (member rows, message authors,-// thread openers) so same-named members never collide. `discriminator` is-// the fallback disambiguator for a mention pill, which only carries a-// `#0042` tag (see message-markdown.tsx) and no userId.-export type OpenProfile = (- name: string,- e: React.MouseEvent,- discriminator?: string,- userId?: string,-) => void--// Passed to the Members drawer when it's showing a private channel/post roster-// OR a thread's participants — the row right-click menu becomes Leave (self,-// non-creator) / Remove (viewer is the unit creator, on other explicit members)-// instead of the server-scoped Role/Kick menu. Remove is CREATOR-ONLY on every-// unit (admins have no content privilege). The creator's own row is locked.-export type MemberManageContext = {- viewerUserId: string- // The viewer created this unit → their own row shows no Leave (owners keep- // the unit), and they may Remove other explicit members.- viewerIsCreator: boolean- // The unit's display name (channel/post/thread), used in the Leave confirm- // dialog title ("Leave /general?"). Optional for back-compat.- unitLabel?: string- // Return a promise so the confirm dialog can show a loading state until the- // remove settles. Resolved value is ignored (mutateAsync resolves to the API- // payload) — the dialog only awaits settlement.- onLeave: (userId: string) => Promise<unknown> | void- onRemove: (userId: string) => Promise<unknown> | void-}diff --git a/src/web/src/components/community/avatar.tsx b/src/web/src/components/community/avatar.tsxindex 778aadc22..728a86932 100644--- a/src/web/src/components/community/avatar.tsx+++ b/src/web/src/components/community/avatar.tsx@@ -1,7 +1,7 @@import type React from "react"import { AvatarBadge } from "@/components/ui/avatar"import { ProfileAvatar } from "@/components/avatar"-import type { Presence } from "./_types"+import type { Presence } from "@/lib/community/models/people"const STATUS_COLOR: Record<Presence, string> = {online: "var(--status-online)",diff --git a/src/web/src/components/community/bots/bot-activity-heatmap.tsx b/src/web/src/components/community/bots/bot-activity-heatmap.tsxindex a381f1866..2392b6749 100644--- a/src/web/src/components/community/bots/bot-activity-heatmap.tsx+++ b/src/web/src/components/community/bots/bot-activity-heatmap.tsx@@ -7,18 +7,7 @@ import {TooltipContent,TooltipTrigger,} from "@/components/ui/tooltip"--// One day's activity for a bot: post-gate messages handled + messages the bot-// sent. Both counts are non-negative integers; a day with no activity is 0/0.-// Field names match the backend rollup contract (Cecilia /Gus/working #617):-// `{ day, handledCount, sentCount }[]`, past 30 days, missing days padded 0.-// A brand-new bot returns [] (normal, not an error) — we render 30 empty cells.-export type BotActivityDay = {- // Calendar day, "YYYY-MM-DD".- day: string- handledCount: number- sentCount: number-}+import type { BotActivityDay } from "@/lib/community/models/people"// Gus asked for "past 30 days" (Gus /Gus/uiux #608). Responsive layout is set// in the grid classes below: mobile = full-width 3×10 ribbon, desktop = a thindiff --git a/src/web/src/components/community/bots/bot-list-controller.test.ts b/src/web/src/components/community/bots/bot-list-controller.test.tsnew file mode 100644index 000000000..5c95dbe57--- /dev/null+++ b/src/web/src/components/community/bots/bot-list-controller.test.ts@@ -0,0 +1,585 @@+import React from "react"+import { readFileSync } from "node:fs"+import { dirname, resolve } from "node:path"+import { fileURLToPath } from "node:url"+import TestRenderer, { act } from "react-test-renderer"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import type { BotSummary } from "@/hooks/community/use-bots"+import type { BotListController } from "./bot-list-types"++const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..")+const readWebSource = (path: string) => readFileSync(resolve(webRoot, path), "utf8")++const mocks = vi.hoisted(() => ({+ hookOrder: [] as string[],+ target: "mac1" as string | null,+ bots: [] as BotSummary[],+ machines: [] as Array<Record<string, unknown>>,+ botsLoading: false,+ machinesLoading: false,+ online: new Set<string>(),+ onboardingSnapshot: null as Record<string, unknown> | null,+ actionState: null as Record<string, unknown> | null,+ push: vi.fn(),+ createDm: vi.fn(),+ del: vi.fn(),+ resetBot: vi.fn(),+ resetMachine: vi.fn(),+ advance: vi.fn(),+ updateResources: vi.fn(),+ recoverMachine: vi.fn(),+ toastSuccess: vi.fn(),+ toastError: vi.fn(),+ toastApiError: vi.fn(),+}))++vi.mock("next/navigation", () => ({+ useRouter: () => {+ mocks.hookOrder.push("router")+ return { push: mocks.push }+ },+ useSearchParams: () => {+ mocks.hookOrder.push("searchParams")+ return { get: () => mocks.target }+ },+}))+vi.mock("@/hooks/community/use-bots", () => ({+ useBots: () => {+ mocks.hookOrder.push("bots")+ return { bots: mocks.bots, isLoading: mocks.botsLoading }+ },+ useDeleteBot: () => {+ mocks.hookOrder.push("delete")+ return { mutateAsync: mocks.del }+ },+ useResetBotSession: () => {+ mocks.hookOrder.push("resetBot")+ return { mutateAsync: mocks.resetBot }+ },+ useResetMachineAgents: () => {+ mocks.hookOrder.push("resetMachine")+ return { mutateAsync: mocks.resetMachine }+ },+}))+vi.mock("@/hooks/community/use-machines", () => ({+ useMachines: () => {+ mocks.hookOrder.push("machines")+ return { machines: mocks.machines, isLoading: mocks.machinesLoading }+ },+}))+vi.mock("@/stores/community/ws", () => ({+ useOnlineUserIds: () => {+ mocks.hookOrder.push("online")+ return mocks.online+ },+}))+vi.mock("@/hooks/community/mutations", () => ({+ useCreateOrGetDm: () => {+ mocks.hookOrder.push("dm")+ return { mutateAsync: mocks.createDm }+ },+}))+vi.mock("@/lib/community-onboarding", () => ({+ useCommunityOnboarding: () => {+ mocks.hookOrder.push("onboarding")+ return mocks.onboardingSnapshot+ },+ readCommunityOnboardingState: () => mocks.actionState,+ advanceCommunityOnboarding: mocks.advance,+ updateCommunityOnboardingResources: mocks.updateResources,+ recoverCommunityOnboardingMachine: mocks.recoverMachine,+}))+vi.mock("sonner", () => ({+ toast: { success: mocks.toastSuccess, error: mocks.toastError },+}))+vi.mock("@/lib/api/client", () => ({ toastApiError: mocks.toastApiError }))++import { useBotListController } from "./bot-list-controller"++let latest: BotListController+function Probe() {+ const controller = useBotListController()+ React.useLayoutEffect(() => {+ latest = controller+ }, [controller])+ return React.createElement("div", {+ ref: (element: HTMLDivElement | null) => {+ Reflect.set(controller.groupRefs.current, "mac1", element)+ Reflect.set(controller.groupRefs.current, "mac2", element)+ },+ })+}++const bot = (id: string, machineId: string): BotSummary => ({+ id,+ name: id,+ description: "",+ image: null,+ machineId,+ runtime: "claude",+ modelName: null,+ lastRefreshContextAt: null,+ dailyActivity: [],+})++describe("useBotListController", () => {+ const scrollIntoView = vi.fn()++ beforeEach(() => {+ vi.clearAllMocks()+ vi.useFakeTimers()+ mocks.hookOrder.length = 0+ mocks.target = "mac1"+ mocks.bots = [bot("b1", "mac1")]+ mocks.machines = [+ { id: "mac1", displayName: "One", hostname: "one", status: "online" },+ { id: "mac2", displayName: "Two", hostname: "two", status: "online" },+ ]+ mocks.online = new Set()+ mocks.onboardingSnapshot = null+ mocks.actionState = null+ mocks.createDm.mockResolvedValue({ conversation: { id: "dm1" } })+ mocks.del.mockResolvedValue(undefined)+ mocks.resetBot.mockResolvedValue({ ok: true })+ mocks.resetMachine.mockResolvedValue({ dispatched: 2 })+ scrollIntoView.mockReset()+ })++ afterEach(() => vi.useRealTimers())++ const render = () => {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(Probe), {+ createNodeMock: () => ({ scrollIntoView }),+ })+ })+ return renderer+ }++ it("keeps the exact external hook order and source-owned thirteen states", () => {+ render()+ expect(mocks.hookOrder.slice(0, 9)).toEqual([+ "router",+ "searchParams",+ "bots",+ "machines",+ "online",+ "delete",+ "resetBot",+ "resetMachine",+ "dm",+ ])+ expect(mocks.hookOrder[9]).toBe("onboarding")++ const source = readWebSource("src/components/community/bots/bot-list-controller.ts")+ expect(source.match(/useState(?:<[^\n]+>)?\(/g)).toHaveLength(13)+ expect(source).not.toMatch(/useCallback\(/)+ expect(source.match(/useMemo\(/g)).toHaveLength(1)+ const orderedHooks = [+ "const router = useRouter()",+ "const searchParams = useSearchParams()",+ "const botsQuery = useBots()",+ "const { machines, isLoading: machinesLoading } = useMachines()",+ "const onlineUserIds = useOnlineUserIds()",+ "const [createOpen",+ "const [editingBot",+ "const [editOpen",+ "const [activityBot",+ "const [activityOpen",+ "const [bugReportBot",+ "const [bugReportOpen",+ "const [confirmDelete",+ "const [confirmReset",+ "const [confirmResetMachine",+ "const [collapsedMachines",+ "const [helpOpen",+ "const del = useDeleteBot()",+ "const resetSession = useResetBotSession()",+ "const resetMachineAgents = useResetMachineAgents()",+ "const createOrGetDm = useCreateOrGetDm()",+ "const onboardingState = useCommunityOnboarding()",+ "const groups = useMemo",+ "const [highlightId",+ "const groupRefs = useRef",+ "const scrolledForRef = useRef",+ "useEffect(() =>",+ ]+ const positions = orderedHooks.map((needle) => source.indexOf(needle))+ expect(positions.every((position) => position >= 0)).toBe(true)+ expect(positions).toEqual([...positions].sort((a, b) => a - b))+ expect(source).toContain("}, [targetMachineId, bots.length])")++ for (const path of [+ "src/components/community/bots/bot-list-view.tsx",+ "src/components/community/bots/bot-list-machine-group.tsx",+ "src/components/community/bots/bot-list-overlays.tsx",+ ]) {+ expect(readWebSource(path)).not.toMatch(/\buse[A-Z]\w*\(/)+ }+ })++ it("retains all observable state and both ref-backed lifecycles across loading/data rerenders", () => {+ mocks.target = null+ const renderer = render()+ const refs = latest.groupRefs+ const selected = bot("selected", "mac1")+ const collapsed = new Set(["mac2"])+ act(() => {+ latest.setCreateOpen(true)+ latest.setEditingBot(selected)+ latest.setEditOpen(true)+ latest.setActivityBot(selected)+ latest.setActivityOpen(true)+ latest.setBugReportBot({ id: selected.id, name: selected.name })+ latest.setBugReportOpen(true)+ latest.setConfirmDelete(selected)+ latest.setConfirmReset(selected)+ latest.setConfirmResetMachine("mac2")+ latest.setCollapsedMachines(collapsed)+ latest.setHelpOpen(true)+ })+ mocks.botsLoading = true+ mocks.machinesLoading = true+ mocks.bots = [bot("replacement", "mac2")]+ act(() => renderer.update(React.createElement(Probe)))+ expect(latest.groupRefs).toBe(refs)+ expect(latest.createOpen).toBe(true)+ expect(latest.editingBot).toBe(selected)+ expect(latest.editOpen).toBe(true)+ expect(latest.activityBot).toBe(selected)+ expect(latest.activityOpen).toBe(true)+ expect(latest.bugReportBot).toEqual({ id: "selected", name: "selected" })+ expect(latest.bugReportOpen).toBe(true)+ expect(latest.confirmDelete).toBe(selected)+ expect(latest.confirmReset).toBe(selected)+ expect(latest.confirmResetMachine).toBe("mac2")+ expect(latest.collapsedMachines).toBe(collapsed)+ expect(latest.helpOpen).toBe(true)+ })++ it("groups known machines first and unresolved machines last without dropping bots", () => {+ mocks.bots = [bot("unknown-a", "gone"), bot("known-2", "mac2"), bot("known-1", "mac1"), bot("unknown-b", "lost")]+ mocks.target = null+ render()+ expect(latest.groups.map((group) => group.machineId)).toEqual(["mac1", "mac2", "gone", "lost"])+ expect(latest.groups.flatMap((group) => group.bots.map((item) => item.id))).toEqual([+ "known-1",+ "known-2",+ "unknown-a",+ "unknown-b",+ ])+ expect(latest.machineName("gone")).toBe("Unknown machine")+ })++ it("does nothing without a target or without bots", () => {+ mocks.target = null+ render()+ expect(scrollIntoView).not.toHaveBeenCalled()+ expect(latest.highlightId).toBeNull()+ expect(vi.getTimerCount()).toBe(0)++ mocks.target = "mac1"+ mocks.bots = []+ render()+ expect(scrollIntoView).not.toHaveBeenCalled()+ expect(latest.highlightId).toBeNull()+ expect(vi.getTimerCount()).toBe(0)+ })++ it("clears a normally consumed target after exactly 2000ms", () => {+ render()+ expect(latest.highlightId).toBe("mac1")+ expect(vi.getTimerCount()).toBe(1)+ act(() => vi.advanceTimersByTime(1999))+ expect(latest.highlightId).toBe("mac1")+ act(() => vi.advanceTimersByTime(1))+ expect(latest.highlightId).toBeNull()+ expect(vi.getTimerCount()).toBe(0)+ })++ it("replaces A with B, cancels A's timer, and cleans the active timer on unmount", () => {+ const renderer = render()+ expect(scrollIntoView).toHaveBeenCalledTimes(1)+ expect(vi.getTimerCount()).toBe(1)+ mocks.target = "mac2"+ act(() => renderer.update(React.createElement(Probe)))+ expect(scrollIntoView).toHaveBeenCalledTimes(2)+ expect(latest.highlightId).toBe("mac2")+ expect(vi.getTimerCount()).toBe(1)+ act(() => vi.advanceTimersByTime(1999))+ expect(latest.highlightId).toBe("mac2")+ act(() => renderer.unmount())+ expect(vi.getTimerCount()).toBe(0)+ })++ it("preserves both consumed-target timer quirks verbatim", () => {+ const renderer = render()+ expect(scrollIntoView).toHaveBeenCalledTimes(1)+ expect(scrollIntoView).toHaveBeenCalledWith({ behavior: "smooth", block: "start" })+ expect(latest.highlightId).toBe("mac1")++ act(() => latest.setCollapsedMachines(new Set(["mac1"])))+ mocks.bots = [bot("b1", "mac1"), bot("b2", "mac1")]+ act(() => renderer.update(React.createElement(Probe)))+ expect(latest.collapsedMachines.has("mac1")).toBe(false)+ expect(scrollIntoView).toHaveBeenCalledTimes(1)+ act(() => vi.advanceTimersByTime(2000))+ expect(latest.highlightId).toBe("mac1")++ mocks.target = null+ act(() => renderer.update(React.createElement(Probe)))+ mocks.target = "mac1"+ act(() => renderer.update(React.createElement(Probe)))+ expect(scrollIntoView).toHaveBeenCalledTimes(1)+ act(() => vi.advanceTimersByTime(2000))+ expect(latest.highlightId).toBe("mac1")+ })++ it("derives all three labels from the render snapshot while actions reread current state", () => {+ mocks.target = null+ const renderer = render()+ expect(latest.guidedCreateLabel).toBe("Create a bot")++ mocks.onboardingSnapshot = {+ status: "active",+ stage: "bot",+ botId: "pending",+ guideAvatarSeed: "seed",+ }+ mocks.actionState = null+ act(() => renderer.update(React.createElement(Probe)))+ expect(latest.guidedCreateLabel).toBe("Open bot chat")+ expect(latest.guidedAvatarSeed).toBe("seed")+ act(() => latest.openGuidedCreate())+ expect(latest.createOpen).toBe(true)+ expect(mocks.createDm).not.toHaveBeenCalled()++ mocks.machines = [{ id: "mac1", displayName: "One", status: "offline" }]+ act(() => renderer.update(React.createElement(Probe)))+ expect(latest.guidedCreateLabel).toBe("Connect a machine")++ mocks.onboardingSnapshot = { status: "active", stage: "bot" }+ mocks.machines = [{ id: "mac1", displayName: "One", status: "online" }]+ act(() => renderer.update(React.createElement(Probe)))+ expect(latest.guidedCreateLabel).toBe("Create a bot")+ })++ it("fires the pending-bot DM without awaiting and advances only after it resolves", async () => {+ mocks.target = null+ mocks.onboardingSnapshot = { status: "active", stage: "bot", botId: "pending" }+ mocks.actionState = { status: "active", stage: "bot", botId: "pending" }+ let resolveDm!: (value: { conversation: { id: string } }) => void+ mocks.createDm.mockReturnValue(new Promise((resolve) => { resolveDm = resolve }))+ render()+ let result: void+ act(() => { result = latest.openGuidedCreate() })+ expect(result!).toBeUndefined()+ expect(mocks.createDm).toHaveBeenCalledWith({ userId: "pending" })+ expect(latest.createOpen).toBe(false)+ expect(mocks.advance).not.toHaveBeenCalled()+ expect(mocks.push).not.toHaveBeenCalled()+ await act(async () => {+ resolveDm({ conversation: { id: "dm1" } })+ await Promise.resolve()+ })+ expect(mocks.advance).toHaveBeenCalledWith("bot", "dm", { botId: "pending", dmId: "dm1" })+ expect(mocks.push).toHaveBeenCalledWith("/c/me/dm1")+ })++ it("recovers a missing machine without opening DM or create", () => {+ mocks.target = null+ mocks.machines = [{ id: "mac1", displayName: "One", status: "offline" }]+ mocks.actionState = { status: "active", stage: "bot", botId: "pending" }+ render()+ expect(latest.openGuidedCreate()).toBeUndefined()+ expect(mocks.recoverMachine).toHaveBeenCalledOnce()+ expect(mocks.push).toHaveBeenCalledWith("/c/me/machines")+ expect(mocks.createDm).not.toHaveBeenCalled()+ expect(latest.createOpen).toBe(false)+ })++ it("opens normal chat on success and reports exact failure without navigation", async () => {+ mocks.target = null+ render()+ await act(async () => { await latest.chatWithBot(bot("chat", "mac1")) })+ expect(mocks.createDm).toHaveBeenCalledWith({ userId: "chat" })+ expect(mocks.push).toHaveBeenCalledWith("/c/me/dm1")++ vi.clearAllMocks()+ const error = new Error("no chat")+ mocks.createDm.mockRejectedValue(error)+ await act(async () => { await latest.chatWithBot(bot("chat", "mac1")) })+ expect(mocks.toastApiError).toHaveBeenCalledWith(error, "Failed to open chat")+ expect(mocks.push).not.toHaveBeenCalled()+ })++ it("makes onBotCreated a no-op for inactive or wrong-stage action-time state", async () => {+ mocks.target = null+ render()+ for (const state of [null, { status: "active", stage: "dm" }]) {+ vi.clearAllMocks()+ mocks.actionState = state+ await act(async () => { await latest.onBotCreated(bot("ignored", "mac1")) })+ expect(mocks.updateResources).not.toHaveBeenCalled()+ expect(mocks.createDm).not.toHaveBeenCalled()+ expect(mocks.advance).not.toHaveBeenCalled()+ expect(mocks.push).not.toHaveBeenCalled()+ }+ })++ it("updates a created bot before awaiting DM and advances/pushes only on success", async () => {+ mocks.target = null+ mocks.actionState = { status: "active", stage: "bot" }+ let resolveDm!: (value: { conversation: { id: string } }) => void+ mocks.createDm.mockReturnValue(new Promise((resolve) => { resolveDm = resolve }))+ render()++ let completion!: Promise<void>+ act(() => { completion = latest.onBotCreated(bot("new", "mac1")) })+ expect(mocks.updateResources).toHaveBeenCalledWith({ botId: "new" })+ expect(mocks.updateResources.mock.invocationCallOrder[0])+ .toBeLessThan(mocks.createDm.mock.invocationCallOrder[0]!)+ expect(mocks.advance).not.toHaveBeenCalled()+ expect(mocks.push).not.toHaveBeenCalled()+ await act(async () => {+ resolveDm({ conversation: { id: "dm-new" } })+ await completion+ })+ expect(mocks.advance).toHaveBeenCalledWith("bot", "dm", { botId: "new", dmId: "dm-new" })+ expect(mocks.createDm.mock.invocationCallOrder[0])+ .toBeLessThan(mocks.advance.mock.invocationCallOrder[0]!)+ expect(mocks.advance.mock.invocationCallOrder[0]).toBeLessThan(mocks.push.mock.invocationCallOrder[0])++ vi.clearAllMocks()+ mocks.createDm.mockRejectedValue(new Error("no dm"))+ await act(async () => { await latest.onBotCreated(bot("failed", "mac1")) })+ expect(mocks.updateResources).toHaveBeenCalledWith({ botId: "failed" })+ expect(mocks.toastApiError).toHaveBeenCalledWith(+ expect.any(Error),+ "Bot created, but the chat couldn't open",+ )+ expect(mocks.advance).not.toHaveBeenCalled()+ expect(mocks.push).not.toHaveBeenCalled()+ })++ it("does not dispatch or toast when confirm selections are absent", async () => {+ mocks.target = null+ render()+ await act(async () => {+ await latest.deleteConfirmedBot()+ await latest.resetConfirmedBot()+ await latest.resetConfirmedMachine()+ })+ expect(mocks.del).not.toHaveBeenCalled()+ expect(mocks.resetBot).not.toHaveBeenCalled()+ expect(mocks.resetMachine).not.toHaveBeenCalled()+ expect(mocks.toastSuccess).not.toHaveBeenCalled()+ expect(mocks.toastError).not.toHaveBeenCalled()+ expect(mocks.toastApiError).not.toHaveBeenCalled()+ expect(latest.confirmDelete).toBeNull()+ expect(latest.confirmReset).toBeNull()+ expect(latest.confirmResetMachine).toBeNull()+ })++ it("preserves delete success, generic rejection, and finally clearing", async () => {+ mocks.target = null+ render()+ act(() => latest.setConfirmDelete(bot("delete-me", "mac1")))+ await act(async () => { await latest.deleteConfirmedBot() })+ expect(mocks.del).toHaveBeenCalledWith("delete-me")+ expect(mocks.toastSuccess).toHaveBeenCalledWith("Deleted delete-me")+ expect(latest.confirmDelete).toBeNull()++ vi.clearAllMocks()+ const error = new Error("delete failed")+ mocks.del.mockRejectedValueOnce(error)+ act(() => latest.setConfirmDelete(bot("reject-me", "mac1")))+ await act(async () => { await latest.deleteConfirmedBot() })+ expect(mocks.toastApiError).toHaveBeenCalledWith(error, "Couldn't delete the bot")+ expect(mocks.toastSuccess).not.toHaveBeenCalled()+ expect(latest.confirmDelete).toBeNull()+ })++ it("covers reset-bot success, generic errors, the offline conjunction, and finally", async () => {+ mocks.target = null+ render()+ const select = () => act(() => latest.setConfirmReset(bot("reset-me", "mac1")))++ select()+ await act(async () => { await latest.resetConfirmedBot() })+ expect(mocks.resetBot).toHaveBeenCalledWith("reset-me")+ expect(mocks.toastSuccess).toHaveBeenCalledWith("Session reset.")+ expect(latest.confirmReset).toBeNull()++ for (const error of [+ new Error("generic"),+ { status: 409, message: "runner unavailable" },+ { status: 500, message: "runner offline" },+ ]) {+ vi.clearAllMocks()+ mocks.resetBot.mockRejectedValueOnce(error)+ select()+ await act(async () => { await latest.resetConfirmedBot() })+ expect(mocks.toastApiError).toHaveBeenCalledWith(error, "Couldn't reset the bot's session")+ expect(mocks.toastError).not.toHaveBeenCalled()+ expect(latest.confirmReset).toBeNull()+ }++ vi.clearAllMocks()+ mocks.resetBot.mockRejectedValueOnce({ status: 409, message: "runner OFFLINE" })+ select()+ await act(async () => { await latest.resetConfirmedBot() })+ expect(mocks.toastError).toHaveBeenCalledWith(+ "Bot is offline — bring it online before resetting.",+ )+ expect(mocks.toastApiError).not.toHaveBeenCalled()+ expect(latest.confirmReset).toBeNull()+ })++ it("covers reset-machine payload/name, grammar, errors, offline, and finally", async () => {+ mocks.target = null+ render()+ const select = () => act(() => latest.setConfirmResetMachine("mac1"))++ mocks.resetMachine.mockResolvedValueOnce({ dispatched: 1 })+ select()+ await act(async () => { await latest.resetConfirmedMachine() })+ expect(mocks.resetMachine).toHaveBeenCalledWith("mac1")+ expect(mocks.toastSuccess).toHaveBeenCalledWith("Dispatched reset to 1 agent on One.")+ expect(latest.confirmResetMachine).toBeNull()++ vi.clearAllMocks()+ mocks.resetMachine.mockResolvedValueOnce({ dispatched: 3 })+ select()+ await act(async () => { await latest.resetConfirmedMachine() })+ expect(mocks.toastSuccess).toHaveBeenCalledWith("Dispatched reset to 3 agents on One.")+ expect(latest.confirmResetMachine).toBeNull()++ for (const generic of [+ { status: 409, message: "runner unavailable" },+ { status: 500, message: "machine offline" },+ ]) {+ vi.clearAllMocks()+ mocks.resetMachine.mockRejectedValueOnce(generic)+ select()+ await act(async () => { await latest.resetConfirmedMachine() })+ expect(mocks.toastApiError).toHaveBeenCalledWith(+ generic,+ "Couldn't reset the machine's agents",+ )+ expect(mocks.toastError).not.toHaveBeenCalled()+ expect(latest.confirmResetMachine).toBeNull()+ }++ vi.clearAllMocks()+ mocks.resetMachine.mockRejectedValueOnce({ status: 409, message: "machine OFFLINE" })+ select()+ await act(async () => { await latest.resetConfirmedMachine() })+ expect(mocks.toastError).toHaveBeenCalledWith(+ "One is offline — bring it online before resetting.",+ )+ expect(mocks.toastApiError).not.toHaveBeenCalled()+ expect(latest.confirmResetMachine).toBeNull()+ })+})diff --git a/src/web/src/components/community/bots/bot-list-controller.ts b/src/web/src/components/community/bots/bot-list-controller.tsnew file mode 100644index 000000000..9dda835a7--- /dev/null+++ b/src/web/src/components/community/bots/bot-list-controller.ts@@ -0,0 +1,256 @@+"use client"++import { useEffect, useMemo, useRef, useState } from "react"+import { useRouter, useSearchParams } from "next/navigation"+import { isPresenceOnline } from "@alook/shared"+import { toast } from "sonner"+import { toastApiError } from "@/lib/api/client"+import { machineName as resolveMachineName } from "@/lib/community/machine-name"+import { useMachines } from "@/hooks/community/use-machines"+import {+ useBots,+ useDeleteBot,+ useResetBotSession,+ useResetMachineAgents,+ type BotSummary,+} from "@/hooks/community/use-bots"+import { useCreateOrGetDm } from "@/hooks/community/mutations"+import { useOnlineUserIds } from "@/stores/community/ws"+import {+ advanceCommunityOnboarding,+ readCommunityOnboardingState,+ recoverCommunityOnboardingMachine,+ updateCommunityOnboardingResources,+ useCommunityOnboarding,+} from "@/lib/community-onboarding"+import type { BotListController } from "./bot-list-types"++export function useBotListController(): BotListController {+ const router = useRouter()+ const searchParams = useSearchParams()+ const botsQuery = useBots()+ const { bots, isLoading } = botsQuery+ const { machines, isLoading: machinesLoading } = useMachines()+ const onlineUserIds = useOnlineUserIds()+ const [createOpen, setCreateOpen] = useState(false)+ const [editingBot, setEditingBot] = useState<BotSummary | null>(null)+ const [editOpen, setEditOpen] = useState(false)+ const [activityBot, setActivityBot] = useState<BotSummary | null>(null)+ const [activityOpen, setActivityOpen] = useState(false)+ const [bugReportBot, setBugReportBot] = useState<Pick<BotSummary, "id" | "name"> | null>(null)+ const [bugReportOpen, setBugReportOpen] = useState(false)+ const [confirmDelete, setConfirmDelete] = useState<BotSummary | null>(null)+ const [confirmReset, setConfirmReset] = useState<BotSummary | null>(null)+ const [confirmResetMachine, setConfirmResetMachine] = useState<string | null>(null)+ const [collapsedMachines, setCollapsedMachines] = useState<Set<string>>(+ () => new Set(),+ )+ const [helpOpen, setHelpOpen] = useState(false)+ const del = useDeleteBot()+ const resetSession = useResetBotSession()+ const resetMachineAgents = useResetMachineAgents()+ const createOrGetDm = useCreateOrGetDm()+ const onboardingState = useCommunityOnboarding()+ const guidedActive = onboardingState?.status === "active" && onboardingState.stage === "bot"+ const guidedPendingBotId = guidedActive ? onboardingState.botId : undefined+ const guidedNeedsMachine =+ guidedActive && !machines.some((machine) => isPresenceOnline(machine.status))++ const chatWithBot = async (bot: BotSummary) => {+ try {+ const data = await createOrGetDm.mutateAsync({ userId: bot.id })+ router.push(`/c/me/${data.conversation.id}`)+ } catch (e) {+ toastApiError(e, "Failed to open chat")+ }+ }++ const openGuidedBotDm = async (botId: string) => {+ try {+ const data = await createOrGetDm.mutateAsync({ userId: botId })+ advanceCommunityOnboarding("bot", "dm", {+ botId,+ dmId: data.conversation.id,+ })+ router.push(`/c/me/${data.conversation.id}`)+ } catch (e) {+ toastApiError(e, "Bot created, but the chat couldn't open")+ }+ }++ const onBotCreated = async (bot: BotSummary) => {+ const state = readCommunityOnboardingState()+ if (state?.status !== "active" || state.stage !== "bot") return+ updateCommunityOnboardingResources({ botId: bot.id })+ await openGuidedBotDm(bot.id)+ }++ const openGuidedCreate = () => {+ const state = readCommunityOnboardingState()+ const hasUsableMachine = machines.some((machine) => isPresenceOnline(machine.status))+ if (state?.status === "active" && state.stage === "bot" && !hasUsableMachine) {+ recoverCommunityOnboardingMachine()+ router.push("/c/me/machines")+ return+ }+ if (state?.status === "active" && state.stage === "bot" && state.botId) {+ void openGuidedBotDm(state.botId)+ return+ }+ setCreateOpen(true)+ }++ const guidedCreateLabel = guidedNeedsMachine+ ? "Connect a machine"+ : guidedPendingBotId+ ? "Open bot chat"+ : "Create a bot"++ const machineName = (id: string): string => {+ const machine = machines.find((item) => item.id === id)+ if (!machine) return "Unknown machine"+ return resolveMachineName(machine)+ }++ const groups = useMemo(() => {+ const byMachine = new Map<string, BotSummary[]>()+ for (const bot of bots) {+ const list = byMachine.get(bot.machineId)+ if (list) list.push(bot)+ else byMachine.set(bot.machineId, [bot])+ }+ const orderedIds = [+ ...machines.map((machine) => machine.id).filter((id) => byMachine.has(id)),+ ...[...byMachine.keys()].filter((id) => !machines.some((machine) => machine.id === id)),+ ]+ return orderedIds.map((machineId) => ({+ machineId,+ machine: machines.find((machine) => machine.id === machineId) ?? null,+ bots: byMachine.get(machineId)!,+ }))+ }, [bots, machines])++ const targetMachineId = searchParams.get("machineId")+ const [highlightId, setHighlightId] = useState<string | null>(null)+ const groupRefs = useRef<Record<string, HTMLDivElement | null>>({})+ const scrolledForRef = useRef<string | null>(null)+ useEffect(() => {+ if (!targetMachineId || bots.length === 0) return+ setCollapsedMachines((current) => {+ if (!current.has(targetMachineId)) return current+ const next = new Set(current)+ next.delete(targetMachineId)+ return next+ })+ if (scrolledForRef.current === targetMachineId) return+ scrolledForRef.current = targetMachineId+ groupRefs.current[targetMachineId]?.scrollIntoView({ behavior: "smooth", block: "start" })+ setHighlightId(targetMachineId)+ const timer = setTimeout(() => setHighlightId(null), 2000)+ return () => clearTimeout(timer)+ }, [targetMachineId, bots.length])++ const openMachines = () => router.push("/c/me/machines")+ const bringMachineOnline = (machineId: string) => {+ router.push(`/c/me/machines?reconnect=${machineId}`)+ }++ const deleteConfirmedBot = async () => {+ if (!confirmDelete) return+ const name = confirmDelete.name+ try {+ await del.mutateAsync(confirmDelete.id)+ toast.success(`Deleted ${name}`)+ } catch (e) {+ toastApiError(e, "Couldn't delete the bot")+ } finally {+ setConfirmDelete(null)+ }+ }++ const resetConfirmedBot = async () => {+ if (!confirmReset) return+ try {+ await resetSession.mutateAsync(confirmReset.id)+ toast.success("Session reset.")+ } catch (e) {+ const status = (e as { status?: number } | undefined)?.status+ const message = (e as { message?: string } | undefined)?.message ?? ""+ if (status === 409 && message.toLowerCase().includes("offline")) {+ toast.error("Bot is offline — bring it online before resetting.")+ } else {+ toastApiError(e, "Couldn't reset the bot's session")+ }+ } finally {+ setConfirmReset(null)+ }+ }++ const resetConfirmedMachine = async () => {+ if (!confirmResetMachine) return+ const name = machineName(confirmResetMachine)+ try {+ const { dispatched } = await resetMachineAgents.mutateAsync(confirmResetMachine)+ toast.success(+ `Dispatched reset to ${dispatched} agent${dispatched === 1 ? "" : "s"} on ${name}.`,+ )+ } catch (e) {+ const status = (e as { status?: number } | undefined)?.status+ const message = (e as { message?: string } | undefined)?.message ?? ""+ if (status === 409 && message.toLowerCase().includes("offline")) {+ toast.error(`${name} is offline — bring it online before resetting.`)+ } else {+ toastApiError(e, "Couldn't reset the machine's agents")+ }+ } finally {+ setConfirmResetMachine(null)+ }+ }++ return {+ bots,+ isLoading,+ machines,+ machinesLoading,+ onlineUserIds,+ createOpen,+ setCreateOpen,+ editingBot,+ setEditingBot,+ editOpen,+ setEditOpen,+ activityBot,+ setActivityBot,+ activityOpen,+ setActivityOpen,+ bugReportBot,+ setBugReportBot,+ bugReportOpen,+ setBugReportOpen,+ confirmDelete,+ setConfirmDelete,+ confirmReset,+ setConfirmReset,+ confirmResetMachine,+ setConfirmResetMachine,+ collapsedMachines,+ setCollapsedMachines,+ helpOpen,+ setHelpOpen,+ guidedActive,+ guidedCreateLabel,+ guidedAvatarSeed: guidedActive ? onboardingState.guideAvatarSeed : undefined,+ groups,+ highlightId,+ groupRefs,+ chatWithBot,+ onBotCreated,+ openGuidedCreate,+ openMachines,+ bringMachineOnline,+ machineName,+ deleteConfirmedBot,+ resetConfirmedBot,+ resetConfirmedMachine,+ }+}diff --git a/src/web/src/components/community/bots/bot-list-facade.contract.test.ts b/src/web/src/components/community/bots/bot-list-facade.contract.test.tsnew file mode 100644index 000000000..f125889b0--- /dev/null+++ b/src/web/src/components/community/bots/bot-list-facade.contract.test.ts@@ -0,0 +1,85 @@+import { readFileSync } from "node:fs"+import { dirname, resolve } from "node:path"+import { fileURLToPath } from "node:url"+import React, { type ComponentProps, type ComponentRef } from "react"+import TestRenderer, { act } from "react-test-renderer"+import { beforeEach, describe, expect, expectTypeOf, it, vi } from "vitest"++const mocks = vi.hoisted(() => ({+ controllerValue: { marker: "controller" },+ controller: vi.fn(),+ view: vi.fn(),+}))++vi.mock("./bot-list-controller", () => ({+ useBotListController: () => {+ mocks.controller()+ return mocks.controllerValue+ },+}))+vi.mock("./bot-list-view", () => ({+ renderBotListView: (props: unknown, controller: unknown) => {+ mocks.view(props, controller)+ return React.createElement("bot-list-view")+ },+}))++import * as facade from "./bot-list"++type ExpectedBotListProps = {+ onBack?: () => void+}++const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..")+const source = (path: string) => readFileSync(resolve(webRoot, path), "utf8")++describe("BotList facade contract", () => {+ beforeEach(() => vi.clearAllMocks())++ it("keeps the exact public surface and omitted-props default", () => {+ expect(Object.keys(facade)).toEqual(["BotList"])+ expectTypeOf<ComponentProps<typeof facade.BotList>>().toEqualTypeOf<ExpectedBotListProps>()+ expectTypeOf<ExpectedBotListProps>().toEqualTypeOf<ComponentProps<typeof facade.BotList>>()+ expectTypeOf<ComponentRef<typeof facade.BotList>>().toEqualTypeOf<never>()++ const text = source("src/components/community/bots/bot-list.tsx")+ expect(text).toContain("export function BotList({ onBack }: BotListProps = {})")+ expect(text).toContain("const controller = useBotListController()")+ expect(text).toContain("return renderBotListView({ onBack }, controller)")+ expect(text).not.toMatch(/<BotListView\b|createElement\(BotListView/)+ expect(text).not.toMatch(/forwardRef|useImperativeHandle/)+ })++ it("invokes the controller and plain view exactly once with omitted props resolved", () => {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(facade.BotList))+ })+ expect(renderer.root.findAllByType("bot-list-view")).toHaveLength(1)+ expect(mocks.controller).toHaveBeenCalledOnce()+ expect(mocks.view).toHaveBeenCalledOnce()+ expect(mocks.view).toHaveBeenCalledWith({ onBack: undefined }, mocks.controllerValue)++ const onBack = vi.fn()+ act(() => renderer.update(React.createElement(facade.BotList, { onBack })))+ expect(mocks.controller).toHaveBeenCalledTimes(2)+ expect(mocks.view).toHaveBeenLastCalledWith({ onBack }, mocks.controllerValue)+ })++ it("keeps the production page and existing regression on the original path", () => {+ const page = source("src/app/c/me/bots/page.tsx")+ const existingTest = source("src/components/community/bots/bot-list-card.test.ts")+ expect(page).toContain('from "@/components/community/bots/bot-list"')+ expect(existingTest).toContain('from "./bot-list"')+ expect(`${page}\n${existingTest}`).not.toMatch(+ /bot-list-(types|controller|view|machine-group|overlays)/,+ )+ })++ it("keeps all internals private to the bot-list implementation", () => {+ const types = source("src/components/community/bots/bot-list-types.ts")+ expect(types).not.toMatch(/^export (?:const|function|class|let|var) /m)+ expect(source("src/components/community/bots/bot-list-controller.ts"))+ .not.toMatch(/from ["']@\/components\/community\//)+ })+})diff --git a/src/web/src/components/community/bots/bot-list-machine-group.test.ts b/src/web/src/components/community/bots/bot-list-machine-group.test.tsnew file mode 100644index 000000000..6252a356d--- /dev/null+++ b/src/web/src/components/community/bots/bot-list-machine-group.test.ts@@ -0,0 +1,316 @@+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { beforeEach, describe, expect, it, vi } from "vitest"+import type { BotSummary } from "@/hooks/community/use-bots"+import type { BotListController, BotMachineGroup } from "./bot-list-types"++const mocks = vi.hoisted(() => ({ heatmap: vi.fn() }))++vi.mock("lucide-react", () => ({+ Activity: "activity-icon",+ ChevronDown: "chevron-icon",+ Monitor: "monitor-icon",+ MoreVertical: "more-icon",+ RotateCcw: "reset-icon",+}))+vi.mock("@/components/avatar", () => ({+ AgentAvatar: (props: unknown) => React.createElement("avatar", props as Record<string, unknown>),+}))+vi.mock("@/components/provider-logo", () => ({+ ProviderLogo: (props: unknown) => React.createElement("provider", props as Record<string, unknown>),+}))+vi.mock("./bot-activity-heatmap", () => ({+ BotActivityHeatmap: (props: unknown) => {+ mocks.heatmap(props)+ return React.createElement("heatmap", props as Record<string, unknown>)+ },+}))+vi.mock("@/components/ui/card", () => ({+ Card: ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) =>+ React.createElement("card", props, children),+}))+vi.mock("@/components/ui/button", () => ({+ Button: ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) =>+ React.createElement("button", props, children),+}))+vi.mock("@/components/ui/dropdown-menu", () => ({+ DropdownMenu: ({ children }: React.PropsWithChildren) => React.createElement("menu", null, children),+ DropdownMenuContent: ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) =>+ React.createElement("menu-content", props, children),+ DropdownMenuItem: ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) =>+ React.createElement("menu-item", props, children),+ DropdownMenuTrigger: ({ render }: { render: React.ReactElement }) => render,+}))++import { renderBotMachineGroup } from "./bot-list-machine-group"++const bot = (overrides: Partial<BotSummary> = {}): BotSummary => ({+ id: "b1",+ name: "Blake",+ description: "",+ image: null,+ machineId: "mac1",+ runtime: "claude",+ modelName: "claude-opus-4-6",+ lastRefreshContextAt: null,+ dailyActivity: [],+ ...overrides,+})++function controller(overrides: Partial<BotListController> = {}): BotListController {+ const noop = vi.fn()+ return {+ onlineUserIds: new Set(),+ collapsedMachines: new Set(),+ setCollapsedMachines: noop,+ setConfirmResetMachine: noop,+ setActivityBot: noop,+ setActivityOpen: noop,+ setEditingBot: noop,+ setEditOpen: noop,+ setConfirmReset: noop,+ setBugReportBot: noop,+ setBugReportOpen: noop,+ setConfirmDelete: noop,+ groupRefs: { current: {} },+ highlightId: null,+ machineName: () => "My Mac",+ bringMachineOnline: noop,+ chatWithBot: noop,+ ...overrides,+ } as BotListController+}++const group = (overrides: Partial<BotMachineGroup> = {}): BotMachineGroup => ({+ machineId: "mac1",+ machine: { id: "mac1", displayName: "My Mac", hostname: "mac", status: "online" } as BotMachineGroup["machine"],+ bots: [bot()],+ ...overrides,+})++const text = (node: TestRenderer.ReactTestInstance): string =>+ node.children.map((child) => typeof child === "string" ? child : text(child)).join("")++describe("renderBotMachineGroup", () => {+ beforeEach(() => vi.clearAllMocks())++ it("keeps the keyed/ref-owned group, card projection, status, and reconnect action", () => {+ const bringMachineOnline = vi.fn()+ const state = controller({ bringMachineOnline })+ const element = renderBotMachineGroup(group(), state)+ expect(element.key).toBe("mac1")+ const groupNode = { marker: "group" }+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(element, { createNodeMock: () => groupNode })+ })+ expect(state.groupRefs.current.mac1).toBe(groupNode)+ expect(element.props.className).toBe(+ "flex flex-col gap-3 rounded-lg p-1 transition-colors duration-500 ",+ )+ expect(renderer.root.findAllByProps({ className: "flex items-center gap-2 px-1" }))+ .toHaveLength(1)+ expect(renderer.root.findAllByProps({ className: "flex flex-col gap-3" }))+ .toHaveLength(1)+ expect(renderer.root.findByType("card").props.className).toBe("flex flex-col gap-3 p-4")+ expect(renderer.root.findAllByProps({ className: "flex items-start justify-between gap-3" }))+ .toHaveLength(1)+ expect(renderer.root.findByProps({ "aria-label": "Collapse My Mac" }).props["aria-expanded"])+ .toBe(true)+ expect(renderer.root.findByType("avatar").props).toEqual(expect.objectContaining({+ name: "Blake",+ avatarUrl: null,+ seed: "b1",+ size: 40,+ }))+ expect(renderer.root.findByType("provider").props.provider).toBe("claude")+ expect(renderer.root.findByProps({ "data-testid": "bot-card-model" }).children).toEqual(["opus-4-6"])+ expect(mocks.heatmap).toHaveBeenCalledWith({ days: [], className: "self-center" })++ const reconnect = renderer.root.findAllByType("button").find((node) =>+ node.children.includes("Bring online"))!+ const stopPropagation = vi.fn()+ act(() => reconnect.props.onClick({ stopPropagation }))+ expect(stopPropagation).toHaveBeenCalledOnce()+ expect(bringMachineOnline).toHaveBeenCalledWith("mac1")+ })++ it("keeps machine presence independent from bot presence and projects Reset all", () => {+ const setConfirmResetMachine = vi.fn()+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(renderBotMachineGroup(+ group({ machine: { id: "mac1", displayName: "My Mac", status: "online" } as BotMachineGroup["machine"] }),+ controller({ onlineUserIds: new Set(), setConfirmResetMachine }),+ ))+ })+ expect(renderer.root.findAll((node) =>+ node.props.className === "inline-block size-1.5 shrink-0 rounded-full bg-status-online"))+ .toHaveLength(1)+ expect(renderer.root.findAll((node) => node.children.includes("Offline"))).not.toHaveLength(0)+ const resetAll = renderer.root.findAllByType("button").find((node) =>+ node.children.includes("Reset all"))!+ act(() => resetAll.props.onClick())+ expect(setConfirmResetMachine).toHaveBeenCalledWith("mac1")++ act(() => {+ renderer.update(renderBotMachineGroup(+ group({ machine: { id: "mac1", displayName: "My Mac", status: "offline" } as BotMachineGroup["machine"] }),+ controller({ onlineUserIds: new Set(), setConfirmResetMachine }),+ ))+ })+ expect(renderer.root.findAll((node) =>+ node.props.className === "inline-block size-1.5 shrink-0 rounded-full bg-muted-foreground"))+ .toHaveLength(1)+ })++ it("omits reconnect for an online bot even when its machine resolves", () => {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(renderBotMachineGroup(+ group(),+ controller({ onlineUserIds: new Set(["b1"]) }),+ ))+ })+ expect(renderer.root.findAll((node) => node.children.includes("Online"))).not.toHaveLength(0)+ expect(renderer.root.findAll((node) => node.children.includes("Bring online"))).toHaveLength(0)+ })++ it("keeps target-only highlight, card keys, and awake formatting", () => {+ const item = bot({+ id: "awake",+ lastRefreshContextAt: new Date(Date.now() - 3_600_000).toISOString(),+ })+ const highlighted = renderBotMachineGroup(+ group({ bots: [item] }),+ controller({ highlightId: "mac1" }),+ )+ const plain = renderBotMachineGroup(+ group({ bots: [item] }),+ controller({ highlightId: "other" }),+ )+ expect(highlighted.props.className).toBe(+ "flex flex-col gap-3 rounded-lg p-1 transition-colors duration-500 bg-primary/5 ring-2 ring-primary/40",+ )+ expect(plain.props.className).toBe(+ "flex flex-col gap-3 rounded-lg p-1 transition-colors duration-500 ",+ )+ const body = React.Children.toArray(highlighted.props.children)[1] as React.ReactElement<{+ children: React.ReactElement[]+ }>+ expect(body.props.children[0]!.key).toBe("awake")++ let renderer!: TestRenderer.ReactTestRenderer+ act(() => { renderer = TestRenderer.create(highlighted) })+ expect(renderer.root.findAll((node) => node.children.includes("Awake 1h"))).not.toHaveLength(0)+ })++ it("keeps hidden collapse semantics and exact copied-Set toggling", () => {+ let nextSet: Set<string> | undefined+ const initial = new Set<string>()+ const setCollapsedMachines = vi.fn((updater: (value: Set<string>) => Set<string>) => {+ nextSet = updater(initial)+ })+ const state = controller({ collapsedMachines: initial, setCollapsedMachines })+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => { renderer = TestRenderer.create(renderBotMachineGroup(group(), state)) })+ act(() => renderer.root.findByProps({ "aria-label": "Collapse My Mac" }).props.onClick())+ expect(nextSet).toEqual(new Set(["mac1"]))+ expect(nextSet).not.toBe(initial)+ expect(initial).toEqual(new Set())++ let expandedSet: Set<string> | undefined+ const collapsed = new Set(["mac1"])+ const expandMachines = vi.fn((updater: (value: Set<string>) => Set<string>) => {+ expandedSet = updater(collapsed)+ })+ act(() => {+ renderer.update(renderBotMachineGroup(group(), controller({+ collapsedMachines: collapsed,+ setCollapsedMachines: expandMachines,+ })))+ })+ const expand = renderer.root.findByProps({ "aria-label": "Expand My Mac" })+ expect(expand.props["aria-expanded"]).toBe(false)+ expect(renderer.root.findAll((node) => node.props.hidden === true)).toHaveLength(1)+ expect(renderer.root.findAllByType("card")).toHaveLength(1)+ act(() => expand.props.onClick())+ expect(expandedSet).toEqual(new Set())+ expect(expandedSet).not.toBe(collapsed)+ expect(collapsed).toEqual(new Set(["mac1"]))+ })++ it("keeps menu order, testids, and selected-bot action projections", () => {+ const setActivityBot = vi.fn()+ const setActivityOpen = vi.fn()+ const setEditingBot = vi.fn()+ const setEditOpen = vi.fn()+ const setConfirmReset = vi.fn()+ const setBugReportBot = vi.fn()+ const setBugReportOpen = vi.fn()+ const setConfirmDelete = vi.fn()+ const chatWithBot = vi.fn()+ const item = bot()+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(renderBotMachineGroup(group({ bots: [item] }), controller({+ setActivityBot,+ setActivityOpen,+ setEditingBot,+ setEditOpen,+ setConfirmReset,+ setBugReportBot,+ setBugReportOpen,+ setConfirmDelete,+ chatWithBot,+ })))+ })+ const items = renderer.root.findAllByType("menu-item")+ expect(items.map(text)).toEqual([+ " Chat",+ " View activity",+ " Edit",+ " Reset",+ " Report a problem",+ " Delete",+ ])+ expect(items[3]!.props["data-testid"]).toBe("bot-reset-session-item")+ expect(items[4]!.props["data-testid"]).toBe("bot-report-problem-item")+ expect(items[0]!.children[0]).toMatchObject({ props: { className: "size-4" } })+ expect(items[2]!.children[0]).toMatchObject({ props: { className: "size-4" } })+ expect(items[4]!.children[0]).toMatchObject({ props: { className: "size-4" } })+ expect([0, 2, 4, 5].map((index) =>+ (items[index]!.children[0] as TestRenderer.ReactTestInstance).type))+ .toEqual(["span", "span", "span", "span"])+ expect(items[1]!.findAllByType("activity-icon")).toHaveLength(1)+ expect(items[3]!.findAllByType("reset-icon")).toHaveLength(1)+ expect(items[5]!.props.variant).toBe("destructive")+ act(() => items[0]!.props.onClick())+ act(() => items[1]!.props.onClick())+ act(() => items[2]!.props.onClick())+ act(() => items[3]!.props.onClick())+ act(() => items[4]!.props.onClick())+ act(() => items[5]!.props.onClick())+ expect(chatWithBot).toHaveBeenCalledWith(item)+ expect(setActivityBot).toHaveBeenCalledWith(item)+ expect(setActivityOpen).toHaveBeenCalledWith(true)+ expect(setEditingBot).toHaveBeenCalledWith(item)+ expect(setEditOpen).toHaveBeenCalledWith(true)+ expect(setConfirmReset).toHaveBeenCalledWith(item)+ expect(setBugReportBot).toHaveBeenCalledWith({ id: "b1", name: "Blake" })+ expect(setBugReportOpen).toHaveBeenCalledWith(true)+ expect(setConfirmDelete).toHaveBeenCalledWith(item)+ })++ it("uses onlineUserIds for bot status and omits reconnect for unknown machines", () => {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(renderBotMachineGroup(+ group({ machine: null }),+ controller({ onlineUserIds: new Set(["b1"]), machineName: () => "Unknown machine" }),+ ))+ })+ expect(renderer.root.findAll((node) => node.children.includes("Online"))).not.toHaveLength(0)+ expect(renderer.root.findAll((node) => node.children.includes("Bring online"))).toHaveLength(0)+ })+})diff --git a/src/web/src/components/community/bots/bot-list-machine-group.tsx b/src/web/src/components/community/bots/bot-list-machine-group.tsxnew file mode 100644index 000000000..8fd236649--- /dev/null+++ b/src/web/src/components/community/bots/bot-list-machine-group.tsx@@ -0,0 +1,210 @@+import { Activity, ChevronDown, Monitor, MoreVertical, RotateCcw } from "lucide-react"+import { formatModelLabel, isPresenceOnline } from "@alook/shared"+import { AgentAvatar } from "@/components/avatar"+import { ProviderLogo } from "@/components/provider-logo"+import { Button } from "@/components/ui/button"+import { Card } from "@/components/ui/card"+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu"+import { formatAwakeDuration } from "@/lib/community/format-time"+import { tid } from "@/lib/community/testids"+import { BotActivityHeatmap } from "./bot-activity-heatmap"+import type { BotListController, BotMachineGroup } from "./bot-list-types"++export function renderBotMachineGroup(+ { machineId, machine, bots }: BotMachineGroup,+ controller: BotListController,+) {+ const machineOnline = isPresenceOnline(machine?.status)+ const collapsed = controller.collapsedMachines.has(machineId)+ const label = controller.machineName(machineId)+ return (+ <div+ key={machineId}+ ref={(element) => {+ controller.groupRefs.current[machineId] = element+ }}+ className={[+ "flex flex-col gap-3 rounded-lg p-1 transition-colors duration-500",+ controller.highlightId === machineId ? "bg-primary/5 ring-2 ring-primary/40" : "",+ ].join(" ")}+ >+ <div className="flex items-center gap-2 px-1">+ <button+ type="button"+ className="flex min-w-0 items-center gap-2 rounded-md text-left focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"+ aria-expanded={!collapsed}+ aria-label={`${collapsed ? "Expand" : "Collapse"} ${label}`}+ onClick={() => {+ controller.setCollapsedMachines((current) => {+ const next = new Set(current)+ if (next.has(machineId)) next.delete(machineId)+ else next.add(machineId)+ return next+ })+ }}+ >+ <ChevronDown+ className={`size-3 shrink-0 text-muted-foreground transition-transform ${collapsed ? "-rotate-90" : ""}`}+ />+ <Monitor className="size-3.5 shrink-0 text-muted-foreground" />+ <span className="truncate font-mono text-xs font-medium text-muted-foreground">+ {label}+ </span>+ <span+ className={[+ "inline-block size-1.5 shrink-0 rounded-full",+ machineOnline ? "bg-status-online" : "bg-muted-foreground",+ ].join(" ")}+ />+ </button>+ <Button+ variant="ghost"+ size="sm"+ className="ml-auto h-7 gap-1.5 px-2 text-xs text-muted-foreground hover:text-foreground"+ onClick={() => controller.setConfirmResetMachine(machineId)}+ >+ <RotateCcw className="size-3.5" />+ Reset all+ </Button>+ </div>+ <div className="flex flex-col gap-3" hidden={collapsed}>+ {bots.map((bot) => {+ const online = controller.onlineUserIds.has(bot.id)+ return (+ <Card key={bot.id} className="flex flex-col gap-3 p-4">+ <div className="flex items-start justify-between gap-3">+ <AgentAvatar name={bot.name} avatarUrl={bot.image} seed={bot.id} size={40} />+ <div className="flex min-w-0 flex-1 flex-wrap items-start gap-x-3 gap-y-2.5">+ <div className="flex min-w-55 flex-1 flex-col gap-1">+ <div className="flex items-center gap-2">+ <span className="truncate text-[15px] font-medium text-foreground">+ {bot.name}+ </span>+ <span+ className={[+ "inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-1 text-[11px] font-medium",+ online+ ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"+ : "bg-muted text-muted-foreground",+ ].join(" ")}+ >+ <span+ className={[+ "inline-block size-1.5 rounded-full",+ online ? "bg-status-online" : "bg-muted-foreground",+ ].join(" ")}+ />+ {online ? "Online" : "Offline"}+ </span>+ {!online && machine && (+ <Button+ size="sm"+ variant="outline"+ className="h-6 shrink-0 px-2 text-xs"+ onClick={(event) => {+ event.stopPropagation()+ controller.bringMachineOnline(machine.id)+ }}+ >+ Bring online+ </Button>+ )}+ </div>+ <span className="flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-xs text-muted-foreground">+ <span className="flex items-center gap-1.5">+ <ProviderLogo provider={bot.runtime} className="size-3.5 shrink-0" />+ <span>{bot.runtime}</span>+ </span>+ <span aria-hidden className="shrink-0">·</span>+ {formatModelLabel(bot.runtime, bot.modelName) ? (+ <span data-testid="bot-card-model" className="font-mono">+ {formatModelLabel(bot.runtime, bot.modelName)}+ </span>+ ) : (+ <span+ data-testid="bot-card-model"+ className="font-mono text-muted-foreground/70"+ title="No model set — uses the machine's local default"+ >+ local default+ </span>+ )}+ {bot.lastRefreshContextAt && (+ <>+ <span aria-hidden className="shrink-0">·</span>+ <span className="shrink-0">+ {formatAwakeDuration(bot.lastRefreshContextAt)}+ </span>+ </>+ )}+ </span>+ </div>+ <BotActivityHeatmap days={bot.dailyActivity} className="self-center" />+ </div>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <button+ aria-label="Bot actions"+ className="grid size-8 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"+ >+ <MoreVertical className="size-4" />+ </button>+ }+ />+ <DropdownMenuContent align="end" className="w-auto min-w-36 max-w-56">+ <DropdownMenuItem onClick={() => controller.chatWithBot(bot)}>+ <span className="size-4" aria-hidden /> Chat+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => {+ controller.setActivityBot(bot)+ controller.setActivityOpen(true)+ }}+ >+ <Activity className="size-4" /> View activity+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => {+ controller.setEditingBot(bot)+ controller.setEditOpen(true)+ }}+ >+ <span className="size-4" aria-hidden /> Edit+ </DropdownMenuItem>+ <DropdownMenuItem+ data-testid={`bot-reset-session-item`}+ onClick={() => controller.setConfirmReset(bot)}+ >+ <RotateCcw className="size-4" /> Reset+ </DropdownMenuItem>+ <DropdownMenuItem+ data-testid={tid.botReportProblemItem}+ onClick={() => {+ controller.setBugReportBot({ id: bot.id, name: bot.name })+ controller.setBugReportOpen(true)+ }}+ >+ <span className="size-4" aria-hidden /> Report a problem+ </DropdownMenuItem>+ <DropdownMenuItem+ variant="destructive"+ onClick={() => controller.setConfirmDelete(bot)}+ >+ <span className="size-4" aria-hidden /> Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </Card>+ )+ })}+ </div>+ </div>+ )+}diff --git a/src/web/src/components/community/bots/bot-list-overlays.test.ts b/src/web/src/components/community/bots/bot-list-overlays.test.tsnew file mode 100644index 000000000..a5fe95213--- /dev/null+++ b/src/web/src/components/community/bots/bot-list-overlays.test.ts@@ -0,0 +1,233 @@+import React from "react"+import { readFileSync } from "node:fs"+import { dirname, resolve } from "node:path"+import { fileURLToPath } from "node:url"+import TestRenderer, { act } from "react-test-renderer"+import { beforeEach, describe, expect, it, vi } from "vitest"+import type { BotListController } from "./bot-list-types"++const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..")+const readWebSource = (path: string) => readFileSync(resolve(webRoot, path), "utf8")++function host(name: string) {+ const Host = ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) =>+ React.createElement(name, props, children)+ Host.displayName = `Host(${name})`+ return Host+}++vi.mock("@/components/community/onboarding-tiles/agent-help-gallery", () => ({+ AgentHelpGallery: host("help"),+}))+vi.mock("./bot-activity-modal", () => ({ BotActivityModal: host("activity") }))+vi.mock("./bug-report-dialog", () => ({ BugReportDialog: host("bug") }))+vi.mock("./create-bot-sheet", () => ({ CreateBotSheet: host("create") }))+vi.mock("./edit-bot-sheet", () => ({ EditBotSheet: host("edit") }))+vi.mock("@/components/ui/alert-dialog", () => ({+ AlertDialog: host("alert"),+ AlertDialogAction: host("alert-action"),+ AlertDialogCancel: host("alert-cancel"),+ AlertDialogContent: host("alert-content"),+ AlertDialogDescription: host("alert-description"),+ AlertDialogFooter: host("alert-footer"),+ AlertDialogHeader: host("alert-header"),+ AlertDialogTitle: host("alert-title"),+}))++import { renderBotListOverlaySlots } from "./bot-list-overlays"++function controller(overrides: Partial<BotListController> = {}): BotListController {+ const noop = vi.fn()+ return {+ createOpen: false,+ setCreateOpen: noop,+ onBotCreated: noop,+ guidedActive: false,+ guidedAvatarSeed: undefined,+ helpOpen: false,+ setHelpOpen: noop,+ editingBot: null,+ editOpen: false,+ setEditOpen: noop,+ activityBot: null,+ activityOpen: false,+ setActivityOpen: noop,+ bugReportBot: null,+ bugReportOpen: false,+ setBugReportOpen: noop,+ confirmDelete: null,+ setConfirmDelete: noop,+ confirmReset: null,+ setConfirmReset: noop,+ confirmResetMachine: null,+ setConfirmResetMachine: noop,+ machineName: () => "My Mac",+ deleteConfirmedBot: noop,+ resetConfirmedBot: noop,+ resetConfirmedMachine: noop,+ ...overrides,+ } as BotListController+}++describe("renderBotListOverlaySlots", () => {+ beforeEach(() => vi.clearAllMocks())++ it("returns exactly eight named elements without an aggregate reconciliation boundary", () => {+ const emptySlots = renderBotListOverlaySlots(controller())+ expect(emptySlots.bug).toBeNull()+ const slots = renderBotListOverlaySlots(controller({+ bugReportBot: { id: "b1", name: "Blake" },+ }))+ expect(Object.keys(slots)).toEqual([+ "create",+ "help",+ "edit",+ "activity",+ "bug",+ "deleteDialog",+ "resetDialog",+ "resetMachineDialog",+ ])+ for (const slot of Object.values(slots)) {+ expect(React.isValidElement(slot)).toBe(true)+ expect(Array.isArray(slot)).toBe(false)+ if (React.isValidElement(slot)) expect(slot.type).not.toBe(React.Fragment)+ }+ expect(Object.values(slots).map((slot) =>+ (slot!.type as React.ComponentType).displayName)).toEqual([+ "Host(create)",+ "Host(help)",+ "Host(edit)",+ "Host(activity)",+ "Host(bug)",+ "Host(alert)",+ "Host(alert)",+ "Host(alert)",+ ])+ const source = readWebSource("src/components/community/bots/bot-list-overlays.tsx")+ expect(source).not.toMatch(/<>|<React\.Fragment|return\s*\[/)+ })++ it("keeps selected child props and the conditional keyed bug slot", () => {+ const bot = { id: "b1", name: "Blake" }+ const setEditOpen = vi.fn()+ const setActivityOpen = vi.fn()+ const setBugReportOpen = vi.fn()+ const state = controller({+ createOpen: true,+ guidedActive: true,+ guidedAvatarSeed: "seed",+ helpOpen: true,+ editingBot: bot as BotListController["editingBot"],+ editOpen: true,+ setEditOpen,+ activityBot: bot as BotListController["activityBot"],+ activityOpen: true,+ setActivityOpen,+ bugReportBot: bot,+ bugReportOpen: true,+ setBugReportOpen,+ })+ const slots = renderBotListOverlaySlots(state)+ expect(slots.create.props).toEqual({+ open: true,+ onOpenChange: state.setCreateOpen,+ onCreated: state.onBotCreated,+ guided: true,+ avatarSeed: "seed",+ })+ expect(slots.edit.props).toEqual({ bot, open: true, onOpenChange: setEditOpen })+ expect(slots.activity.props).toEqual({ bot, open: true, onOpenChange: setActivityOpen })+ expect(slots.help.props).toEqual({+ open: true,+ onOpenChange: state.setHelpOpen,+ })+ expect(slots.bug?.key).toBe("b1")+ expect(slots.bug?.props).toEqual({ bot, open: true, onOpenChange: setBugReportOpen })++ act(() => slots.edit.props.onOpenChange(false))+ act(() => slots.activity.props.onOpenChange(false))+ act(() => slots.bug?.props.onOpenChange(false))+ expect(setEditOpen).toHaveBeenCalledWith(false)+ expect(setActivityOpen).toHaveBeenCalledWith(false)+ expect(setBugReportOpen).toHaveBeenCalledWith(false)+ expect(state.editingBot).toBe(bot)+ expect(state.activityBot).toBe(bot)+ expect(state.bugReportBot).toBe(bot)+ })++ it("wires dialog close clearing and exact confirmed actions", () => {+ const setConfirmDelete = vi.fn()+ const setConfirmReset = vi.fn()+ const setConfirmResetMachine = vi.fn()+ const deleteConfirmedBot = vi.fn()+ const resetConfirmedBot = vi.fn()+ const resetConfirmedMachine = vi.fn()+ const state = controller({+ confirmDelete: { id: "b1", name: "Blake" } as BotListController["confirmDelete"],+ setConfirmDelete,+ confirmReset: { id: "b1", name: "Blake" } as BotListController["confirmReset"],+ setConfirmReset,+ confirmResetMachine: "mac1",+ setConfirmResetMachine,+ deleteConfirmedBot,+ resetConfirmedBot,+ resetConfirmedMachine,+ })+ const slots = renderBotListOverlaySlots(state)+ const renders = [slots.deleteDialog, slots.resetDialog, slots.resetMachineDialog].map((slot) => {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => { renderer = TestRenderer.create(slot) })+ return renderer+ })+ expect(renders.map((renderer) => renderer.root.findByType("alert").props.open))+ .toEqual([true, true, true])+ act(() => renders[0]!.root.findByType("alert").props.onOpenChange(true))+ act(() => renders[1]!.root.findByType("alert").props.onOpenChange(true))+ act(() => renders[2]!.root.findByType("alert").props.onOpenChange(true))+ expect(setConfirmDelete).not.toHaveBeenCalled()+ expect(setConfirmReset).not.toHaveBeenCalled()+ expect(setConfirmResetMachine).not.toHaveBeenCalled()+ act(() => renders[0]!.root.findByType("alert").props.onOpenChange(false))+ act(() => renders[1]!.root.findByType("alert").props.onOpenChange(false))+ act(() => renders[2]!.root.findByType("alert").props.onOpenChange(false))+ expect(setConfirmDelete).toHaveBeenCalledWith(null)+ expect(setConfirmReset).toHaveBeenCalledWith(null)+ expect(setConfirmResetMachine).toHaveBeenCalledWith(null)++ act(() => renders[0]!.root.findByType("alert-action").props.onClick())+ act(() => renders[1]!.root.findByProps({ "data-testid": "bot-reset-confirm" }).props.onClick())+ act(() => renders[2]!.root.findByProps({ "data-testid": "machine-reset-all-confirm" }).props.onClick())+ expect(deleteConfirmedBot).toHaveBeenCalledOnce()+ expect(resetConfirmedBot).toHaveBeenCalledOnce()+ expect(resetConfirmedMachine).toHaveBeenCalledOnce()++ expect(renders[0]!.root.findByType("alert-description").children.join(""))+ .toBe("The bot will leave every server it's in and its runner key will be revoked. Past messages remain in history with the bot's current name and avatar.")+ expect(renders[0]!.root.findByType("alert-title").children.join(""))+ .toBe("Delete Blake?")+ expect(renders[0]!.root.findByType("alert-action").props.className)+ .toBe("bg-destructive text-destructive-foreground hover:bg-destructive/90")+ expect(renders[1]!.root.findByType("alert-description").children.join(""))+ .toBe("Its running process will stop and it'll start a fresh session that picks up unfinished work from its notes.")+ expect(renders[1]!.root.findByType("alert-title").children.join(""))+ .toBe("Reset this bot's session?")+ expect(renders[2]!.root.findByType("alert-description").children.join(""))+ .toBe("Every agent on this machine will start a fresh session. Any that aren't currently running will be woken too.")+ })++ it("keeps reset-machine title fallback and selected machine name", () => {+ const without = renderBotListOverlaySlots(controller())+ const withMachine = renderBotListOverlaySlots(controller({ confirmResetMachine: "mac1" }))+ let first!: TestRenderer.ReactTestRenderer+ let second!: TestRenderer.ReactTestRenderer+ act(() => {+ first = TestRenderer.create(without.resetMachineDialog)+ second = TestRenderer.create(withMachine.resetMachineDialog)+ })+ const title = (renderer: TestRenderer.ReactTestRenderer) =>+ renderer.root.findByType("alert-title").children.join("")+ expect(title(first)).toBe("Reset all agents on this machine?")+ expect(title(second)).toBe("Reset all agents on My Mac?")+ })+})diff --git a/src/web/src/components/community/bots/bot-list-overlays.tsx b/src/web/src/components/community/bots/bot-list-overlays.tsxnew file mode 100644index 000000000..12cc3e898--- /dev/null+++ b/src/web/src/components/community/bots/bot-list-overlays.tsx@@ -0,0 +1,137 @@+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog"+import { AgentHelpGallery } from "@/components/community/onboarding-tiles/agent-help-gallery"+import { BotActivityModal } from "./bot-activity-modal"+import { BugReportDialog } from "./bug-report-dialog"+import { CreateBotSheet } from "./create-bot-sheet"+import { EditBotSheet } from "./edit-bot-sheet"+import type { BotListController, BotListOverlaySlots } from "./bot-list-types"++export function renderBotListOverlaySlots(+ controller: BotListController,+): BotListOverlaySlots {+ return {+ create: (+ <CreateBotSheet+ open={controller.createOpen}+ onOpenChange={controller.setCreateOpen}+ onCreated={controller.onBotCreated}+ guided={controller.guidedActive}+ avatarSeed={controller.guidedAvatarSeed}+ />+ ),+ help: (+ <AgentHelpGallery open={controller.helpOpen} onOpenChange={controller.setHelpOpen} />+ ),+ edit: (+ <EditBotSheet+ bot={controller.editingBot}+ open={controller.editOpen}+ onOpenChange={controller.setEditOpen}+ />+ ),+ activity: (+ <BotActivityModal+ bot={controller.activityBot}+ open={controller.activityOpen}+ onOpenChange={controller.setActivityOpen}+ />+ ),+ bug: controller.bugReportBot ? (+ <BugReportDialog+ key={controller.bugReportBot.id}+ bot={controller.bugReportBot}+ open={controller.bugReportOpen}+ onOpenChange={controller.setBugReportOpen}+ />+ ) : null,+ deleteDialog: (+ <AlertDialog+ open={!!controller.confirmDelete}+ onOpenChange={(open) => !open && controller.setConfirmDelete(null)}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Delete {controller.confirmDelete?.name}?</AlertDialogTitle>+ <AlertDialogDescription>+ The bot will leave every server it's in and its runner key will be+ revoked. Past messages remain in history with the bot's current name+ and avatar.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ onClick={controller.deleteConfirmedBot}+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"+ >+ Delete+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ ),+ resetDialog: (+ <AlertDialog+ open={!!controller.confirmReset}+ onOpenChange={(open) => !open && controller.setConfirmReset(null)}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Reset this bot's session?</AlertDialogTitle>+ <AlertDialogDescription>+ Its running process will stop and it'll start a fresh session+ that picks up unfinished work from its notes.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ data-testid="bot-reset-confirm"+ onClick={controller.resetConfirmedBot}+ >+ Reset+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ ),+ resetMachineDialog: (+ <AlertDialog+ open={!!controller.confirmResetMachine}+ onOpenChange={(open) => !open && controller.setConfirmResetMachine(null)}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ Reset all agents on {controller.confirmResetMachine+ ? controller.machineName(controller.confirmResetMachine)+ : "this machine"}?+ </AlertDialogTitle>+ <AlertDialogDescription>+ Every agent on this machine will start a fresh session. Any that+ aren't currently running will be woken too.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ data-testid="machine-reset-all-confirm"+ onClick={controller.resetConfirmedMachine}+ >+ Reset all+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ ),+ }+}diff --git a/src/web/src/components/community/bots/bot-list-types.ts b/src/web/src/components/community/bots/bot-list-types.tsnew file mode 100644index 000000000..4dc490a83--- /dev/null+++ b/src/web/src/components/community/bots/bot-list-types.ts@@ -0,0 +1,71 @@+import type { Dispatch, SetStateAction } from "react"+import type { CommunityMachineSummary } from "@alook/shared"+import type { BotSummary } from "@/hooks/community/use-bots"++export type BotListProps = {+ onBack?: () => void+}++export type BotMachineGroup = {+ machineId: string+ machine: CommunityMachineSummary | null+ bots: BotSummary[]+}++export type BotListController = {+ bots: BotSummary[]+ isLoading: boolean+ machines: CommunityMachineSummary[]+ machinesLoading: boolean+ onlineUserIds: ReadonlySet<string>+ createOpen: boolean+ setCreateOpen: Dispatch<SetStateAction<boolean>>+ editingBot: BotSummary | null+ setEditingBot: Dispatch<SetStateAction<BotSummary | null>>+ editOpen: boolean+ setEditOpen: Dispatch<SetStateAction<boolean>>+ activityBot: BotSummary | null+ setActivityBot: Dispatch<SetStateAction<BotSummary | null>>+ activityOpen: boolean+ setActivityOpen: Dispatch<SetStateAction<boolean>>+ bugReportBot: Pick<BotSummary, "id" | "name"> | null+ setBugReportBot: Dispatch<SetStateAction<Pick<BotSummary, "id" | "name"> | null>>+ bugReportOpen: boolean+ setBugReportOpen: Dispatch<SetStateAction<boolean>>+ confirmDelete: BotSummary | null+ setConfirmDelete: Dispatch<SetStateAction<BotSummary | null>>+ confirmReset: BotSummary | null+ setConfirmReset: Dispatch<SetStateAction<BotSummary | null>>+ confirmResetMachine: string | null+ setConfirmResetMachine: Dispatch<SetStateAction<string | null>>+ collapsedMachines: Set<string>+ setCollapsedMachines: Dispatch<SetStateAction<Set<string>>>+ helpOpen: boolean+ setHelpOpen: Dispatch<SetStateAction<boolean>>+ guidedActive: boolean+ guidedCreateLabel: string+ guidedAvatarSeed: string | undefined+ groups: BotMachineGroup[]+ highlightId: string | null+ groupRefs: { current: Record<string, HTMLDivElement | null> }+ chatWithBot: (bot: BotSummary) => Promise<void>+ onBotCreated: (bot: BotSummary) => Promise<void>+ openGuidedCreate: () => void+ openMachines: () => void+ bringMachineOnline: (machineId: string) => void+ machineName: (machineId: string) => string+ deleteConfirmedBot: () => Promise<void>+ resetConfirmedBot: () => Promise<void>+ resetConfirmedMachine: () => Promise<void>+}++export type BotListOverlaySlots = {+ create: React.ReactElement+ help: React.ReactElement+ edit: React.ReactElement+ activity: React.ReactElement+ bug: React.ReactElement | null+ deleteDialog: React.ReactElement+ resetDialog: React.ReactElement+ resetMachineDialog: React.ReactElement+}diff --git a/src/web/src/components/community/bots/bot-list-view.test.ts b/src/web/src/components/community/bots/bot-list-view.test.tsnew file mode 100644index 000000000..9ee88e41d--- /dev/null+++ b/src/web/src/components/community/bots/bot-list-view.test.ts@@ -0,0 +1,284 @@+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { beforeEach, describe, expect, it, vi } from "vitest"+import type { BotListController } from "./bot-list-types"++const mocks = vi.hoisted(() => ({+ group: vi.fn(),+ overlays: vi.fn(),+ createSheet: vi.fn(),+}))++vi.mock("./bot-list-machine-group", () => ({+ renderBotMachineGroup: (group: { machineId: string }, controller: BotListController) => {+ mocks.group(group, controller)+ return React.createElement("machine-group", { key: group.machineId, machineId: group.machineId })+ },+}))+vi.mock("./bot-list-overlays", () => ({+ renderBotListOverlaySlots: (controller: BotListController) => {+ mocks.overlays(controller)+ return {+ create: React.createElement("slot", { name: "create" }),+ help: React.createElement("slot", { name: "help" }),+ edit: React.createElement("slot", { name: "edit" }),+ activity: React.createElement("slot", { name: "activity" }),+ bug: React.createElement("slot", { name: "bug" }),+ deleteDialog: React.createElement("slot", { name: "delete" }),+ resetDialog: React.createElement("slot", { name: "reset" }),+ resetMachineDialog: React.createElement("slot", { name: "resetMachine" }),+ }+ },+}))+vi.mock("./create-bot-sheet", () => ({+ CreateBotSheet: (props: unknown) => {+ mocks.createSheet(props)+ return React.createElement("create-sheet", props as Record<string, unknown>)+ },+}))+vi.mock("@/components/community/onboarding-tiles/create-tile", () => ({+ CreateTile: () => React.createElement("create-tile"),+}))++import { renderBotListView } from "./bot-list-view"++function controller(overrides: Partial<BotListController> = {}): BotListController {+ const noop = vi.fn()+ return {+ bots: [],+ isLoading: false,+ machines: [],+ machinesLoading: false,+ onlineUserIds: new Set(),+ createOpen: false,+ setCreateOpen: noop,+ editingBot: null,+ setEditingBot: noop,+ editOpen: false,+ setEditOpen: noop,+ activityBot: null,+ setActivityBot: noop,+ activityOpen: false,+ setActivityOpen: noop,+ bugReportBot: null,+ setBugReportBot: noop,+ bugReportOpen: false,+ setBugReportOpen: noop,+ confirmDelete: null,+ setConfirmDelete: noop,+ confirmReset: null,+ setConfirmReset: noop,+ confirmResetMachine: null,+ setConfirmResetMachine: noop,+ collapsedMachines: new Set(),+ setCollapsedMachines: noop,+ helpOpen: false,+ setHelpOpen: noop,+ guidedActive: false,+ guidedCreateLabel: "Create a bot",+ guidedAvatarSeed: undefined,+ groups: [],+ highlightId: null,+ groupRefs: { current: {} },+ chatWithBot: noop,+ onBotCreated: noop,+ openGuidedCreate: noop,+ openMachines: noop,+ bringMachineOnline: noop,+ machineName: () => "Machine",+ deleteConfirmedBot: noop,+ resetConfirmedBot: noop,+ resetConfirmedMachine: noop,+ ...overrides,+ } as BotListController+}++describe("renderBotListView", () => {+ beforeEach(() => vi.clearAllMocks())++ it("keeps the exact three-card skeleton branch for either loading source", () => {+ for (const loading of [{ isLoading: true }, { machinesLoading: true }]) {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(renderBotListView({}, controller(loading)))+ })+ const skeletonFibers = renderer.root.findAll((node) =>+ typeof node.type === "function" && node.type.name === "BotCardSkeleton")+ expect(skeletonFibers).toHaveLength(3)+ expect(skeletonFibers.map((node) => node.parent)).toEqual([+ skeletonFibers[0]!.parent,+ skeletonFibers[0]!.parent,+ skeletonFibers[0]!.parent,+ ])+ expect(renderer.root.findAllByProps({ className: "flex flex-col gap-3 p-6" }))+ .toHaveLength(1)+ expect(renderer.root.findAllByProps({ className: "flex flex-col gap-3 p-4" }))+ .toHaveLength(3)+ expect(renderer.root.findAllByProps({ className: "size-10 shrink-0 rounded-full" }))+ .toHaveLength(3)+ expect(renderer.root.findAllByProps({ className: "h-3.5 w-28 rounded" }))+ .toHaveLength(3)+ expect(renderer.root.findAllByProps({ className: "h-3 w-48 rounded" }))+ .toHaveLength(3)+ expect(renderer.root.findAllByProps({ className: "size-8 shrink-0 rounded-md" }))+ .toHaveLength(3)+ expect(mocks.overlays).not.toHaveBeenCalled()+ expect(mocks.createSheet).not.toHaveBeenCalled()+ act(() => renderer.unmount())+ }+ })++ it("bypasses loading for warm bots and renders the populated branch", () => {+ const state = controller({+ bots: [{ id: "b1" }] as BotListController["bots"],+ isLoading: true,+ machinesLoading: true,+ })+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => { renderer = TestRenderer.create(renderBotListView({}, state)) })+ expect(renderer.root.findAll((node) =>+ typeof node.type === "function" && node.type.name === "BotCardSkeleton"))+ .toHaveLength(0)+ expect(mocks.overlays).toHaveBeenCalledWith(state)+ })++ it("keeps empty state machine routing and constructs only its direct create sheet", () => {+ const openMachines = vi.fn()+ const setCreateOpen = vi.fn()+ const onBotCreated = vi.fn()+ const state = controller({+ openMachines,+ createOpen: true,+ setCreateOpen,+ onBotCreated,+ guidedActive: true,+ guidedAvatarSeed: "seed",+ })+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(renderBotListView({}, state))+ })+ expect(renderer.root.findAllByType("create-tile")).toHaveLength(1)+ expect(renderer.root.findAllByType("create-sheet")).toHaveLength(1)+ expect(renderer.root.findAll((node) => node.children.includes("Connect a machine first")))+ .toHaveLength(1)+ expect(renderer.root.findAll((node) => node.children.includes(+ "Bots need a connected machine to run. Connect one first, then come back to create your bot.",+ ))).toHaveLength(1)+ const connect = renderer.root.findAllByType("button").find((node) =>+ node.children.includes("Connect a machine"))!+ act(() => connect.props.onClick())+ expect(openMachines).toHaveBeenCalledOnce()+ expect(mocks.createSheet).toHaveBeenCalledWith(expect.objectContaining({+ open: true,+ onOpenChange: setCreateOpen,+ onCreated: onBotCreated,+ guided: true,+ avatarSeed: "seed",+ }))+ expect(mocks.overlays).not.toHaveBeenCalled()+ })++ it("uses guided create for empty bots on a machine and preserves back wiring", () => {+ const onBack = vi.fn()+ const openGuidedCreate = vi.fn()+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(renderBotListView(+ { onBack },+ controller({+ machines: [{ id: "mac1" }] as BotListController["machines"],+ guidedCreateLabel: "Open bot chat",+ openGuidedCreate,+ }),+ ))+ })+ act(() => renderer.root.findByProps({ "aria-label": "Back" }).props.onClick())+ expect(onBack).toHaveBeenCalledOnce()+ expect(renderer.root.findAll((node) => node.children.includes("No bots yet"))).toHaveLength(1)+ expect(renderer.root.findAll((node) => node.children.includes(+ "Create a bot and chat with it from anywhere — spin up servers and share it with family and friends.",+ ))).toHaveLength(1)+ const open = renderer.root.findAllByType("button").find((node) =>+ node.children.includes("Open bot chat"))!+ act(() => open.props.onClick())+ expect(openGuidedCreate).toHaveBeenCalledOnce()+ })++ it("inserts group results and all eight named overlay slots in exact sibling order", () => {+ const setHelpOpen = vi.fn()+ const openGuidedCreate = vi.fn()+ const state = controller({+ bots: [{ id: "b1" }] as BotListController["bots"],+ setHelpOpen,+ openGuidedCreate,+ groups: [+ { machineId: "mac1", machine: null, bots: [] },+ { machineId: "mac2", machine: null, bots: [] },+ ],+ })+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(renderBotListView({}, state))+ })+ expect(mocks.group.mock.calls.map(([group]) => group.machineId)).toEqual(["mac1", "mac2"])+ expect(mocks.group.mock.calls.every(([, passed]) => passed === state)).toBe(true)+ expect(mocks.overlays).toHaveBeenCalledWith(state)+ expect(renderer.root.findByProps({+ className: "flex flex-1 flex-col gap-6 overflow-y-auto thin-scrollbar p-6",+ })).toBeTruthy()+ expect(renderer.root.findAllByProps({+ className: "flex items-center justify-between gap-4",+ })).toHaveLength(1)+ expect(renderer.root.findByProps({+ className: "text-xl font-medium text-foreground",+ }).children).toEqual(["My Bots"])+ expect(renderer.root.findByProps({+ className: "text-sm text-muted-foreground",+ }).children).toEqual([+ "Bots you own — they show up as friends and can be added to any server.",+ ])+ expect(renderer.root.findAllByProps({ className: "flex items-center gap-1" }))+ .toHaveLength(1)+ expect(renderer.root.findAllByProps({ className: "flex flex-col gap-6" }))+ .toHaveLength(1)+ act(() => renderer.root.findByProps({ "aria-label": "How your agent works" }).props.onClick())+ expect(setHelpOpen).toHaveBeenCalledWith(true)+ const create = renderer.root.findAllByType("button").find((node) =>+ node.children.includes("Create a bot"))!+ act(() => create.props.onClick())+ expect(openGuidedCreate).toHaveBeenCalledOnce()+ expect(renderer.root.findAllByType("slot").map((node) => node.props.name)).toEqual([+ "create",+ "help",+ "edit",+ "activity",+ "bug",+ "delete",+ "reset",+ "resetMachine",+ ])+ })++ it("keeps the same outer/back-bar contract in loading, empty, and populated branches", () => {+ const onBack = vi.fn()+ const states = [+ controller({ isLoading: true }),+ controller(),+ controller({ bots: [{ id: "b1" }] as BotListController["bots"] }),+ ]+ for (const state of states) {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => { renderer = TestRenderer.create(renderBotListView({ onBack }, state)) })+ expect(renderer.root.findAllByProps({ className: "flex min-h-0 flex-1 flex-col" }))+ .not.toHaveLength(0)+ const back = renderer.root.findByProps({ "aria-label": "Back" })+ expect(back.parent?.props.className).toBe(+ "flex h-12 shrink-0 items-center gap-2 border-b border-border/40 px-6",+ )+ act(() => back.props.onClick())+ act(() => renderer.unmount())+ }+ expect(onBack).toHaveBeenCalledTimes(3)+ })+})diff --git a/src/web/src/components/community/bots/bot-list-view.tsx b/src/web/src/components/community/bots/bot-list-view.tsxnew file mode 100644index 000000000..28fff9afb--- /dev/null+++ b/src/web/src/components/community/bots/bot-list-view.tsx@@ -0,0 +1,141 @@+import { ChevronLeft, HelpCircle } from "lucide-react"+import { Button } from "@/components/ui/button"+import { Card } from "@/components/ui/card"+import { Skeleton } from "@/components/ui/skeleton"+import { CreateTile } from "@/components/community/onboarding-tiles/create-tile"+import { CreateBotSheet } from "./create-bot-sheet"+import { renderBotMachineGroup } from "./bot-list-machine-group"+import { renderBotListOverlaySlots } from "./bot-list-overlays"+import type { BotListController, BotListProps } from "./bot-list-types"++function BotCardSkeleton() {+ return (+ <Card className="flex flex-col gap-3 p-4">+ <div className="flex items-start justify-between gap-3">+ <Skeleton className="size-10 shrink-0 rounded-full" />+ <div className="flex min-w-0 flex-1 flex-col gap-2 py-0.5">+ <Skeleton className="h-3.5 w-28 rounded" />+ <Skeleton className="h-3 w-48 rounded" />+ </div>+ <Skeleton className="size-8 shrink-0 rounded-md" />+ </div>+ </Card>+ )+}++export function renderBotListView(+ { onBack }: BotListProps,+ controller: BotListController,+) {+ const backBar = onBack ? (+ <header className="flex h-12 shrink-0 items-center gap-2 border-b border-border/40 px-6">+ <Button+ variant="ghost"+ size="icon-sm"+ onClick={onBack}+ className="text-muted-foreground hover:text-foreground"+ aria-label="Back"+ >+ <ChevronLeft className="size-5" />+ </Button>+ <span className="ml-1 truncate text-base font-semibold">My Bots</span>+ </header>+ ) : null++ if ((controller.isLoading || controller.machinesLoading) && controller.bots.length === 0) {+ return (+ <div className="flex min-h-0 flex-1 flex-col">+ {backBar}+ <div className="flex flex-col gap-3 p-6">+ <BotCardSkeleton />+ <BotCardSkeleton />+ <BotCardSkeleton />+ </div>+ </div>+ )+ }++ if (controller.bots.length === 0) {+ const needsMachine = controller.machines.length === 0+ return (+ <div className="flex min-h-0 flex-1 flex-col">+ {backBar}+ <div className="flex flex-1 flex-col items-center justify-center gap-4 p-12 text-center">+ <div className="w-full max-w-70 overflow-hidden rounded-xl">+ <div className="aspect-200/130 w-full">+ <CreateTile />+ </div>+ </div>+ <div className="flex flex-col gap-1">+ <h2 className="text-lg font-medium text-foreground">+ {needsMachine ? "Connect a machine first" : "No bots yet"}+ </h2>+ <p className="max-w-md text-sm text-muted-foreground">+ {needsMachine+ ? "Bots need a connected machine to run. Connect one first, then come back to create your bot."+ : "Create a bot and chat with it from anywhere — spin up servers and share it with family and friends."}+ </p>+ </div>+ <div data-onboarding-target="create-bot" className="w-fit">+ <Button+ onClick={needsMachine ? controller.openMachines : controller.openGuidedCreate}+ >+ {needsMachine ? "Connect a machine" : controller.guidedCreateLabel}+ </Button>+ </div>+ </div>+ <CreateBotSheet+ open={controller.createOpen}+ onOpenChange={controller.setCreateOpen}+ onCreated={controller.onBotCreated}+ guided={controller.guidedActive}+ avatarSeed={controller.guidedAvatarSeed}+ />+ </div>+ )+ }++ const overlays = renderBotListOverlaySlots(controller)+ return (+ <div className="flex min-h-0 flex-1 flex-col">+ {backBar}+ <div className="flex flex-1 flex-col gap-6 overflow-y-auto thin-scrollbar p-6">+ <header className="flex items-center justify-between gap-4">+ <div className="flex flex-col gap-1">+ <h1 className="text-xl font-medium text-foreground">My Bots</h1>+ <p className="text-sm text-muted-foreground">+ Bots you own — they show up as friends and can be added to any server.+ </p>+ </div>+ <div className="flex items-center gap-1">+ <Button+ variant="ghost"+ size="icon"+ aria-label="How your agent works"+ onClick={() => controller.setHelpOpen(true)}+ className="text-muted-foreground hover:text-foreground"+ >+ <HelpCircle className="size-5" />+ </Button>+ <div data-onboarding-target="create-bot" className="w-fit">+ <Button onClick={controller.openGuidedCreate}>{controller.guidedCreateLabel}</Button>+ </div>+ </div>+ </header>++ <div className="flex flex-col gap-6">+ {controller.groups.map((group) => renderBotMachineGroup(group, controller))}+ </div>+ </div>++ {overlays.create}+ {overlays.help}+ {overlays.edit}+ {overlays.activity}+ {overlays.bug}+ {overlays.deleteDialog}+ {overlays.resetDialog}+ {overlays.resetMachineDialog}+ </div>+ )+}diff --git a/src/web/src/components/community/bots/bot-list.tsx b/src/web/src/components/community/bots/bot-list.tsxindex 89d14a174..4d742b0bf 100644--- a/src/web/src/components/community/bots/bot-list.tsx+++ b/src/web/src/components/community/bots/bot-list.tsx@@ -1,700 +1,10 @@"use client"-import { useEffect, useMemo, useRef, useState } from "react"-import { useRouter, useSearchParams } from "next/navigation"-import { ChevronDown, ChevronLeft, Monitor, MoreVertical, HelpCircle, RotateCcw, Activity } from "lucide-react"-import { toast } from "sonner"-import { toastApiError } from "@/lib/api/client"-import { isPresenceOnline, formatModelLabel } from "@alook/shared"-import { machineName as resolveMachineName } from "@/lib/community/machine-name"-import { Button } from "@/components/ui/button"-import { Card } from "@/components/ui/card"-import { Skeleton } from "@/components/ui/skeleton"-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu"-import {- AlertDialog,- AlertDialogAction,- AlertDialogCancel,- AlertDialogContent,- AlertDialogDescription,- AlertDialogFooter,- AlertDialogHeader,- AlertDialogTitle,-} from "@/components/ui/alert-dialog"-import { AgentAvatar } from "@/components/avatar"-import { ProviderLogo } from "@/components/provider-logo"-import { formatAwakeDuration } from "@/components/community/format-time"-import { BotActivityHeatmap } from "./bot-activity-heatmap"-import { useMachines } from "@/hooks/community/use-machines"-import { useBots, useDeleteBot, useResetBotSession, useResetMachineAgents, type BotSummary } from "@/hooks/community/use-bots"-import { useCreateOrGetDm } from "@/hooks/community/mutations"-import { useOnlineUserIds } from "@/stores/community/ws"-import { CreateBotSheet } from "./create-bot-sheet"-import { EditBotSheet } from "./edit-bot-sheet"-import { BotActivityModal } from "./bot-activity-modal"-import { BugReportDialog } from "./bug-report-dialog"-import { CreateTile } from "@/components/community/onboarding-tiles/create-tile"-import { AgentHelpGallery } from "@/components/community/onboarding-tiles/agent-help-gallery"-import {- advanceCommunityOnboarding,- readCommunityOnboardingState,- recoverCommunityOnboardingMachine,- updateCommunityOnboardingResources,- useCommunityOnboarding,-} from "@/lib/community-onboarding"-import { tid } from "@/lib/community/testids"+import { useBotListController } from "./bot-list-controller"+import { renderBotListView } from "./bot-list-view"+import type { BotListProps } from "./bot-list-types"-/**- * BotList — the /c/me/bots surface.- *- * Visual language matches the sibling MachineList: a back-bar header, a- * 6-unit-padded scroll region, header/CTA row, Card rows with a 40px avatar,- * status pill, meta line, and a kebab menu. Empty state matches the machine- * empty state so users don't learn two idioms.- */-// Loading placeholder shaped like a real bot Card (40px avatar + name row +-// meta line + trailing kebab slot) so the list doesn't reflow when data lands-// — replaces the old structureless muted box.-function BotCardSkeleton() {- return (- <Card className="flex flex-col gap-3 p-4">- <div className="flex items-start justify-between gap-3">- <Skeleton className="size-10 shrink-0 rounded-full" />- <div className="flex min-w-0 flex-1 flex-col gap-2 py-0.5">- <Skeleton className="h-3.5 w-28 rounded" />- <Skeleton className="h-3 w-48 rounded" />- </div>- <Skeleton className="size-8 shrink-0 rounded-md" />- </div>- </Card>- )-}--export function BotList({ onBack }: { onBack?: () => void } = {}) {- const router = useRouter()- const searchParams = useSearchParams()- const botsQuery = useBots()- const { bots, isLoading } = botsQuery- const { machines, isLoading: machinesLoading } = useMachines()- // Presence read: single API for humans + bots, server-pushed identically- // (see plans/community-account-debt-fixes.md Fix 3 — the owner is always- // part of its own bots' presence audience, even for a bot not yet in any- // shared server, so this pill uses the same signal every other surface- // (DM sidebar, friend list, mention popover) reads from — no divergence).- const onlineUserIds = useOnlineUserIds()- const [createOpen, setCreateOpen] = useState(false)- // `editingBot` deliberately never resets to null on close — EditBotSheet- // stays mounted at all times (see its render below) so its open/close- // transition always has a "closed" state to animate from, matching- // CreateBotSheet. Only `editOpen` toggles; the last-edited bot lingers- // harmlessly while the sheet is hidden.- const [editingBot, setEditingBot] = useState<BotSummary | null>(null)- const [editOpen, setEditOpen] = useState(false)- const [activityBot, setActivityBot] = useState<BotSummary | null>(null)- const [activityOpen, setActivityOpen] = useState(false)- const [bugReportBot, setBugReportBot] = useState<Pick<BotSummary, "id" | "name"> | null>(null)- const [bugReportOpen, setBugReportOpen] = useState(false)- const [confirmDelete, setConfirmDelete] = useState<BotSummary | null>(null)- const [confirmReset, setConfirmReset] = useState<BotSummary | null>(null)- // Batch "reset all agents on this machine" confirm — keyed by machineId so the- // dialog knows which group it's acting on (and can name it).- const [confirmResetMachine, setConfirmResetMachine] = useState<string | null>(null)- const [collapsedMachines, setCollapsedMachines] = useState<Set<string>>(- () => new Set(),- )- const [helpOpen, setHelpOpen] = useState(false)- const del = useDeleteBot()- const resetSession = useResetBotSession()- const resetMachineAgents = useResetMachineAgents()- const createOrGetDm = useCreateOrGetDm()- const onboardingState = useCommunityOnboarding()- const guidedActive = onboardingState?.status === "active" && onboardingState.stage === "bot"- const guidedPendingBotId =- guidedActive ? onboardingState.botId : undefined- const guidedNeedsMachine =- guidedActive &&- !machines.some((machine) => isPresenceOnline(machine.status))-- const chatWithBot = async (bot: BotSummary) => {- try {- const data = await createOrGetDm.mutateAsync({ userId: bot.id })- router.push(`/c/me/${data.conversation.id}`)- } catch (e) {- toastApiError(e, "Failed to open chat")- }- }-- const openGuidedBotDm = async (botId: string) => {- try {- const data = await createOrGetDm.mutateAsync({ userId: botId })- advanceCommunityOnboarding("bot", "dm", {- botId,- dmId: data.conversation.id,- })- router.push(`/c/me/${data.conversation.id}`)- } catch (e) {- toastApiError(e, "Bot created, but the chat couldn't open")- }- }-- const onBotCreated = async (bot: BotSummary) => {- const state = readCommunityOnboardingState()- if (state?.status !== "active" || state.stage !== "bot") return- updateCommunityOnboardingResources({ botId: bot.id })- await openGuidedBotDm(bot.id)- }-- const openGuidedCreate = () => {- const state = readCommunityOnboardingState()- const hasUsableMachine = machines.some((machine) => isPresenceOnline(machine.status))- if (state?.status === "active" && state.stage === "bot" && !hasUsableMachine) {- recoverCommunityOnboardingMachine()- router.push("/c/me/machines")- return- }- if (state?.status === "active" && state.stage === "bot" && state.botId) {- void openGuidedBotDm(state.botId)- return- }- setCreateOpen(true)- }-- const guidedCreateLabel = guidedNeedsMachine- ? "Connect a machine"- : guidedPendingBotId- ? "Open bot chat"- : "Create a bot"-- const machineName = (id: string): string => {- const m = machines.find((x) => x.id === id)- if (!m) return "Unknown machine"- return resolveMachineName(m)- }-- // Group bots by their bound machine, ordered to match the Machines page- // (any bot whose machine no longer resolves — deleted/unbound — sorts- // into a trailing "Unknown machine" group instead of disappearing).- const groups = useMemo(() => {- const byMachine = new Map<string, BotSummary[]>()- for (const bot of bots) {- const list = byMachine.get(bot.machineId)- if (list) list.push(bot)- else byMachine.set(bot.machineId, [bot])- }- const orderedIds = [- ...machines.map((m) => m.id).filter((id) => byMachine.has(id)),- ...[...byMachine.keys()].filter((id) => !machines.some((m) => m.id === id)),- ]- return orderedIds.map((machineId) => ({- machineId,- machine: machines.find((m) => m.id === machineId) ?? null,- bots: byMachine.get(machineId)!,- }))- }, [bots, machines])-- // Deep-link from the machine-delete dialog's "Manage bots" action- // (`?machineId=`) — scroll to that group and flash a highlight so the- // user immediately sees which bots block the delete.- const targetMachineId = searchParams.get("machineId")- const [highlightId, setHighlightId] = useState<string | null>(null)- const groupRefs = useRef<Record<string, HTMLDivElement | null>>({})- const scrolledForRef = useRef<string | null>(null)- useEffect(() => {- if (!targetMachineId || bots.length === 0) return- setCollapsedMachines((current) => {- if (!current.has(targetMachineId)) return current- const next = new Set(current)- next.delete(targetMachineId)- return next- })- if (scrolledForRef.current === targetMachineId) return- scrolledForRef.current = targetMachineId- groupRefs.current[targetMachineId]?.scrollIntoView({ behavior: "smooth", block: "start" })- setHighlightId(targetMachineId)- const t = setTimeout(() => setHighlightId(null), 2000)- return () => clearTimeout(t)- }, [targetMachineId, bots.length])-- const backBar = onBack ? (- <header className="flex h-12 shrink-0 items-center gap-2 border-b border-border/40 px-6">- <Button- variant="ghost"- size="icon-sm"- onClick={onBack}- className="text-muted-foreground hover:text-foreground"- aria-label="Back"- >- <ChevronLeft className="size-5" />- </Button>- <span className="ml-1 truncate text-base font-semibold">My Bots</span>- </header>- ) : null-- if ((isLoading || machinesLoading) && bots.length === 0) {- return (- <div className="flex min-h-0 flex-1 flex-col">- {backBar}- <div className="flex flex-col gap-3 p-6">- <BotCardSkeleton />- <BotCardSkeleton />- <BotCardSkeleton />- </div>- </div>- )- }-- if (bots.length === 0) {- const needsMachine = machines.length === 0- return (- <div className="flex min-h-0 flex-1 flex-col">- {backBar}- <div className="flex flex-1 flex-col items-center justify-center gap-4 p-12 text-center">- <div className="w-full max-w-70 overflow-hidden rounded-xl">- <div className="aspect-200/130 w-full">- <CreateTile />- </div>- </div>- <div className="flex flex-col gap-1">- <h2 className="text-lg font-medium text-foreground">- {needsMachine ? "Connect a machine first" : "No bots yet"}- </h2>- <p className="max-w-md text-sm text-muted-foreground">- {needsMachine- ? "Bots need a connected machine to run. Connect one first, then come back to create your bot."- : "Create a bot and chat with it from anywhere — spin up servers and share it with family and friends."}- </p>- </div>- {/* No help ? in the empty state (Gus): the gallery is about mechanics- a user only needs AFTER they own a bot — it lives in the populated- header instead. */}- <div data-onboarding-target="create-bot" className="w-fit">- <Button- onClick={needsMachine ? () => router.push("/c/me/machines") : openGuidedCreate}- >- {needsMachine ? "Connect a machine" : guidedCreateLabel}- </Button>- </div>- </div>- <CreateBotSheet- open={createOpen}- onOpenChange={setCreateOpen}- onCreated={onBotCreated}- guided={guidedActive}- avatarSeed={guidedActive ? onboardingState.guideAvatarSeed : undefined}- />- </div>- )- }-- return (- <div className="flex min-h-0 flex-1 flex-col">- {backBar}- <div className="flex flex-1 flex-col gap-6 overflow-y-auto thin-scrollbar p-6">- <header className="flex items-center justify-between gap-4">- <div className="flex flex-col gap-1">- <h1 className="text-xl font-medium text-foreground">My Bots</h1>- <p className="text-sm text-muted-foreground">- Bots you own — they show up as friends and can be added to any server.- </p>- </div>- <div className="flex items-center gap-1">- <Button- variant="ghost"- size="icon"- aria-label="How your agent works"- onClick={() => setHelpOpen(true)}- className="text-muted-foreground hover:text-foreground"- >- <HelpCircle className="size-5" />- </Button>- <div data-onboarding-target="create-bot" className="w-fit">- <Button onClick={openGuidedCreate}>{guidedCreateLabel}</Button>- </div>- </div>- </header>-- <div className="flex flex-col gap-6">- {groups.map(({ machineId, machine, bots: machineBots }) => {- const machineOnline = isPresenceOnline(machine?.status)- const collapsed = collapsedMachines.has(machineId)- const label = machineName(machineId)- return (- <div- key={machineId}- ref={(el) => {- groupRefs.current[machineId] = el- }}- className={[- "flex flex-col gap-3 rounded-lg p-1 transition-colors duration-500",- highlightId === machineId ? "bg-primary/5 ring-2 ring-primary/40" : "",- ].join(" ")}- >- <div className="flex items-center gap-2 px-1">- <button- type="button"- className="flex min-w-0 items-center gap-2 rounded-md text-left focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"- aria-expanded={!collapsed}- aria-label={`${collapsed ? "Expand" : "Collapse"} ${label}`}- onClick={() => {- setCollapsedMachines((current) => {- const next = new Set(current)- if (next.has(machineId)) next.delete(machineId)- else next.add(machineId)- return next- })- }}- >- <ChevronDown- className={`size-3 shrink-0 text-muted-foreground transition-transform ${collapsed ? "-rotate-90" : ""}`}- />- <Monitor className="size-3.5 shrink-0 text-muted-foreground" />- <span className="truncate font-mono text-xs font-medium text-muted-foreground">- {label}- </span>- <span- className={[- "inline-block size-1.5 shrink-0 rounded-full",- machineOnline ? "bg-status-online" : "bg-muted-foreground",- ].join(" ")}- />- </button>- {/* Reset every agent bound to this machine in one command- (Gus #811). Idle bots get cold-started too (② semantics). */}- <Button- variant="ghost"- size="sm"- className="ml-auto h-7 gap-1.5 px-2 text-xs text-muted-foreground hover:text-foreground"- onClick={() => setConfirmResetMachine(machineId)}- >- <RotateCcw className="size-3.5" />- Reset all- </Button>- </div>- <div className="flex flex-col gap-3" hidden={collapsed}>- {machineBots.map((bot) => {- const online = onlineUserIds.has(bot.id)- return (- <Card key={bot.id} className="flex flex-col gap-3 p-4">- <div className="flex items-start justify-between gap-3">- <AgentAvatar name={bot.name} avatarUrl={bot.image} seed={bot.id} size={40} />- {/* The name/meta column and the heatmap share a- flex-wrap row that starts AFTER the avatar — so when- the strip wraps it aligns to the name column, not the- card's left edge under the avatar (Gus #726/#730).- The strip sits right of the meta when there's room- and drops to its own line below when the card is too- narrow (Gus #720) — native, content/width-based. */}- <div className="flex min-w-0 flex-1 flex-wrap items-start gap-x-3 gap-y-2.5">- {/* min-w = the meta line's natural width, so the strip- is forced to WRAP below before the runtime/model/- awake text has to truncate (Gus #730 — never let- the heatmap squeeze the meta). */}- <div className="flex min-w-55 flex-1 flex-col gap-1">- <div className="flex items-center gap-2">- <span className="truncate text-[15px] font-medium text-foreground">- {bot.name}- </span>- <span- className={[- "inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-1 text-[11px] font-medium",- online- ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"- : "bg-muted text-muted-foreground",- ].join(" ")}- >- <span- className={[- "inline-block size-1.5 rounded-full",- online ? "bg-status-online" : "bg-muted-foreground",- ].join(" ")}- />- {online ? "Online" : "Offline"}- </span>- {/* A bot's presence is its bound machine's- status, so "bring online" jumps to Machines- and opens the same reconnect Sheet as- MachineCard's "Reconnect…". Omitted when the- machine can't be resolved (Unknown machine). */}- {!online && machine && (- <Button- size="sm"- variant="outline"- className="h-6 shrink-0 px-2 text-xs"- onClick={(e) => {- e.stopPropagation()- router.push(`/c/me/machines?reconnect=${machine.id}`)- }}- >- Bring online- </Button>- )}- </div>- {/* One meta line (Gus #573: no third row). Runtime ·- model · awake-duration (my-bots #516; Gus- #672/#674 relabelled "Refreshed X ago" → the- awake concept "Awake 17h"). null lastRefresh =- never awoke → the segment is omitted. The old- "Handled N msgs" counter is replaced by the- 30-day activity heatmap (Gus #608). */}- {/* Meta wraps (not truncates): when the card is too- narrow to fit runtime · model · Awake on one- line, the segments fold to a second line instead- of getting cut — provider/model are important- info and must stay fully readable (Gus #730 /- Alli #731). */}- <span className="flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-xs text-muted-foreground">- <span className="flex items-center gap-1.5">- <ProviderLogo provider={bot.runtime} className="size-3.5 shrink-0" />- <span>{bot.runtime}</span>- </span>- <span aria-hidden className="shrink-0">·</span>- {formatModelLabel(bot.runtime, bot.modelName) ? (- <span data-testid="bot-card-model" className="font-mono">- {formatModelLabel(bot.runtime, bot.modelName)}- </span>- ) : (- <span- data-testid="bot-card-model"- className="font-mono text-muted-foreground/70"- title="No model set — uses the machine's local default"- >- local default- </span>- )}- {bot.lastRefreshContextAt && (- <>- <span aria-hidden className="shrink-0">·</span>- <span className="shrink-0">{formatAwakeDuration(bot.lastRefreshContextAt)}</span>- </>- )}- </span>- </div>- {/* The strip. No ml-auto: the id-column is flex-1 so- it eats the slack and pushes the strip to the- right when they share a line; when the row wraps,- the strip is alone on its line and left-aligns to- the name column (Gus #726/#730). self-center only- affects the shared line's vertical alignment. */}- <BotActivityHeatmap- days={bot.dailyActivity}- className="self-center"- />- </div>- <DropdownMenu>- <DropdownMenuTrigger- render={- <button- aria-label="Bot actions"- className="grid size-8 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"- >- <MoreVertical className="size-4" />- </button>- }- />- {/* Nav-icon pattern from message-menu (uiux #14,- Gus "less is more"): icon ONLY on the high-freq- actions (View activity, Reset) as scan anchors;- the rest render an icon-width placeholder so- every label shares one left edge. */}- <DropdownMenuContent align="end" className="w-auto min-w-36 max-w-56">- <DropdownMenuItem onClick={() => chatWithBot(bot)}>- <span className="size-4" aria-hidden /> Chat- </DropdownMenuItem>- <DropdownMenuItem- onClick={() => {- setActivityBot(bot)- setActivityOpen(true)- }}- >- <Activity className="size-4" /> View activity- </DropdownMenuItem>- <DropdownMenuItem- onClick={() => {- setEditingBot(bot)- setEditOpen(true)- }}- >- <span className="size-4" aria-hidden /> Edit- </DropdownMenuItem>- <DropdownMenuItem- data-testid={`bot-reset-session-item`}- onClick={() => setConfirmReset(bot)}- >- <RotateCcw className="size-4" /> Reset- </DropdownMenuItem>- <DropdownMenuItem- data-testid={tid.botReportProblemItem}- onClick={() => {- setBugReportBot({ id: bot.id, name: bot.name })- setBugReportOpen(true)- }}- >- <span className="size-4" aria-hidden /> Report a problem- </DropdownMenuItem>- <DropdownMenuItem- variant="destructive"- onClick={() => setConfirmDelete(bot)}- >- <span className="size-4" aria-hidden /> Delete- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </div>- </Card>- )- })}- </div>- </div>- )- })}- </div>- </div>-- <CreateBotSheet- open={createOpen}- onOpenChange={setCreateOpen}- onCreated={onBotCreated}- guided={guidedActive}- avatarSeed={guidedActive ? onboardingState.guideAvatarSeed : undefined}- />- <AgentHelpGallery open={helpOpen} onOpenChange={setHelpOpen} />- <EditBotSheet bot={editingBot} open={editOpen} onOpenChange={setEditOpen} />- <BotActivityModal- bot={activityBot}- open={activityOpen}- onOpenChange={setActivityOpen}- />- {bugReportBot && (- <BugReportDialog- key={bugReportBot.id}- bot={bugReportBot}- open={bugReportOpen}- onOpenChange={setBugReportOpen}- />- )}- <AlertDialog- open={!!confirmDelete}- onOpenChange={(open) => !open && setConfirmDelete(null)}- >- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>Delete {confirmDelete?.name}?</AlertDialogTitle>- <AlertDialogDescription>- The bot will leave every server it's in and its runner key will be- revoked. Past messages remain in history with the bot's current name- and avatar.- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel>Cancel</AlertDialogCancel>- <AlertDialogAction- onClick={async () => {- if (!confirmDelete) return- const name = confirmDelete.name- try {- await del.mutateAsync(confirmDelete.id)- toast.success(`Deleted ${name}`)- } catch (e) {- toastApiError(e, "Couldn't delete the bot")- } finally {- setConfirmDelete(null)- }- }}- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"- >- Delete- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>- <AlertDialog- open={!!confirmReset}- onOpenChange={(open) => !open && setConfirmReset(null)}- >- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>Reset this bot's session?</AlertDialogTitle>- <AlertDialogDescription>- Its running process will stop and it'll start a fresh session- that picks up unfinished work from its notes.- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel>Cancel</AlertDialogCancel>- <AlertDialogAction- data-testid="bot-reset-confirm"- onClick={async () => {- if (!confirmReset) return- try {- await resetSession.mutateAsync(confirmReset.id)- toast.success("Session reset.")- } catch (e) {- const status = (e as { status?: number } | undefined)?.status- const message = (e as { message?: string } | undefined)?.message ?? ""- if (status === 409 && message.toLowerCase().includes("offline")) {- toast.error("Bot is offline — bring it online before resetting.")- } else {- toastApiError(e, "Couldn't reset the bot's session")- }- } finally {- setConfirmReset(null)- }- }}- >- Reset- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>- <AlertDialog- open={!!confirmResetMachine}- onOpenChange={(open) => !open && setConfirmResetMachine(null)}- >- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>- Reset all agents on {confirmResetMachine ? machineName(confirmResetMachine) : "this machine"}?- </AlertDialogTitle>- <AlertDialogDescription>- Every agent on this machine will start a fresh session. Any that- aren't currently running will be woken too.- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel>Cancel</AlertDialogCancel>- <AlertDialogAction- data-testid="machine-reset-all-confirm"- onClick={async () => {- if (!confirmResetMachine) return- const name = machineName(confirmResetMachine)- try {- const { dispatched } = await resetMachineAgents.mutateAsync(confirmResetMachine)- toast.success(- `Dispatched reset to ${dispatched} agent${dispatched === 1 ? "" : "s"} on ${name}.`,- )- } catch (e) {- const status = (e as { status?: number } | undefined)?.status- const message = (e as { message?: string } | undefined)?.message ?? ""- if (status === 409 && message.toLowerCase().includes("offline")) {- toast.error(`${name} is offline — bring it online before resetting.`)- } else {- toastApiError(e, "Couldn't reset the machine's agents")- }- } finally {- setConfirmResetMachine(null)- }- }}- >- Reset all- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>- </div>- )+export function BotList({ onBack }: BotListProps = {}) {+ const controller = useBotListController()+ return renderBotListView({ onBack }, controller)}diff --git a/src/web/src/components/community/channel-header.title-dialog.test.ts b/src/web/src/components/community/channels/channel-header.title-dialog.test.tssimilarity index 98%rename from src/web/src/components/community/channel-header.title-dialog.test.tsrename to src/web/src/components/community/channels/channel-header.title-dialog.test.tsindex bfd1fbfa5..c992c6afe 100644--- a/src/web/src/components/community/channel-header.title-dialog.test.ts+++ b/src/web/src/components/community/channels/channel-header.title-dialog.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from "vitest"import React from "react"import TestRenderer, { act } from "react-test-renderer"-vi.mock("./create-dialog-shell", async () => {+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 }) => (diff --git a/src/web/src/components/community/channel-header.tsx b/src/web/src/components/community/channels/channel-header.tsxsimilarity index 98%rename from src/web/src/components/community/channel-header.tsxrename to src/web/src/components/community/channels/channel-header.tsxindex eab1f849f..51211b077 100644--- a/src/web/src/components/community/channel-header.tsx+++ b/src/web/src/components/community/channels/channel-header.tsx@@ -12,12 +12,12 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator } from "@/components/ui/dropdown-menu"import { Skeleton } from "@/components/ui/skeleton"import { ChannelIcon } from "./channel-icon"-import { EntityIcon } from "./entity-icon"-import { SlugHint } from "./slug-hint"+import { EntityIcon } from "../entity-icon"+import { SlugHint } from "../settings/slug-hint"import { previewSlug } from "@/lib/community/slug-preview"import { SeededBackdrop } from "@/components/avatar"-import type { RightPanel } from "./_types"-import { CreateDialogShell } from "./create-dialog-shell"+import type { RightPanel } from "@/components/community/shell/panel-types"+import { CreateDialogShell } from "../settings/create-dialog-shell"// Skeleton header for the loading frame between route change and channel// metadata arriving. Same h-12 footprint as <ChannelHeader> so the body belowdiff --git a/src/web/src/components/community/channel-icon.tsx b/src/web/src/components/community/channels/channel-icon.tsxsimilarity index 100%rename from src/web/src/components/community/channel-icon.tsxrename to src/web/src/components/community/channels/channel-icon.tsxdiff --git a/src/web/src/components/community/channel-route.text-scroll-target.test.ts b/src/web/src/components/community/channels/channel-route.text-scroll-target.test.tssimilarity index 91%rename from src/web/src/components/community/channel-route.text-scroll-target.test.tsrename to src/web/src/components/community/channels/channel-route.text-scroll-target.test.tsindex e9d940b96..61065615a 100644--- a/src/web/src/components/community/channel-route.text-scroll-target.test.ts+++ b/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts@@ -3,8 +3,8 @@ import TestRenderer, { act } from "react-test-renderer"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { ChannelRoute } from "./channel-route"import { ForumChannelSurface } from "./forum-channel-surface"-import { MessageList } from "./message-list"-import { useChannelMemberViewModel } from "./channel-member-view-model"+import { MessageList } from "../messages/message-list"+import { useChannelMemberViewModel } from "../members/channel-member-view-model"import { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"const { mockRouteModel, mockMemberViewModel } = vi.hoisted(() => ({@@ -47,31 +47,31 @@ vi.mock("next/navigation", () => ({vi.mock("sonner", () => ({ toast: vi.fn() }))vi.mock("@/lib/api/client", () => ({ apiFetch: vi.fn(), toastApiError: vi.fn() }))vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))-vi.mock("@/components/community/channel-header", () => ({+vi.mock("@/components/community/channels/channel-header", () => ({ChannelHeader: () => null,ChannelHeaderSkeleton: () => null,}))-vi.mock("@/components/community/message-list", () => ({ MessageList: vi.fn(() => null) }))-vi.mock("@/components/community/composer", () => ({+vi.mock("@/components/community/messages/message-list", () => ({ MessageList: vi.fn(() => null) }))+vi.mock("@/components/community/messages/composer", () => ({Composer: () => null,ComposerSkeleton: () => null,}))-vi.mock("@/components/community/forum-view", () => ({ ForumViewSkeleton: () => null }))-vi.mock("@/components/community/forum-channel-surface", () => ({+vi.mock("@/components/community/channels/forum-view", () => ({ ForumViewSkeleton: () => null }))+vi.mock("@/components/community/channels/forum-channel-surface", () => ({ForumChannelSurface: vi.fn(() => null),}))-vi.mock("@/components/community/channel-member-view-model", () => ({+vi.mock("@/components/community/members/channel-member-view-model", () => ({useChannelMemberViewModel: vi.fn(() => mockMemberViewModel),}))-vi.mock("@/components/community/channel-shell", () => ({+vi.mock("@/components/community/channels/channel-shell", () => ({ChannelShell: ({ body }: { body: React.ReactNode }) => body,}))-vi.mock("@/components/community/community-panel-sheet", () => ({ CommunityPanelSheet: () => null }))-vi.mock("@/components/community/message-context-sheet", () => ({ MessageContextSheet: () => null }))-vi.mock("@/components/community/thread-opener", () => ({ ThreadOpener: () => null }))-vi.mock("@/components/community/add-members-dialog", () => ({ AddMembersDialog: () => null }))-vi.mock("@/components/community/_types", () => ({ canManageServer: () => false }))+vi.mock("@/components/community/shell/community-panel-sheet", () => ({ CommunityPanelSheet: () => null }))+vi.mock("@/components/community/messages/message-context-sheet", () => ({ MessageContextSheet: () => null }))+vi.mock("@/components/community/messages/thread-opener", () => ({ ThreadOpener: () => null }))+vi.mock("@/components/community/members/add-members-dialog", () => ({ AddMembersDialog: () => null }))vi.mock("@alook/shared", () => ({+ canManageServer: () => false,isForum: () => false,deriveThreadName: () => "thread",USE_SERVER_DEFAULT: "default",diff --git a/src/web/src/components/community/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsxsimilarity index 93%rename from src/web/src/components/community/channel-route.tsxrename to src/web/src/components/community/channels/channel-route.tsxindex 6cfb71fad..d8b67d502 100644--- a/src/web/src/components/community/channel-route.tsx+++ b/src/web/src/components/community/channels/channel-route.tsx@@ -4,17 +4,16 @@ import { useCallback, useEffect, useMemo, useState } from "react"import { useRouter, useSearchParams } from "next/navigation"import { toastApiError } from "@/lib/api/client"import { useBreakpoint } from "@/hooks/use-mobile"-import { ChannelHeaderSkeleton, type ChannelNotifLevel } from "@/components/community/channel-header"-import { MessageList } from "@/components/community/message-list"-import { ComposerSkeleton } from "@/components/community/composer"-import { ForumViewSkeleton } from "@/components/community/forum-view"-import { TextChannelSurface } from "@/components/community/text-channel-surface"-import { ThreadChannelSurface } from "@/components/community/thread-channel-surface"-import { ForumChannelSurface } from "@/components/community/forum-channel-surface"-import { useChannelMemberViewModel } from "@/components/community/channel-member-view-model"-import type { OpenProfile } from "@/components/community/_types"-import { canManageServer } from "@/components/community/_types"-import { USE_SERVER_DEFAULT } from "@alook/shared"+import { ChannelHeaderSkeleton, type ChannelNotifLevel } from "@/components/community/channels/channel-header"+import { MessageList } from "@/components/community/messages/message-list"+import { ComposerSkeleton } from "@/components/community/messages/composer"+import { ForumViewSkeleton } from "@/components/community/channels/forum-view"+import { TextChannelSurface } from "@/components/community/channels/text-channel-surface"+import { ThreadChannelSurface } from "@/components/community/channels/thread-channel-surface"+import { ForumChannelSurface } from "@/components/community/channels/forum-channel-surface"+import { useChannelMemberViewModel } from "@/components/community/members/channel-member-view-model"+import type { OpenProfile } from "@/components/community/social/profile-types"+import { canManageServer, USE_SERVER_DEFAULT } from "@alook/shared"import { setLastChannel } from "@/lib/community/last-channel"import { resolveChannelDisplayName } from "@/lib/community/channel-display-name"import {diff --git a/src/web/src/components/community/channel-shell.tsx b/src/web/src/components/community/channels/channel-shell.tsxsimilarity index 100%rename from src/web/src/components/community/channel-shell.tsxrename to src/web/src/components/community/channels/channel-shell.tsxdiff --git a/src/web/src/components/community/channel-sidebar.crumb.test.ts b/src/web/src/components/community/channels/channel-sidebar.crumb.test.tssimilarity index 100%rename from src/web/src/components/community/channel-sidebar.crumb.test.tsrename to src/web/src/components/community/channels/channel-sidebar.crumb.test.tsdiff --git a/src/web/src/components/community/channel-sidebar.tsx b/src/web/src/components/community/channels/channel-sidebar.tsxsimilarity index 97%rename from src/web/src/components/community/channel-sidebar.tsxrename to src/web/src/components/community/channels/channel-sidebar.tsxindex ff04f7e87..942d02cd6 100644--- a/src/web/src/components/community/channel-sidebar.tsx+++ b/src/web/src/components/community/channels/channel-sidebar.tsx@@ -11,13 +11,14 @@ import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuIteimport { Skeleton } from "@/components/ui/skeleton"import { SortableCategory } from "./sortable-category"import { SortableChannel, PendingChannelRow } from "./sortable-channel"-import { CreateChannelDialog } from "./create-channel-dialog"-import { CreateCategoryDialog } from "./create-category-dialog"-import { CategorySettingsDialog } from "./category-settings-dialog"+import { CreateChannelDialog } from "../settings/create-channel-dialog"+import { CreateCategoryDialog } from "../settings/create-category-dialog"+import { CategorySettingsDialog } from "../settings/category-settings-dialog"import { catId, catOf, isCat, reorderChannelsWithin, type ChannelTree } from "./use-channel-tree"-import { InviteDialog } from "./invite-dialog"-import { ChannelAddMembersDialog } from "./channel-add-members-dialog"-import type { Channel, SettingsSection } from "./_types"+import { InviteDialog } from "../social/invite-dialog"+import { ChannelAddMembersDialog } from "../members/channel-add-members-dialog"+import type { Channel } from "@/lib/community/models/navigation"+import type { SettingsSection } from "@/components/community/settings/settings-types"import { UNCATEGORIZED_CATEGORY_ID, type ChannelType } from "@alook/shared"import { tid } from "@/lib/community/testids"import type { ForumSidebarThread } from "@/hooks/community/use-forum-sidebar-threads"diff --git a/src/web/src/components/community/dm-header.tsx b/src/web/src/components/community/channels/dm-header.tsxsimilarity index 94%rename from src/web/src/components/community/dm-header.tsxrename to src/web/src/components/community/channels/dm-header.tsxindex fec8baef8..c33243910 100644--- a/src/web/src/components/community/dm-header.tsx+++ b/src/web/src/components/community/channels/dm-header.tsx@@ -1,8 +1,8 @@import { ChevronLeft } from "lucide-react"import { Button } from "@/components/ui/button"import { Skeleton } from "@/components/ui/skeleton"-import { Avatar } from "./avatar"-import type { DM } from "./_types"+import { Avatar } from "../avatar"+import type { DM } from "@/lib/community/models/people"export function DmHeader({ dm, onBack, titleAs: Title = "h1" }: {dm: DMdiff --git a/src/web/src/components/community/dm-sidebar.prefetch.test.ts b/src/web/src/components/community/channels/dm-sidebar.prefetch.test.tssimilarity index 100%rename from src/web/src/components/community/dm-sidebar.prefetch.test.tsrename to src/web/src/components/community/channels/dm-sidebar.prefetch.test.tsdiff --git a/src/web/src/components/community/dm-sidebar.tsx b/src/web/src/components/community/channels/dm-sidebar.tsxsimilarity index 98%rename from src/web/src/components/community/dm-sidebar.tsxrename to src/web/src/components/community/channels/dm-sidebar.tsxindex b5186c5b9..eb83ab58a 100644--- a/src/web/src/components/community/dm-sidebar.tsx+++ b/src/web/src/components/community/channels/dm-sidebar.tsx@@ -2,10 +2,10 @@import { memo } from "react"import { Users, Ban, Monitor, Bot } from "lucide-react"-import { Avatar } from "./avatar"+import { Avatar } from "../avatar"import { Skeleton } from "@/components/ui/skeleton"import { tid } from "@/lib/community/testids"-import type { DM } from "./_types"+import type { DM } from "@/lib/community/models/people"export const DmSidebar = memo(function DmSidebar({dms, activeDm, blockedUserIds, loading, onPickDm, onShowFriends, onShowMachines, onShowBots,diff --git a/src/web/src/components/community/forum-channel-surface.test.ts b/src/web/src/components/community/channels/forum-channel-surface.test.tssimilarity index 94%rename from src/web/src/components/community/forum-channel-surface.test.tsrename to src/web/src/components/community/channels/forum-channel-surface.test.tsindex c34e286f4..b954f033d 100644--- a/src/web/src/components/community/forum-channel-surface.test.ts+++ b/src/web/src/components/community/channels/forum-channel-surface.test.ts@@ -2,7 +2,7 @@ import React from "react"import TestRenderer, { act } from "react-test-renderer"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { ChannelHeader } from "./channel-header"-import { CommunityPanelSheet } from "./community-panel-sheet"+import { CommunityPanelSheet } from "../shell/community-panel-sheet"import { ForumChannelSurface } from "./forum-channel-surface"import { ForumSurface } from "./forum-surface"@@ -38,14 +38,14 @@ vi.mock("@/hooks/community/mutations", () => ({variables: { threadId: "post_deleting" },}),}))-vi.mock("@/components/community/_types", async (importOriginal) => {- const original = await importOriginal<typeof import("./_types")>()+vi.mock("@alook/shared", async (importOriginal) => {+ const original = await importOriginal<typeof import("@alook/shared")>()return { ...original, canManageServer: (role: string | undefined) => role === "owner" || role === "admin" }})-vi.mock("@/components/community/channel-header", () => ({+vi.mock("@/components/community/channels/channel-header", () => ({ChannelHeader: vi.fn(() => null),}))-vi.mock("@/components/community/channel-shell", () => ({+vi.mock("@/components/community/channels/channel-shell", () => ({ChannelShell: ({ header, body, panels, dialogs }: {header: React.ReactNodebody: React.ReactNode@@ -53,10 +53,10 @@ vi.mock("@/components/community/channel-shell", () => ({dialogs?: React.ReactNode}) => React.createElement(React.Fragment, null, header, body, panels, dialogs),}))-vi.mock("@/components/community/community-panel-sheet", () => ({+vi.mock("@/components/community/shell/community-panel-sheet", () => ({CommunityPanelSheet: vi.fn(() => null),}))-vi.mock("@/components/community/forum-surface", () => ({+vi.mock("@/components/community/channels/forum-surface", () => ({ForumSurface: vi.fn(() => null),}))diff --git a/src/web/src/components/community/forum-channel-surface.tsx b/src/web/src/components/community/channels/forum-channel-surface.tsxsimilarity index 87%rename from src/web/src/components/community/forum-channel-surface.tsxrename to src/web/src/components/community/channels/forum-channel-surface.tsxindex 765acb63b..3abf752d3 100644--- a/src/web/src/components/community/forum-channel-surface.tsx+++ b/src/web/src/components/community/channels/forum-channel-surface.tsx@@ -2,14 +2,16 @@import { useCallback, useEffect, useState, type ReactNode } from "react"import { toastApiError } from "@/lib/api/client"-import { canManageServer, type OpenProfile, type RightPanel, type Role } from "@/components/community/_types"-import { ChannelHeader, type ChannelNotifLevel } from "@/components/community/channel-header"-import { ChannelShell } from "@/components/community/channel-shell"-import type { ChannelMemberPanelProps } from "@/components/community/channel-member-view-model"-import { CommunityPanelSheet } from "@/components/community/community-panel-sheet"-import type { NewForumThread } from "@/components/community/create-forum-thread"-import { ForumSurface } from "@/components/community/forum-surface"-import type { Member } from "@/components/community/_types"+import { canManageServer, type CommunityRole as Role } from "@alook/shared"+import type { OpenProfile } from "@/components/community/social/profile-types"+import type { RightPanel } from "@/components/community/shell/panel-types"+import { ChannelHeader, type ChannelNotifLevel } from "@/components/community/channels/channel-header"+import { ChannelShell } from "@/components/community/channels/channel-shell"+import type { ChannelMemberPanelProps } from "@/components/community/members/channel-member-view-model"+import { CommunityPanelSheet } from "@/components/community/shell/community-panel-sheet"+import type { NewForumThread } from "@/components/community/messages/create-forum-thread"+import { ForumSurface } from "@/components/community/channels/forum-surface"+import type { Member } from "@/lib/community/models/people"import {useCreateForumThread,useDeleteForumThread,diff --git a/src/web/src/components/community/forum-child-header.contract.test.ts b/src/web/src/components/community/channels/forum-child-header.contract.test.tssimilarity index 100%rename from src/web/src/components/community/forum-child-header.contract.test.tsrename to src/web/src/components/community/channels/forum-child-header.contract.test.tsdiff --git a/src/web/src/components/community/forum-surface.tsx b/src/web/src/components/community/channels/forum-surface.tsxsimilarity index 86%rename from src/web/src/components/community/forum-surface.tsxrename to src/web/src/components/community/channels/forum-surface.tsxindex 76a05cc37..c09f40f24 100644--- a/src/web/src/components/community/forum-surface.tsx+++ b/src/web/src/components/community/channels/forum-surface.tsx@@ -1,7 +1,8 @@"use client"-import type { NewForumThread } from "./create-forum-thread"-import type { ForumThread, Member } from "./_types"+import type { NewForumThread } from "../messages/create-forum-thread"+import type { ForumThread } from "@/lib/community/models/message"+import type { Member } from "@/lib/community/models/people"import { ForumView } from "./forum-view"import { useForumFeed } from "@/hooks/community/use-forum-feed"diff --git a/src/web/src/components/community/forum-view.scroll.test.ts b/src/web/src/components/community/channels/forum-view.scroll.test.tssimilarity index 98%rename from src/web/src/components/community/forum-view.scroll.test.tsrename to src/web/src/components/community/channels/forum-view.scroll.test.tsindex a1e1f04b1..6b80961ac 100644--- a/src/web/src/components/community/forum-view.scroll.test.ts+++ b/src/web/src/components/community/channels/forum-view.scroll.test.ts@@ -1,7 +1,7 @@import { act, create, type ReactTestRenderer } from "react-test-renderer"import { createElement } from "react"import { beforeEach, describe, expect, it, vi } from "vitest"-import type { ForumThread } from "./_types"+import type { ForumThread } from "@/lib/community/models/message"const scrollToIndex = vi.fn()let requestOlder: (() => void) | undefineddiff --git a/src/web/src/components/community/forum-view.test.ts b/src/web/src/components/community/channels/forum-view.test.tssimilarity index 99%rename from src/web/src/components/community/forum-view.test.tsrename to src/web/src/components/community/channels/forum-view.test.tsindex ef3b3bd3e..deedc9c18 100644--- a/src/web/src/components/community/forum-view.test.ts+++ b/src/web/src/components/community/channels/forum-view.test.ts@@ -3,7 +3,7 @@ import { createElement } from "react"import { renderToStaticMarkup } from "react-dom/server"import { ForumView, shouldActivateForumRow } from "./forum-view"import { tid } from "@/lib/community/testids"-import type { ForumThread } from "./_types"+import type { ForumThread } from "@/lib/community/models/message"const LAST_AT = "2020-01-01T00:00:00.000Z"diff --git a/src/web/src/components/community/forum-view.tsx b/src/web/src/components/community/channels/forum-view.tsxsimilarity index 97%rename from src/web/src/components/community/forum-view.tsxrename to src/web/src/components/community/channels/forum-view.tsxindex d26584f74..33d791889 100644--- a/src/web/src/components/community/forum-view.tsx+++ b/src/web/src/components/community/channels/forum-view.tsx@@ -5,18 +5,19 @@ import { useVirtualizer } from "@tanstack/react-virtual"import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS } from "@/hooks/community/virtualizer-react-options"import { MessagesSquare, ListChevronsUpDown, Plus, Tag, Trash2 } from "lucide-react"import { Button } from "@/components/ui/button"-import { formatRelativeTime } from "./format-time"+import { formatRelativeTime } from "@/lib/community/format-time"import { Skeleton } from "@/components/ui/skeleton"-import { Avatar } from "./avatar"+import { Avatar } from "../avatar"import { AvatarGroup, AvatarGroupCount } from "@/components/ui/avatar"import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"-import { EmptyState } from "./empty-state"-import { CreateForumThread, type NewForumThread } from "./create-forum-thread"+import { EmptyState } from "../empty-state"+import { CreateForumThread, type NewForumThread } from "../messages/create-forum-thread"import { PostTagDialog } from "./post-tag-dialog"import { ConfirmDialog } from "@/components/ui/confirm-dialog"import { tid } from "@/lib/community/testids"-import type { ForumThread, Member } from "./_types"-import { VirtualRows } from "./virtual-cursor-list"+import type { ForumThread } from "@/lib/community/models/message"+import type { Member } from "@/lib/community/models/people"+import { VirtualRows } from "../messages/virtual-cursor-list"import { useVirtualCursorSentinel } from "@/hooks/community/use-virtual-cursor-sentinel"import { tagColorClassName, tagColorStyle } from "@/lib/community/tag-color"import { cn } from "@/lib/utils"diff --git a/src/web/src/components/community/post-tag-dialog.tsx b/src/web/src/components/community/channels/post-tag-dialog.tsxsimilarity index 100%rename from src/web/src/components/community/post-tag-dialog.tsxrename to src/web/src/components/community/channels/post-tag-dialog.tsxdiff --git a/src/web/src/components/community/sortable-category.test.ts b/src/web/src/components/community/channels/sortable-category.test.tssimilarity index 100%rename from src/web/src/components/community/sortable-category.test.tsrename to src/web/src/components/community/channels/sortable-category.test.tsdiff --git a/src/web/src/components/community/sortable-category.tsx b/src/web/src/components/community/channels/sortable-category.tsxsimilarity index 99%rename from src/web/src/components/community/sortable-category.tsxrename to src/web/src/components/community/channels/sortable-category.tsxindex db4cbbf39..cd7697fe5 100644--- a/src/web/src/components/community/sortable-category.tsx+++ b/src/web/src/components/community/channels/sortable-category.tsx@@ -8,7 +8,7 @@ import { useDroppable } from "@dnd-kit/core"import { CSS } from "@dnd-kit/utilities"import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuSeparator } from "@/components/ui/context-menu"import { ConfirmDialog } from "@/components/ui/confirm-dialog"-import { DropLine } from "./drop-line"+import { DropLine } from "../drop-line"// True when the category header has at least one right-click action. With none, we skip// the ContextMenu wrapper so a non-admin doesn't get an empty popover strip.diff --git a/src/web/src/components/community/sortable-channel.test.ts b/src/web/src/components/community/channels/sortable-channel.test.tssimilarity index 95%rename from src/web/src/components/community/sortable-channel.test.tsrename to src/web/src/components/community/channels/sortable-channel.test.tsindex 7f4453be3..7df571499 100644--- a/src/web/src/components/community/sortable-channel.test.ts+++ b/src/web/src/components/community/channels/sortable-channel.test.ts@@ -2,7 +2,7 @@ import { describe, it, expect } from "vitest"import { createElement } from "react"import { renderToStaticMarkup } from "react-dom/server"import { hasChannelMenu, PendingChannelRow } from "./sortable-channel"-import type { Channel } from "./_types"+import type { Channel } from "@/lib/community/models/navigation"const noop = () => {}diff --git a/src/web/src/components/community/sortable-channel.tsx b/src/web/src/components/community/channels/sortable-channel.tsxsimilarity index 97%rename from src/web/src/components/community/sortable-channel.tsxrename to src/web/src/components/community/channels/sortable-channel.tsxindex 148b17a14..4dfcc070a 100644--- a/src/web/src/components/community/sortable-channel.tsx+++ b/src/web/src/components/community/channels/sortable-channel.tsx@@ -2,14 +2,14 @@import { useState } from "react"import { BellOff, Loader2, Pencil, Trash2, Users } from "lucide-react"-import { EntityIcon } from "./entity-icon"+import { EntityIcon } from "../entity-icon"import { useSortable } from "@dnd-kit/sortable"import { CSS } from "@dnd-kit/utilities"import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuSeparator } from "@/components/ui/context-menu"import { ConfirmDialog } from "@/components/ui/confirm-dialog"-import { DropLine } from "./drop-line"+import { DropLine } from "../drop-line"import { tid } from "@/lib/community/testids"-import type { Channel } from "./_types"+import type { Channel } from "@/lib/community/models/navigation"// True when the row has at least one right-click action. With none, we skip the// ContextMenu wrapper entirely so a non-manager doesn't get an empty popover strip.diff --git a/src/web/src/components/community/text-channel-surface.test.ts b/src/web/src/components/community/channels/text-channel-surface.test.tssimilarity index 98%rename from src/web/src/components/community/text-channel-surface.test.tsrename to src/web/src/components/community/channels/text-channel-surface.test.tsindex b9c110555..34385ecb7 100644--- a/src/web/src/components/community/text-channel-surface.test.ts+++ b/src/web/src/components/community/channels/text-channel-surface.test.ts@@ -1,8 +1,8 @@import React from "react"import TestRenderer, { act } from "react-test-renderer"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"-import { MessageChannelController } from "./message-channel-controller"-import type { MessageChannelControllerValue } from "./message-channel-controller"+import { MessageChannelController } from "../messages/message-channel-controller"+import type { MessageChannelControllerValue } from "../messages/message-channel-controller"import type { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"import { buildAttachmentUploadFormData } from "@/hooks/community/mutations/uploads"import { useMessageStreamStore } from "@/stores/community/message-stream"diff --git a/src/web/src/components/community/text-channel-surface.tsx b/src/web/src/components/community/channels/text-channel-surface.tsxsimilarity index 90%rename from src/web/src/components/community/text-channel-surface.tsxrename to src/web/src/components/community/channels/text-channel-surface.tsxindex 4ed944d8f..4ba59ed69 100644--- a/src/web/src/components/community/text-channel-surface.tsx+++ b/src/web/src/components/community/channels/text-channel-surface.tsx@@ -3,17 +3,19 @@import { useEffect, useState, type ComponentProps, type ReactNode } from "react"import { useBreakpoint } from "@/hooks/use-mobile"import { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"-import { ChannelHeader, type ChannelNotifLevel } from "@/components/community/channel-header"-import { ChannelShell } from "@/components/community/channel-shell"-import { CommunityPanelSheet } from "@/components/community/community-panel-sheet"-import type { ChannelMemberPanelProps } from "@/components/community/channel-member-view-model"-import { Composer } from "@/components/community/composer"-import { MessageContextSheet } from "@/components/community/message-context-sheet"-import { MessageList } from "@/components/community/message-list"+import { ChannelHeader, type ChannelNotifLevel } from "@/components/community/channels/channel-header"+import { ChannelShell } from "@/components/community/channels/channel-shell"+import { CommunityPanelSheet } from "@/components/community/shell/community-panel-sheet"+import type { ChannelMemberPanelProps } from "@/components/community/members/channel-member-view-model"+import { Composer } from "@/components/community/messages/composer"+import { MessageContextSheet } from "@/components/community/messages/message-context-sheet"+import { MessageList } from "@/components/community/messages/message-list"import {MessageChannelController,-} from "@/components/community/message-channel-controller"-import type { FileAttachment, ImagePreview, OpenProfile, RightPanel } from "@/components/community/_types"+} from "@/components/community/messages/message-channel-controller"+import type { FileAttachment, ImagePreview } from "@/lib/community/models/message"+import type { OpenProfile } from "@/components/community/social/profile-types"+import type { RightPanel } from "@/components/community/shell/panel-types"export function TextChannelSurface({channelId,diff --git a/src/web/src/components/community/thread-channel-surface.test.ts b/src/web/src/components/community/channels/thread-channel-surface.test.tssimilarity index 93%rename from src/web/src/components/community/thread-channel-surface.test.tsrename to src/web/src/components/community/channels/thread-channel-surface.test.tsindex 477c97bda..2f15b0d42 100644--- a/src/web/src/components/community/thread-channel-surface.test.ts+++ b/src/web/src/components/community/channels/thread-channel-surface.test.ts@@ -3,13 +3,13 @@ import TestRenderer, { act } from "react-test-renderer"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { ThreadChannelSurface } from "./thread-channel-surface"import { ChannelHeader } from "./channel-header"-import { CommunityPanelSheet } from "./community-panel-sheet"-import { Composer } from "./composer"-import { MessageContextSheet } from "./message-context-sheet"-import { MessageList } from "./message-list"-import { ThreadOpener } from "./thread-opener"+import { CommunityPanelSheet } from "../shell/community-panel-sheet"+import { Composer } from "../messages/composer"+import { MessageContextSheet } from "../messages/message-context-sheet"+import { MessageList } from "../messages/message-list"+import { ThreadOpener } from "../messages/thread-opener"import { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"-import type { MessageChannelControllerValue } from "./message-channel-controller"+import type { MessageChannelControllerValue } from "../messages/message-channel-controller"const mocks = vi.hoisted(() => ({router: { push: vi.fn(), replace: vi.fn(), back: vi.fn() },@@ -36,11 +36,11 @@ vi.mock("@/hooks/community/use-channel-message-feed", () => ({vi.mock("@/hooks/community/mutations", () => ({useEditMessage: () => ({ mutateAsync: mocks.editMessage }),}))-vi.mock("@/components/community/channel-header", () => ({+vi.mock("@/components/community/channels/channel-header", () => ({ChannelHeader: vi.fn(() => null),ChannelHeaderSkeleton: vi.fn(() => null),}))-vi.mock("@/components/community/channel-shell", () => ({+vi.mock("@/components/community/channels/channel-shell", () => ({ChannelShell: ({header,body,@@ -53,23 +53,23 @@ vi.mock("@/components/community/channel-shell", () => ({dialogs?: React.ReactNode}) => React.createElement(React.Fragment, null, header, body, panels, dialogs),}))-vi.mock("@/components/community/community-panel-sheet", () => ({+vi.mock("@/components/community/shell/community-panel-sheet", () => ({CommunityPanelSheet: vi.fn(() => null),}))-vi.mock("@/components/community/composer", () => ({+vi.mock("@/components/community/messages/composer", () => ({Composer: vi.fn(() => null),ComposerSkeleton: vi.fn(() => null),}))-vi.mock("@/components/community/message-context-sheet", () => ({+vi.mock("@/components/community/messages/message-context-sheet", () => ({MessageContextSheet: vi.fn(() => null),}))-vi.mock("@/components/community/message-list", () => ({+vi.mock("@/components/community/messages/message-list", () => ({MessageList: vi.fn(() => null),}))-vi.mock("@/components/community/thread-opener", () => ({+vi.mock("@/components/community/messages/thread-opener", () => ({ThreadOpener: vi.fn(() => null),}))-vi.mock("@/components/community/message-channel-controller", () => ({+vi.mock("@/components/community/messages/message-channel-controller", () => ({MessageChannelController: ({feed: messageFeed,children,diff --git a/src/web/src/components/community/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsxsimilarity index 93%rename from src/web/src/components/community/thread-channel-surface.tsxrename to src/web/src/components/community/channels/thread-channel-surface.tsxindex 470a2eb6a..4fcfe19f6 100644--- a/src/web/src/components/community/thread-channel-surface.tsx+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx@@ -6,16 +6,18 @@ import { toastApiError, apiFetch } from "@/lib/api/client"import { useBreakpoint } from "@/hooks/use-mobile"import { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"import { useEditMessage } from "@/hooks/community/mutations"-import { ChannelHeader, ChannelHeaderSkeleton, type ChannelNotifLevel } from "@/components/community/channel-header"-import { ChannelShell } from "@/components/community/channel-shell"-import { CommunityPanelSheet } from "@/components/community/community-panel-sheet"-import { Composer, ComposerSkeleton } from "@/components/community/composer"-import { MessageChannelController } from "@/components/community/message-channel-controller"-import { MessageContextSheet } from "@/components/community/message-context-sheet"-import { MessageList } from "@/components/community/message-list"-import { ThreadOpener } from "@/components/community/thread-opener"-import type { FileAttachment, ImagePreview, OpenProfile, RightPanel } from "@/components/community/_types"-import type { ChannelMemberPanelProps } from "@/components/community/channel-member-view-model"+import { ChannelHeader, ChannelHeaderSkeleton, type ChannelNotifLevel } from "@/components/community/channels/channel-header"+import { ChannelShell } from "@/components/community/channels/channel-shell"+import { CommunityPanelSheet } from "@/components/community/shell/community-panel-sheet"+import { Composer, ComposerSkeleton } from "@/components/community/messages/composer"+import { MessageChannelController } from "@/components/community/messages/message-channel-controller"+import { MessageContextSheet } from "@/components/community/messages/message-context-sheet"+import { MessageList } from "@/components/community/messages/message-list"+import { ThreadOpener } from "@/components/community/messages/thread-opener"+import type { FileAttachment, ImagePreview } from "@/lib/community/models/message"+import type { OpenProfile } from "@/components/community/social/profile-types"+import type { RightPanel } from "@/components/community/shell/panel-types"+import type { ChannelMemberPanelProps } from "@/components/community/members/channel-member-view-model"const ignoreNestedThread = () => {}diff --git a/src/web/src/components/community/use-channel-tree.test.ts b/src/web/src/components/community/channels/use-channel-tree.test.tssimilarity index 98%rename from src/web/src/components/community/use-channel-tree.test.tsrename to src/web/src/components/community/channels/use-channel-tree.test.tsindex 442b1c78b..ebee10855 100644--- a/src/web/src/components/community/use-channel-tree.test.ts+++ b/src/web/src/components/community/channels/use-channel-tree.test.ts@@ -9,7 +9,7 @@ import {mergeChannelMetadata,type ChannelOrder,} from "./use-channel-tree"-import type { Channel, Category } from "./_types"+import type { Channel, Category } from "@/lib/community/models/navigation"const ch = (id: string): Channel => ({ id, name: id, active: false, unread: false })diff --git a/src/web/src/components/community/use-channel-tree.ts b/src/web/src/components/community/channels/use-channel-tree.tssimilarity index 99%rename from src/web/src/components/community/use-channel-tree.tsrename to src/web/src/components/community/channels/use-channel-tree.tsindex 91c0cdde6..458920326 100644--- a/src/web/src/components/community/use-channel-tree.ts+++ b/src/web/src/components/community/channels/use-channel-tree.ts@@ -3,7 +3,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react"import { arrayMove } from "@dnd-kit/sortable"import type { DragEndEvent } from "@dnd-kit/core"-import type { Category, Channel } from "./_types"+import type { Category, Channel } from "@/lib/community/models/navigation"// dnd ids: category ids are used directly (they already have a "cat_" prefix);// channel ids are bare. We distinguish by checking the "cat_" prefix.diff --git a/src/web/src/components/community/community-avatar-shape.contract.test.ts b/src/web/src/components/community/community-avatar-shape.contract.test.tsindex 8c75c8edb..3c269ddc8 100644--- a/src/web/src/components/community/community-avatar-shape.contract.test.ts+++ b/src/web/src/components/community/community-avatar-shape.contract.test.ts@@ -9,8 +9,8 @@ const readWeb = (path: string) => readFileSync(resolve(webRoot, path), "utf8")describe("community avatar shape contract", () => {it("keeps My Profile preview and crop circular", () => {- const profile = readWeb("src/components/community/edit-profile-dialog.tsx")- const shell = readWeb("src/components/community/shell-frame.tsx")+ const profile = readWeb("src/components/community/settings/user-settings.tsx")+ const shell = readWeb("src/components/community/shell/shell-frame-overlays.tsx")expect(profile).toContain('className="block size-24 overflow-hidden rounded-full ring-1 ring-border/50"',diff --git a/src/web/src/components/community/composer.tsx b/src/web/src/components/community/composer.tsxdeleted file mode 100644index e61571bc8..000000000--- a/src/web/src/components/community/composer.tsx+++ /dev/null@@ -1,910 +0,0 @@-"use client"--import { forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from "react"-import { createPortal } from "react-dom"-import { FileIcon, ImageIcon, PlusCircle, Smile, Upload, Users, X } from "lucide-react"-import { useEditor, EditorContent, type JSONContent } from "@tiptap/react"-import StarterKit from "@tiptap/starter-kit"-import Placeholder from "@tiptap/extension-placeholder"-import { DOMParser as PMDOMParser } from "@tiptap/pm/model"-import { buildPasteDom } from "@/lib/community/paste-plain-text"-import { nextListScrollTop } from "@/lib/community/popup-scroll"-import { readComposerDraft, writeComposerDraft, clearComposerDraft } from "@/lib/community/composer-draft"-import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"-import { Skeleton } from "@/components/ui/skeleton"-import { useFileAttachments, type PendingFile } from "@/hooks/use-file-attachments"-import { MAX_ATTACHMENT_SIZE_BYTES } from "@alook/shared"-import { tid } from "@/lib/community/testids"-import { Avatar } from "./avatar"-import { ChannelIcon } from "./channel-icon"-import { EmojiPickerPopover } from "./emoji-picker"-import type { Member } from "./_types"-import type { MentionType } from "@alook/shared"-import {- buildCommunityMentionExtension,- detectMentionType,- EMPTY_MENTION_STATE,- rankMentionItems,- type MentionContext,- type MentionItem,- type MentionPopupState,-} from "@/lib/community/mention-extension"-import {- buildCommunityChannelRefExtension,- EMPTY_CHANNEL_REF_STATE,- rankChannelRefItems,- toChannelRefCommandProps,- type ChannelRefCandidate,- type ChannelRefPopupState,-} from "@/lib/community/channel-ref-extension"--export type SendAttachment = {- file: File- thumbnailBlob?: Blob- previewObjectUrl?: string- width?: number- height?: number-}--// Pure mapping from `useFileAttachments`'s pending-file state to `onSend`'s-// attachments argument. Extracted so the width/height threading through-// `Composer.send()` is unit-testable without mounting the tiptap editor.-export function pendingFilesToSendAttachments(pendingFiles: PendingFile[]): SendAttachment[] | undefined {- if (pendingFiles.length === 0) return undefined- return pendingFiles.map((pf) => ({- file: pf.file,- thumbnailBlob: pf.thumbnailBlob ?? undefined,- previewObjectUrl: pf.thumbnailUrl ?? undefined,- width: pf.width,- height: pf.height,- }))-}--// Pure extraction of the paste → File[] collection used by `handlePaste`:-// keep only clipboard items whose `kind === "file"` (a pasted image, or any-// dragged-in-then-copied file) and unwrap each via `getAsFile()`, dropping the-// occasional null the API returns. Extracted (like `pendingFilesToSendAttachments`)-// so the filtering is unit-testable without mounting the tiptap editor.-export function clipboardFiles(items: DataTransferItemList | undefined): File[] {- if (!items) return []- const files: File[] = []- for (let i = 0; i < items.length; i++) {- if (items[i].kind === "file") {- const f = items[i].getAsFile()- if (f) files.push(f)- }- }- return files-}--type ComposerMode = "chat" | "forumThreadBody"--export type ComposerHandle = {- focusEditor: () => void- submitNow: () => void- resetAfterSubmit: () => void- isEmpty: () => boolean- // Trigger the hidden file input's picker. Used by consumers that render- // their own attach button outside the composer's absolute-positioned frame.- openFilePicker: () => void-}--type ComposerBaseProps = {- channel: string- context: MentionContext- members: Member[]- // Fire-and-forget hook the composer calls with the current @-query on every- // suggestion tick. Wired to `useServerMembers.searchMembers`, which debounces- // and hits `/servers/:id/members/search`. Undefined for surfaces that don't- // have a server roster (DM composer).- onSearchMembers?: (query: string) => void- // `/`-autocomplete candidates. Single-server list for channel/thread- // composers; cross-server flattened list (via `useChannelRefDirectory()`)- // for DM composers. Always provided by the caller — empty array is fine,- // the popup just shows nothing on `/`.- channelRefCandidates?: ChannelRefCandidate[]- onChannelRefIntent?: () => void- onTyping?: () => void- // when set, shows a "Replying to X" bar above the input- replyingTo?: string- onCancelReply?: () => void- // Auto-focus the editor on mount and on channel change. Desktop only —- // callers pass `bp !== "mobile"` to avoid unexpected soft-keyboard pop-up.- autoFocus?: boolean- // `"chat"` (default) — Enter sends, Shift+Enter newline, `send()` clears.- // `"forumThreadBody"` — inverted: Enter newline, Shift+Enter submits; `send()`- // does NOT clear so the parent can await mutation success before resetting.- mode?: ComposerMode- // Placeholder override — used by `forumThreadBody` to swap the chat-composer- // relic string. Falls back to the mode-derived default when absent.- placeholder?: string- // Hide the composer's built-in emoji-picker button (bottom-right). Used by- // the create-post composer, where emoji is dropped from the compose surface.- hideEmoji?: boolean- // Hide the composer's built-in attach button (bottom-left). Used by the- // create-post composer, which renders its own attach button in the footer- // row and drives it through `ComposerHandle.openFilePicker()`.- hideAttach?: boolean- // Fires only on emptiness-state transitions (`hasContent` flips), not every- // keystroke. Used by the create-post orchestrator to drive the footer button's- // `disabled` state without mirroring editor content in parent React state.- onDirty?: (hasContent: boolean) => void- // When set, the composer persists its unsent text under this localStorage- // scope (per channel/DM) and restores it on mount — the view remounts on- // every channel switch (keyed by id), so this is what survives navigation.- // Text only; attachments/replies are not cached. Omitted for forumThreadBody- // (the parent owns that draft lifecycle).- draftKey?: string-}--type ComposerAcceptedSend = {- sendContract: "accepted"- mode?: "chat"- onAcceptSend: (markdown: string, attachments?: SendAttachment[], mentionType?: MentionType) => boolean- onDeferredSubmit?: never-}--type ComposerDeferredSend = {- sendContract: "deferred"- mode: "forumThreadBody"- onDeferredSubmit: (markdown: string, attachments?: SendAttachment[], mentionType?: MentionType) => void | Promise<void>- onAcceptSend?: never-}--export type ComposerProps = ComposerBaseProps & (ComposerAcceptedSend | ComposerDeferredSend)--// Composer — plain-text TipTap editor with a chat-style @-mention popover.-// Users type raw markdown which MessageBody/Streamdown renders on display.-// In `mode="chat"` (default) Enter sends, Shift+Enter adds a newline. In-// `mode="forumThreadBody"` the mapping is inverted (Enter = newline,-// Shift+Enter = submit) to match /w's issue-sheet convention. While the-// mention popover is open Enter/Tab/Arrow keys drive selection instead.-// @everyone is a virtual candidate in channel + thread contexts-// (hidden in DM). (@here was removed — plans/remove-here-mention.md.)-export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Composer({- channel,- context,- members,- onSearchMembers,- channelRefCandidates = [],- onChannelRefIntent,- sendContract,- onAcceptSend,- onDeferredSubmit,- onTyping,- replyingTo,- onCancelReply,- autoFocus = false,- mode = "chat",- placeholder,- hideEmoji = false,- hideAttach = false,- onDirty,- draftKey,-}, ref) {- const isForumThreadBody = mode === "forumThreadBody"- const {- pendingFiles,- setPendingFiles,- transferPendingFiles,- awaitPendingFiles,- addPendingFiles,- fileInputRef,- handleFileSelect,- removePendingFile,- dragging,- handleDragEnter,- handleDragLeave,- handleDragOver,- handleDrop: handleDropRaw,- } = useFileAttachments({- maxFileSize: MAX_ATTACHMENT_SIZE_BYTES,- })- const typingTimer = useRef<NodeJS.Timeout | null>(null)- const sendRef = useRef<() => void>(() => {})- const sendInFlightRef = useRef<Promise<void> | null>(null)- const lifecycleVersionRef = useRef(0)-- // Draft cache key, held in a ref so the editor's `onUpdate` closure (captured- // once at build) always persists under the current scope. Restore is- // suppressed via this flag so hydrating the editor doesn't fire `onTyping`.- const draftKeyRef = useRef(draftKey)- const sendScopeRef = useRef<string | null>(null)- const sendScopeVersionRef = useRef(0)- useLayoutEffect(() => {- const nextScope = `${context}\u0000${channel}\u0000${draftKey ?? ""}`- if (sendScopeRef.current !== nextScope) {- sendScopeRef.current = nextScope- sendScopeVersionRef.current++- }- draftKeyRef.current = draftKey- }, [channel, context, draftKey])- useLayoutEffect(() => () => { lifecycleVersionRef.current++ }, [])- const restoringDraftRef = useRef(false)-- const [mentionPopup, setMentionPopup] = useState<MentionPopupState>(EMPTY_MENTION_STATE)- const mentionPopupRef = useRef(mentionPopup)- useEffect(() => { mentionPopupRef.current = mentionPopup }, [mentionPopup])-- const [channelRefPopup, setChannelRefPopup] = useState<ChannelRefPopupState>(EMPTY_CHANNEL_REF_STATE)- const channelRefPopupRef = useRef(channelRefPopup)- useEffect(() => { channelRefPopupRef.current = channelRefPopup }, [channelRefPopup])-- // The mention extension is built ONCE — its suggestion callbacks read refs- // at runtime so live `members`/`context` updates are visible without- // rebuilding the editor (which would reset its state).- const membersRef = useRef(members)- const contextRef = useRef(context)- const onSearchMembersRef = useRef(onSearchMembers)- // The most recent @-query the suggestion plugin passed us. Kept so the- // re-rank effect below (fired when `members` changes while the popup is- // open) can rank against the query the user actually sees.- const queryRef = useRef<string>("")- useEffect(() => { membersRef.current = members }, [members])- useEffect(() => { contextRef.current = context }, [context])- useEffect(() => { onSearchMembersRef.current = onSearchMembers }, [onSearchMembers])-- const fireTyping = () => {- if (!onTyping || typingTimer.current) return- onTyping()- typingTimer.current = setTimeout(() => { typingTimer.current = null }, 3_000)- }-- // eslint-disable-next-line react-hooks/refs -- refs read in runtime callbacks, not render- const [mentionExtension] = useState(() =>- buildCommunityMentionExtension({- membersRef,- contextRef,- popupRef: mentionPopupRef,- setPopup: setMentionPopup,- onSearchMembersRef,- queryRef,- }),- )-- // Same "built once, refs read at runtime" pattern as the mention extension.- const channelRefCandidatesRef = useRef(channelRefCandidates)- const onChannelRefIntentRef = useRef(onChannelRefIntent)- const channelRefQueryRef = useRef<string>("")- useEffect(() => { channelRefCandidatesRef.current = channelRefCandidates }, [channelRefCandidates])- useEffect(() => { onChannelRefIntentRef.current = onChannelRefIntent }, [onChannelRefIntent])-- // eslint-disable-next-line react-hooks/refs -- refs read in runtime callbacks, not render- const [channelRefExtension] = useState(() =>- buildCommunityChannelRefExtension({- candidatesRef: channelRefCandidatesRef,- popupRef: channelRefPopupRef,- onIntentRef: onChannelRefIntentRef,- setPopup: setChannelRefPopup,- queryRef: channelRefQueryRef,- }),- )-- // Re-rank + push a new popup state whenever `members` changes AND the popup- // is open. Without this, tiptap's `suggestion.items` only fires on- // caret/query updates — so remote-arrival changes to `members` (e.g. a- // `useServerMembers.searchMembers` response landing) wouldn't reach the- // popup until the user typed another character.- //- // Guard: bail unless the recomputed items differ from what's already- // visible. React batches state updates through `Object.is`, but the popup- // object identity always changes here (we rebuild it), so an unconditional- // `setPopup` would fire on every `members` render — an infinite loop risk- // if a downstream effect touches `members`.- useEffect(() => {- const cur = mentionPopupRef.current- // Popup closed → nothing to reconcile.- if (!cur.command) return- const next = rankMentionItems(members, context, queryRef.current)- if (itemsEqual(cur.items, next)) return- // Preserve selectedIndex if it's still valid; otherwise reset to 0.- setMentionPopup({- ...cur,- items: next,- selectedIndex: cur.selectedIndex < next.length ? cur.selectedIndex : 0,- })- }, [members, context])-- // Same re-rank-on-candidates-change effect, mirrored for the channel-ref popup.- useEffect(() => {- const cur = channelRefPopupRef.current- if (!cur.command) return- const next = rankChannelRefItems(channelRefCandidates, channelRefQueryRef.current)- if (channelRefItemsEqual(cur.items, next)) return- setChannelRefPopup({- ...cur,- items: next,- selectedIndex: cur.selectedIndex < next.length ? cur.selectedIndex : 0,- })- }, [channelRefCandidates])-- const editor = useEditor({- immediatelyRender: false,- extensions: [- StarterKit.configure({- heading: false,- horizontalRule: false,- codeBlock: false,- code: false,- blockquote: false,- bold: false,- italic: false,- strike: false,- bulletList: false,- orderedList: false,- listItem: false,- listKeymap: false,- }),- Placeholder.configure({ placeholder: placeholder ?? (context === "channel" ? `Message /${channel}` : `Message ${channel}`) }),- mentionExtension,- channelRefExtension,- ],- editorProps: {- attributes: {- class: "outline-none",- enterkeyhint: isForumThreadBody ? "enter" : "send",- },- handleKeyDown: (_view, event) => {- // editorProps.handleKeyDown runs BEFORE the suggestion plugin's keymap,- // so when the mention popup is open we must NOT intercept Enter here —- // otherwise we'd send the message instead of picking the highlighted- // candidate. Returning false yields to ProseMirror's keymap chain, so- // the suggestion plugin gets Enter/Arrow/Tab/Esc as designed.- const mentionOpen =- mentionPopupRef.current.items.length > 0 && mentionPopupRef.current.command !== null- const channelRefOpen =- channelRefPopupRef.current.items.length > 0 && channelRefPopupRef.current.command !== null- if (mentionOpen || channelRefOpen) return false-- if (isForumThreadBody) {- if (event.key === "Enter" && event.shiftKey && !event.isComposing) {- event.preventDefault()- sendRef.current()- return true- }- return false- }-- if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {- event.preventDefault()- sendRef.current()- return true- }- return false- },- // Paste an image (or any file) from the clipboard → same pipeline as the- // file picker / drag-drop: `addPendingFiles` (25MB + MIME + thumbnail).- // Consume the event (`preventDefault` + `return true`) once files are- // found so ProseMirror doesn't ALSO paste the image as text/HTML. Text-- // only pastes return false and fall through to `clipboardTextParser`- // below, which preserves both newline levels.- handlePaste: (_view, event) => {- const files = clipboardFiles(event.clipboardData?.items)- if (files.length > 0) {- event.preventDefault()- addPendingFiles(files)- return true- }- return false- },- // Preserve BOTH newline levels on paste: a blank line (`\n\n`) becomes a- // paragraph break, a single `\n` becomes a hard line break — instead of- // ProseMirror's default, which collapses any run of newlines to one- // paragraph boundary (flattening a pasted multi-paragraph message). The- // built DOM is handed to ProseMirror's own `DOMParser.parseSlice` so- // slice open depths are computed by the library, not by hand.- clipboardTextParser: (text, $context) => {- const dom = buildPasteDom(text, document)- return PMDOMParser.fromSchema($context.doc.type.schema).parseSlice(dom, {- preserveWhitespace: true,- context: $context,- })- },- },- onUpdate: ({ editor }) => {- // Restore writes into the editor programmatically — don't treat that as- // the user typing (would fire a spurious typing indicator + re-save).- if (restoringDraftRef.current) return- fireTyping()- emitDirtyTransition()- const key = draftKeyRef.current- if (key && !isForumThreadBody) {- // Persist the ProseMirror doc (JSON), not plain text — so @mention /- // channel-ref pill nodes survive the round-trip and restore as pills,- // not inert `@label` text.- writeComposerDraft(key, editor.isEmpty ? null : editor.getJSON())- }- },- })-- // Restore a cached draft on mount / when the scope key changes. The view- // remounts on channel switch, so this fires once per composer instance for- // the common case; the `draftKey` dep also covers a same-instance scope- // change. Uses the paste pipeline so paragraph/hard-break structure round-- // trips exactly like `getText({blockSeparator:"\n\n"})` serialized it.- useEffect(() => {- if (!editor || isForumThreadBody || !draftKey) return- const doc = readComposerDraft(draftKey)- if (!doc) return- restoringDraftRef.current = true- try {- // Restore the stored ProseMirror doc directly — mention / channel-ref- // pill nodes come back as pills (a plain-text restore would flatten them- // to inert `@label` text). emitUpdate:false so the programmatic set isn't- // treated as typing; errorOnInvalidContent:true so a stale/incompatible- // doc throws into the catch below instead of silently blanking.- editor.commands.setContent(doc as JSONContent, { emitUpdate: false, errorOnInvalidContent: true })- } catch {- // Corrupt/incompatible stored doc — drop it rather than crash the editor.- clearComposerDraft(draftKey)- } finally {- restoringDraftRef.current = false- }- // Only re-run when the editor instance or scope key changes — not on every- // render. Restoring is a mount-time (per-instance) concern.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [editor, draftKey])-- // Emitted-emptiness ref — used by the onDirty transition logic below to fire- // only when the boolean flips. Initialized to false because the editor mounts- // empty and no attachments exist yet.- const prevHasContentRef = useRef<boolean>(false)- const onDirtyRef = useRef(onDirty)- useEffect(() => { onDirtyRef.current = onDirty }, [onDirty])- const emitDirtyTransition = () => {- if (!editor) return- const next = !editor.isEmpty || pendingFiles.length > 0- if (next === prevHasContentRef.current) return- prevHasContentRef.current = next- onDirtyRef.current?.(next)- }- // Attachment-side emptiness flips (drops, picker, removal) also feed onDirty.- useEffect(() => {- emitDirtyTransition()- // emitDirtyTransition reads editor + pendingFiles by closure, so bind to- // both. It's a stable inner closure — the dependency list is intentionally- // the observed state, not the function.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [pendingFiles, editor])-- const send = () => {- if (!editor || sendInFlightRef.current) return- const attemptScopeVersion = sendScopeVersionRef.current- const attemptLifecycle = lifecycleVersionRef.current- const attempt = (async () => {- const preparedFiles = await awaitPendingFiles()- if (- lifecycleVersionRef.current !== attemptLifecycle ||- sendScopeVersionRef.current !== attemptScopeVersion- ) return- if (editor.isEmpty && preparedFiles.length === 0) return- // Block separator `\n\n` — paragraph breaks serialize as a markdown blank- // line (a real paragraph), while in-paragraph hard breaks serialize as a- // single `\n` (HardBreak's `renderText`). `remark-breaks` on render turns- // the single `\n` into `<br>` and the blank line into a new paragraph, so- // the compose → send → render round-trip preserves both newline levels.- const markdown = editor.isEmpty ? "" : editor.getText({ blockSeparator: "\n\n" }).trim()- const mentionType = detectMentionType(markdown)- const attachments = pendingFilesToSendAttachments([...preparedFiles])- if (sendContract === "accepted") {- if (!onAcceptSend?.(markdown, attachments, mentionType)) return- } else {- await onDeferredSubmit?.(markdown, attachments, mentionType)- }- // In forumThreadBody mode the parent needs to await mutation success before- // clearing — otherwise a failed create wipes the user's typed content.- // Reset is delegated to the parent via `resetAfterSubmit()` on the ref.- if (isForumThreadBody) return- editor.commands.clearContent()- if (draftKeyRef.current) clearComposerDraft(draftKeyRef.current)- transferPendingFiles()- setMentionPopup(EMPTY_MENTION_STATE)- setChannelRefPopup(EMPTY_CHANNEL_REF_STATE)- })()- sendInFlightRef.current = attempt- void attempt.then(() => {- if (sendInFlightRef.current === attempt) sendInFlightRef.current = null- }, () => {- if (sendInFlightRef.current === attempt) sendInFlightRef.current = null- })- }-- useLayoutEffect(() => {- sendRef.current = send- })-- useImperativeHandle(ref, () => ({- focusEditor: () => { editor?.commands.focus("end") },- submitNow: () => {- send()- },- resetAfterSubmit: () => {- if (!editor) return- editor.commands.clearContent()- setPendingFiles([])- setMentionPopup(EMPTY_MENTION_STATE)- setChannelRefPopup(EMPTY_CHANNEL_REF_STATE)- },- isEmpty: () => !editor || (editor.isEmpty && pendingFiles.length === 0),- openFilePicker: () => { fileInputRef.current?.click() },- }))-- // Auto-focus on mount + on channel switch. `<Composer>` is not remounted- // per channel (only `<MessageList>` is keyed by channelId), so keying this- // effect on `channel` is what refocuses when the user navigates channels.- // Skipped in forumThreadBody mode — the parent controls focus (starts on the- // title, jumps to the body on Enter).- useEffect(() => {- if (!autoFocus || !editor || isForumThreadBody) return- editor.commands.focus("end")- }, [autoFocus, editor, channel, isForumThreadBody])-- // Focus the editor when a reply is initiated. Clicking "reply" on a message- // sets `replyingTo` on the parent but doesn't touch the composer, so without- // this the reply bar appears while focus stays on the message list — the user- // has to click into the input before typing. Fire only on the unset→set edge- // (clicking reply), not while a reply is already active or on cancel. Focus- // regardless of `autoFocus`: reply is an explicit user action, so popping the- // mobile keyboard is intended (same rationale as the drop handler below).- const prevReplyingToRef = useRef(replyingTo)- useEffect(() => {- const opened = !prevReplyingToRef.current && !!replyingTo- prevReplyingToRef.current = replyingTo- if (opened && editor && !isForumThreadBody) editor.commands.focus("end")- }, [replyingTo, editor, isForumThreadBody])-- // Refocus editor after a drop so the user can start typing without- // clicking. The drop landed on the composer container — the intent is- // clear.- const handleDrop = (e: React.DragEvent) => {- handleDropRaw(e)- editor?.commands.focus()- }-- return (- <div- className={isForumThreadBody ? "relative" : "relative px-3 pb-3 pt-0"}- onDragEnter={handleDragEnter}- onDragLeave={handleDragLeave}- onDragOver={handleDragOver}- onDrop={handleDrop}- >- <CommunityMentionList state={mentionPopup} />- <ChannelRefList state={channelRefPopup} />-- {/* reply context bar — attached above the input */}- {replyingTo && (- <div className="flex items-center gap-2 rounded-t-xl border border-b-0 border-border/40 bg-muted/60 px-4 py-2 text-xs text-muted-foreground">- <span className="min-w-0 truncate">Replying to <span className="font-medium text-foreground">{replyingTo}</span></span>- <button onClick={onCancelReply} className="ml-auto grid size-4 shrink-0 place-items-center rounded-full hover:bg-foreground/10 hover:text-foreground" aria-label="Cancel reply">- <X className="size-3.5" />- </button>- </div>- )}-- {/* pending attachments preview */}- {pendingFiles.length > 0 && (- <div className={`flex flex-wrap gap-2 border-x border-b border-border/40 bg-muted/40 px-4 py-2 ${replyingTo ? "" : "rounded-t-xl border-t"}`}>- {pendingFiles.map((pf, i) => {- const isImage = pf.file.type.startsWith("image/")- return (- <div key={i} className="group relative flex items-center gap-2 rounded-md border border-border bg-background px-3 py-2 text-xs">- {isImage ? <ImageIcon className="size-3.5 text-muted-foreground" /> : <FileIcon className="size-3.5 text-muted-foreground" />}- <span className="max-w-30 truncate text-foreground">{pf.file.name}</span>- <button- onClick={() => removePendingFile(i)}- className="grid size-4 shrink-0 place-items-center rounded-full hover:bg-destructive/10 hover:text-destructive"- aria-label="Remove file"- >- <X className="size-3" />- </button>- </div>- )- })}- </div>- )}-- <div className={`relative ${isForumThreadBody ? "bg-transparent ring-0" : "bg-muted shadow-(--e1) ring-1 ring-border/40 transition-shadow focus-within:ring-2 focus-within:ring-ring/60"} ${replyingTo || pendingFiles.length > 0 ? "rounded-b-xl" : "rounded-xl"}`}>- {dragging && (- <div- className={`pointer-events-none absolute inset-0 z-10 grid place-items-center border-2 border-dashed border-ring bg-background/80 ${replyingTo || pendingFiles.length > 0 ? "rounded-b-xl" : "rounded-xl"}`}- >- <p className="text-sm font-medium text-muted-foreground">Drop files here</p>- </div>- )}- <input- ref={fileInputRef}- type="file"- multiple- onChange={handleFileSelect}- className="hidden"- />- <div className={`chat-composer relative py-3 ${isForumThreadBody ? "px-2" : "px-12"}`} data-testid={tid.composerInput}>- <EditorContent editor={editor} className={`${isForumThreadBody ? "max-h-60" : "max-h-40"} overflow-y-auto thin-scrollbar text-base chat-input-line-height outline-none`} />- </div>- {/* Attach button — fixed bottom-left */}- {!hideAttach && (- <DropdownMenu onOpenChange={(open) => { if (!open) editor?.commands.focus() }}>- <DropdownMenuTrigger- render={<button data-testid={tid.composerAttach} className="absolute left-2 bottom-2 grid size-8 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground aria-expanded:bg-accent aria-expanded:text-foreground" aria-label="Add" />}- >- <PlusCircle className="size-5" />- </DropdownMenuTrigger>- <DropdownMenuContent side="top" align="start" className="w-44">- <DropdownMenuItem onClick={() => { fileInputRef.current?.click(); editor?.commands.focus() }}><Upload className="size-4" /> Upload a File</DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- )}- {/* Emoji button — fixed bottom-right */}- {!hideEmoji && (- <EmojiPickerPopover side="top" align="end" onPick={(e) => editor?.chain().focus().insertContent(e).run()}>- <button className="absolute right-2 bottom-2 grid size-8 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground aria-expanded:bg-accent aria-expanded:text-foreground" aria-label="Emoji picker">- <Smile className="size-5" />- </button>- </EmojiPickerPopover>- )}- </div>- </div>- )-})--// Loading placeholder for <Composer>. Same outer footprint (px-3 pb-3 pt-0 +-// rounded surface) so the message list above stays anchored across channel-// switches and the input bar doesn't jump in.-export function ComposerSkeleton() {- return (- <div className="relative px-3 pb-3 pt-0">- <div className="relative rounded-xl bg-muted px-12 py-3 shadow-(--e1) ring-1 ring-border/40">- <Skeleton className="h-5 w-2/5 rounded" />- <Skeleton className="absolute left-2 bottom-2 size-8 rounded-full" />- <Skeleton className="absolute right-2 bottom-2 size-8 rounded-full" />- </div>- </div>- )-}--// Structural equality on the popup's `items` array — used by the "members-// changed while popup is open" effect to skip no-op updates. Two lists are-// equal iff they have identical (kind,id,label) at each index; that's enough-// to catch the ranking-preserving cases (avatar/status flips get an update-// because the row visually differs). Guards against setPopup churn that-// would otherwise re-fire the effect via React's render loop.-function itemsEqual(a: MentionItem[], b: MentionItem[]): boolean {- if (a === b) return true- if (a.length !== b.length) return false- for (let i = 0; i < a.length; i++) {- const x = a[i]- const y = b[i]- if (x.kind !== y.kind || x.id !== y.id || x.label !== y.label) return false- if (x.kind === "member" && y.kind === "member") {- if (x.avatar !== y.avatar || x.status !== y.status) return false- }- }- return true-}--// Scroll the currently-highlighted row of a suggestion popover into view.-// Looks the row up by `aria-selected="true"` (not child index) — the mention-// list interleaves a "Members" section-header sibling, so an index lookup is-// off-by-one; the attribute is exact. Drives `scrollTop` directly (the popup is-// a fixed/transformed portal where `scrollIntoView` misbehaves). Row offsets-// are container-relative because the list container is `position:relative`.-function scrollSelectedRowIntoView(list: HTMLDivElement | null): void {- if (!list) return- const row = list.querySelector<HTMLElement>('[aria-selected="true"]')- if (!row) return- list.scrollTop = nextListScrollTop(- list.scrollTop,- list.clientHeight,- row.offsetTop,- row.offsetHeight,- )-}--// Shared positioning for both suggestion popups (@-mention + /-ref). Both are-// fixed portals anchored to the caret rect. Horizontal: clamp so the 256px-// popup never runs off the right edge. Vertical: prefer above the caret (the-// default), but FLIP to below when there isn't room above — otherwise a caret-// near the top of the viewport (e.g. the create-post form) lifts the popup off-// the top edge. `POPUP_MAX_HEIGHT` mirrors the list's `max-h-60` (240px).-const POPUP_WIDTH = 256-const POPUP_MAX_HEIGHT = 240-const VIEWPORT_MARGIN = 8--export function popoverStyle(rect: DOMRect, viewportW: number, viewportH: number): React.CSSProperties {- const maxLeft = Math.max(VIEWPORT_MARGIN, viewportW - POPUP_WIDTH - VIEWPORT_MARGIN)- const left = Math.min(rect.left, maxLeft)-- const spaceAbove = rect.top- const flipBelow = spaceAbove < POPUP_MAX_HEIGHT + VIEWPORT_MARGIN && rect.bottom + POPUP_MAX_HEIGHT + VIEWPORT_MARGIN <= viewportH- return flipBelow- ? { top: rect.bottom + 4, left }- : { top: rect.top - 4, left, transform: "translateY(-100%)" }-}--function viewportSize(): { w: number; h: number } {- if (typeof window === "undefined") return { w: POPUP_WIDTH, h: POPUP_MAX_HEIGHT }- return { w: window.innerWidth, h: window.innerHeight }-}--// Portal-rendered popup. Anchored to the caret via clientRect() from-// @tiptap/suggestion (above by default, flips below near the viewport top —-// see `popoverStyle`). Highlighted row syncs to hover so keyboard + pointer agree.-function CommunityMentionList({ state }: { state: MentionPopupState }) {- const listRef = useRef<HTMLDivElement>(null)- const { items, selectedIndex, command, rect } = state-- useEffect(() => {- scrollSelectedRowIntoView(listRef.current)- }, [selectedIndex])-- if (!rect || items.length === 0 || !command) return null-- // Whether to show a "MEMBERS" section header above the first member row —- // only when virtual (everyone/here) rows precede members.- const firstMemberIdx = items.findIndex((it) => it.kind === "member")- const hasVirtual = items.some((it) => it.kind !== "member")- const showMembersHeader = hasVirtual && firstMemberIdx > 0-- const vp = viewportSize()-- return createPortal(- <div- className="fixed z-100 w-64 rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-(--e2)"- style={popoverStyle(rect, vp.w, vp.h)}- >- <div ref={listRef} className="relative max-h-60 overflow-x-hidden overflow-y-auto thin-scrollbar">- {items.map((item, i) => {- const selected = i === selectedIndex- return (- <MentionRow- key={`${item.kind}:${item.id}`}- item={item}- selected={selected}- showMembersHeader={showMembersHeader && i === firstMemberIdx}- onSelect={() => command({ id: item.id, label: item.label })}- />- )- })}- </div>- </div>,- document.body,- )-}--// Structural equality on the channel-ref popup's `items` array — same-// no-op-skip purpose as `itemsEqual` above.-function channelRefItemsEqual(a: ChannelRefCandidate[], b: ChannelRefCandidate[]): boolean {- if (a === b) return true- if (a.length !== b.length) return false- for (let i = 0; i < a.length; i++) {- if (a[i].id !== b[i].id || a[i].name !== b[i].name || a[i].serverId !== b[i].serverId) return false- }- return true-}--// Portal-rendered `/`-ref popup. Mirrors `CommunityMentionList` — anchored-// above the caret via clientRect(), highlighted row synced to hover.-function ChannelRefList({ state }: { state: ChannelRefPopupState }) {- const listRef = useRef<HTMLDivElement>(null)- const { items, selectedIndex, command, rect } = state-- useEffect(() => {- scrollSelectedRowIntoView(listRef.current)- }, [selectedIndex])-- if (!rect || items.length === 0 || !command) return null-- // The list spans multiple servers (the DM case) when any two candidates- // differ on serverId — only then does each row show its "serverName /"- // prefix, so same-server lists stay clean.- const spansMultipleServers = items.some((it) => it.serverId !== items[0]?.serverId)-- const vp = viewportSize()-- return createPortal(- <div- className="fixed z-100 w-64 rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-(--e2)"- style={popoverStyle(rect, vp.w, vp.h)}- >- <div ref={listRef} className="relative max-h-60 overflow-x-hidden overflow-y-auto thin-scrollbar">- {items.map((item, i) => (- <ChannelRefRow- key={item.id}- item={item}- selected={i === selectedIndex}- showServerPrefix={spansMultipleServers}- onSelect={() => command(toChannelRefCommandProps(item))}- />- ))}- </div>- </div>,- document.body,- )-}--function ChannelRefRow({ item, selected, showServerPrefix, onSelect }: {- item: ChannelRefCandidate- selected: boolean- showServerPrefix: boolean- onSelect: () => void-}) {- return (- <button- type="button"- role="option"- aria-selected={selected}- className={[- "flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm transition-colors",- selected ? "bg-accent" : "hover:bg-accent/50",- ].join(" ")}- onMouseDown={(e) => {- // mousedown (not click) — same rationale as MentionRow.- e.preventDefault()- onSelect()- }}- >- <ChannelIcon className="size-3.5 text-muted-foreground" />- <span className="font-medium">- {showServerPrefix && <span className="text-muted-foreground">{item.serverName} / </span>}- {item.name}- </span>- </button>- )-}--function MentionRow({ item, selected, showMembersHeader, onSelect }: {- item: MentionItem- selected: boolean- showMembersHeader: boolean- onSelect: () => void-}) {- return (- <>- {showMembersHeader && (- <div className="-mx-1 mt-1 border-t border-border/60 px-2 pt-2 pb-1 text-xs font-semibold text-muted-foreground">Members</div>- )}- <button- type="button"- role="option"- data-testid={tid.mentionOption(item.id)}- aria-selected={selected}- className={[- "flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm transition-colors",- selected ? "bg-accent" : "hover:bg-accent/50",- ].join(" ")}- onMouseDown={(e) => {- // mousedown (not click) so the editor doesn't blur first and lose- // the suggestion plugin's caret tracking.- e.preventDefault()- onSelect()- }}- >- {item.kind === "member" ? (- <Avatar label={item.avatar} seed={item.userId} size={24} presence={item.status} ringColor="var(--popover)" />- ) : (- // Only `@everyone` remains as a virtual (non-member) item — `@here`- // was removed (plans/remove-here-mention.md).- <span className="grid size-6 place-items-center rounded-full bg-primary/15 text-primary">- <Users className="size-3.5" />- </span>- )}- <span className="font-medium">- {item.kind === "member" ? (- <>- {item.name}- <span className="ml-1 text-xs font-normal tracking-wide text-muted-foreground">- #{item.discriminator}- </span>- </>- ) : (- `@${item.label}`- )}- </span>- {item.kind !== "member" && (- <span className="ml-auto text-xs text-muted-foreground">Notify everyone</span>- )}- </button>- </>- )-}diff --git a/src/web/src/components/community/entity-icon.test.ts b/src/web/src/components/community/entity-icon.test.tsindex 48f7a0bce..98e99e114 100644--- a/src/web/src/components/community/entity-icon.test.ts+++ b/src/web/src/components/community/entity-icon.test.ts@@ -1,7 +1,7 @@import { describe, it, expect } from "vitest"import { Hash, ListChevronsUpDown } from "lucide-react"import { getEntityIcon } from "./entity-icon"-import { ChannelIcon } from "./channel-icon"+import { ChannelIcon } from "./channels/channel-icon"describe("getEntityIcon", () => {it("text and undefined → ChannelIcon (the custom slash glyph)", () => {diff --git a/src/web/src/components/community/entity-icon.tsx b/src/web/src/components/community/entity-icon.tsxindex 9c9c14dbb..d778e3299 100644--- a/src/web/src/components/community/entity-icon.tsx+++ b/src/web/src/components/community/entity-icon.tsx@@ -1,5 +1,6 @@import { Hash, ListChevronsUpDown } from "lucide-react"-import { ChannelIcon } from "./channel-icon"+import { ChannelIcon } from "./channels/channel-icon"+import type { EntityKind } from "@/lib/community/models/navigation"/*** Every community entity that gets a leading glyph, keyed by its RAW stored@@ -7,8 +8,6 @@ import { ChannelIcon } from "./channel-icon"* carries `"thread"` — so this wider union takes the raw value straight off* the row without a lossy cast.*/-export type EntityKind = "text" | "forum" | "thread"-type IconComponent = (props: { className?: string }) => React.ReactNode/**diff --git a/src/web/src/components/community/add-members-dialog.test.ts b/src/web/src/components/community/members/add-members-dialog.test.tssimilarity index 100%rename from src/web/src/components/community/add-members-dialog.test.tsrename to src/web/src/components/community/members/add-members-dialog.test.tsdiff --git a/src/web/src/components/community/add-members-dialog.tsx b/src/web/src/components/community/members/add-members-dialog.tsxsimilarity index 99%rename from src/web/src/components/community/add-members-dialog.tsxrename to src/web/src/components/community/members/add-members-dialog.tsxindex b56da3a3b..0658f3ad9 100644--- a/src/web/src/components/community/add-members-dialog.tsx+++ b/src/web/src/components/community/members/add-members-dialog.tsx@@ -6,7 +6,7 @@ import { Search, Loader2 } from "lucide-react"import { Dialog, DialogContent } from "@/components/ui/dialog"import { Input } from "@/components/ui/input"import { Button } from "@/components/ui/button"-import { Avatar } from "./avatar"+import { Avatar } from "../avatar"import { displayName } from "@/lib/community/display-name"import { toastApiError } from "@/lib/api/client"diff --git a/src/web/src/components/community/channel-add-members-dialog.tsx b/src/web/src/components/community/members/channel-add-members-dialog.tsxsimilarity index 100%rename from src/web/src/components/community/channel-add-members-dialog.tsxrename to src/web/src/components/community/members/channel-add-members-dialog.tsxdiff --git a/src/web/src/components/community/channel-member-view-model.test.ts b/src/web/src/components/community/members/channel-member-view-model.test.tssimilarity index 98%rename from src/web/src/components/community/channel-member-view-model.test.tsrename to src/web/src/components/community/members/channel-member-view-model.test.tsindex c56695dde..60d0b1ed1 100644--- a/src/web/src/components/community/channel-member-view-model.test.ts+++ b/src/web/src/components/community/members/channel-member-view-model.test.ts@@ -63,10 +63,10 @@ vi.mock("@/stores/community/ws", () => ({useCommunityWsStore: (selector: (state: { userStatuses: typeof mocks.userStatuses }) => unknown) =>selector({ userStatuses: mocks.userStatuses }),}))-vi.mock("@/components/community/add-members-dialog", () => ({+vi.mock("@/components/community/members/add-members-dialog", () => ({AddMembersDialog: vi.fn(() => null),}))-vi.mock("@/components/community/community-panel-sheet", () => ({+vi.mock("@/components/community/shell/community-panel-sheet", () => ({CommunityPanelSheet: () => null,}))diff --git a/src/web/src/components/community/channel-member-view-model.tsx b/src/web/src/components/community/members/channel-member-view-model.tsxsimilarity index 97%rename from src/web/src/components/community/channel-member-view-model.tsxrename to src/web/src/components/community/members/channel-member-view-model.tsxindex d5b3f8105..81fcb9fa8 100644--- a/src/web/src/components/community/channel-member-view-model.tsx+++ b/src/web/src/components/community/members/channel-member-view-model.tsx@@ -2,10 +2,10 @@import { useEffect, useMemo, useState, type ComponentProps, type ReactNode } from "react"import { toast } from "sonner"-import { isForum } from "@alook/shared"-import { AddMembersDialog } from "@/components/community/add-members-dialog"-import type { CommunityPanelSheet } from "@/components/community/community-panel-sheet"-import type { Member, Role } from "@/components/community/_types"+import { isForum, type CommunityRole as Role } from "@alook/shared"+import { AddMembersDialog } from "@/components/community/members/add-members-dialog"+import type { CommunityPanelSheet } from "@/components/community/shell/community-panel-sheet"+import type { Member } from "@/lib/community/models/people"import { toastApiError } from "@/lib/api/client"import { makeUserNameResolver } from "@/lib/community/display-name"import { resolveRowPresence } from "@/lib/community/presence"diff --git a/src/web/src/components/community/member-list.test.ts b/src/web/src/components/community/members/member-list.test.tssimilarity index 97%rename from src/web/src/components/community/member-list.test.tsrename to src/web/src/components/community/members/member-list.test.tsindex 0c8c4b83c..ae790c0b2 100644--- a/src/web/src/components/community/member-list.test.ts+++ b/src/web/src/components/community/members/member-list.test.ts@@ -3,7 +3,7 @@ import fs from "node:fs"import path from "node:path"import { fileURLToPath } from "node:url"import { computeDuplicateNames, hasMemberMenu } from "./member-list"-import type { Member } from "./_types"+import type { Member } from "@/lib/community/models/people"const member = (id: string, name: string, discriminator = "0000"): Member => ({id,diff --git a/src/web/src/components/community/member-list.tsx b/src/web/src/components/community/members/member-list.tsxsimilarity index 97%rename from src/web/src/components/community/member-list.tsxrename to src/web/src/components/community/members/member-list.tsxindex b232285de..c89e4c1fb 100644--- a/src/web/src/components/community/member-list.tsx+++ b/src/web/src/components/community/members/member-list.tsx@@ -9,14 +9,23 @@ import {} from "@/components/ui/context-menu"import { Skeleton } from "@/components/ui/skeleton"import { Input } from "@/components/ui/input"-import { Avatar } from "./avatar"+import { Avatar } from "../avatar"import { ConfirmDialog } from "@/components/ui/confirm-dialog"import { toastApiError } from "@/lib/api/client"import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS } from "@/hooks/community/virtualizer-react-options"-import { hasStatus } from "./status-presets"+import { hasStatus } from "../social/status-presets"import { tid } from "@/lib/community/testids"-import type { Member, Role, OpenProfile, MemberManageContext } from "./_types"-import { canManageServer, isServerOwner, ROLES, isPresenceOnline, isPresenceOffline } from "./_types"+import type { Member } from "@/lib/community/models/people"+import type { OpenProfile } from "@/components/community/social/profile-types"+import type { MemberManageContext } from "@/components/community/members/member-management-types"+import {+ canManageServer,+ isPresenceOffline,+ isPresenceOnline,+ isServerOwner,+ ROLES,+ type CommunityRole as Role,+} from "@alook/shared"// The Leave/Remove confirm flow the row menu opens (private channel/post/thread).type ManageConfirm = { kind: "leave" | "remove"; member: Member }diff --git a/src/web/src/components/community/members/member-management-types.ts b/src/web/src/components/community/members/member-management-types.tsnew file mode 100644index 000000000..788d1d95b--- /dev/null+++ b/src/web/src/components/community/members/member-management-types.ts@@ -0,0 +1,19 @@+// Passed to the Members drawer when it's showing a private channel/post roster+// OR a thread's participants — the row right-click menu becomes Leave (self,+// non-creator) / Remove (viewer is the unit creator, on other explicit members)+// instead of the server-scoped Role/Kick menu. Remove is CREATOR-ONLY on every+// unit (admins have no content privilege). The creator's own row is locked.+export type MemberManageContext = {+ viewerUserId: string+ // The viewer created this unit → their own row shows no Leave (owners keep+ // the unit), and they may Remove other explicit members.+ viewerIsCreator: boolean+ // The unit's display name (channel/post/thread), used in the Leave confirm+ // dialog title ("Leave /general?"). Optional for back-compat.+ unitLabel?: string+ // Return a promise so the confirm dialog can show a loading state until the+ // remove settles. Resolved value is ignored (mutateAsync resolves to the API+ // payload) — the dialog only awaits settlement.+ onLeave: (userId: string) => Promise<unknown> | void+ onRemove: (userId: string) => Promise<unknown> | void+}diff --git a/src/web/src/components/community/private-category-row.test.ts b/src/web/src/components/community/members/private-category-row.test.tssimilarity index 100%rename from src/web/src/components/community/private-category-row.test.tsrename to src/web/src/components/community/members/private-category-row.test.tsdiff --git a/src/web/src/components/community/private-category-row.tsx b/src/web/src/components/community/members/private-category-row.tsxsimilarity index 100%rename from src/web/src/components/community/private-category-row.tsxrename to src/web/src/components/community/members/private-category-row.tsxdiff --git a/src/web/src/components/community/message-channel-controller.tsx b/src/web/src/components/community/message-channel-controller.tsxdeleted file mode 100644index 1de3ecd8a..000000000--- a/src/web/src/components/community/message-channel-controller.tsx+++ /dev/null@@ -1,524 +0,0 @@-"use client"--import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react"-import { useRouter, useSearchParams } from "next/navigation"-import { toast } from "sonner"-import { deriveThreadName, type MentionType } from "@alook/shared"-import { apiFetch, toastApiError } from "@/lib/api/client"-import { avatarInitial } from "@/lib/community/avatar"-import type { FileAttachment, ImagePreview, Msg } from "@/components/community/_types"-import type { SendAttachment } from "@/components/community/composer"-import type { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"-import {- useCommunityStore,- useTypingNamesForScope,- useTypingUsersForScope,-} from "@/stores/community"-import { useMessageStreamStore } from "@/stores/community/message-stream"-import { toOptimisticReplyPreview } from "@/lib/community/reply-preview"-import {- sendNonce,- tempMessageId,- toAttachmentVm,- useCreateThread,- useEditMessage,- usePinMessage,- useSendMessage,- useToggleMark,- useToggleReactionApi,- useUnpinMessage,- useUploadFile,- zipUploadResultsWithDimensions,- type UploadedAttachment,-} from "@/hooks/community/mutations"-import {- communityWsResetTypingThrottle,- communityWsSendTyping,-} from "@/hooks/community/use-community-ws"--type MessageFeed = ReturnType<typeof useChannelMessageFeed>--type Viewer = {- id: string- name: string- avatar: string-}--type MessageUiHandlers = {- navigate?: (serverId: string, channelId: string) => void- previewImage?: (image: ImagePreview) => void- previewAttachment?: (attachment: FileAttachment) => void-}--export function MessageChannelController({- channelId,- serverId,- serverParam,- channelName,- forumParentChannelId,- viewer,- anchorMessageId,- feed,- uiHandlers,- onOpenThread,- onOpenPinned,- resolveUserName,- children,-}: {- channelId: string- serverId: string- serverParam: string- channelName: string- forumParentChannelId?: string- viewer: Viewer- anchorMessageId: string | null- feed: MessageFeed- uiHandlers: MessageUiHandlers- onOpenThread: (threadId: string) => void- onOpenPinned: () => void- resolveUserName: (userId: string) => string- children: (controller: MessageChannelControllerValue) => ReactNode-}) {- const router = useRouter()- const searchParams = useSearchParams()- const [replyTo, setReplyTo] = useState<{ id: string; authorName: string; text: string } | null>(null)- const [searchQuery, setSearchQuery] = useState("")- const [searchResults, setSearchResults] = useState<Msg[]>([])- const [scrollTargetId, setScrollTargetId] = useState<string | null>(anchorMessageId)- const [contextTarget, setContextTarget] = useState<{- serverId: string- channelId: string- label: string- seq: number- } | null>(null)- const { mutateAsync: sendMessageAsync } = useSendMessage()- const toggleReactionApi = useToggleReactionApi()- 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}`)- const typingNames = useTypingNamesForScope(`ch:${channelId}`)- const pinnedIds = useMemo(() => new Set(feed.pinned.map((message) => message.id)), [feed.pinned])- const consumeScrollTarget = useCallback((targetId: string) => {- setScrollTargetId((current) => (current === targetId ? null : current))- }, [])-- useEffect(() => {- if (!scrollTargetId) return- if (feed.messages.some((message) => message.id === scrollTargetId)) return- if (feed.isError) {- setScrollTargetId((current) => (current === scrollTargetId ? null : current))- }- }, [- scrollTargetId,- feed.messages,- feed.isError,- ])-- useEffect(() => {- setReplyTo(null)- setSearchQuery("")- setSearchResults([])- setContextTarget(null)- }, [channelId])-- const search = useCallback(async (query: string) => {- setSearchQuery(query)- if (!query.trim()) {- setSearchResults([])- return- }- try {- const params = new URLSearchParams({ q: query, channelId })- const data = await apiFetch<{- results: Array<{- message: { id: string; content: string; authorId: string; createdAt: string }- author: { name: string; image: string | null }- }>- }>(`/api/community/messages/search?${params}`)- setSearchResults(data.results.map((result) => ({- id: result.message.id,- type: "chat" as const,- authorName: result.author.name,- authorAvatar: result.author.image ?? avatarInitial(result.author.name),- content: result.message.content,- createdAt: result.message.createdAt,- })))- } catch (error) {- setSearchResults([])- toastApiError(error, "Search failed")- }- }, [channelId])-- const openContextSeq = useCallback((seq: number) => {- setContextTarget((current) =>- current ? { ...current, seq } : { serverId, channelId, label: channelName, seq },- )- }, [serverId, channelId, channelName])-- const onSheetReply = useCallback((target: { id: string; authorName: string; text: string }) => {- if (contextTarget && contextTarget.channelId !== channelId) {- useCommunityStore.getState().setPendingReply({ channelId: contextTarget.channelId, target })- setContextTarget(null)- uiHandlers.navigate?.(contextTarget.serverId, contextTarget.channelId)- return- }- setReplyTo(target)- setContextTarget(null)- }, [contextTarget, channelId, uiHandlers])-- const pendingReply = useCommunityStore((state) => state.pendingReply)- useEffect(() => {- if (!pendingReply || pendingReply.channelId !== channelId) return- setReplyTo(pendingReply.target)- useCommunityStore.getState().setPendingReply(null)- }, [pendingReply, channelId])-- const actionContext = useRef({- messages: feed.messages,- pinnedIds,- channelName,- uiHandlers,- onOpenThread,- onOpenPinned,- })- useLayoutEffect(() => {- actionContext.current = {- messages: feed.messages,- pinnedIds,- channelName,- uiHandlers,- onOpenThread,- onOpenPinned,- }- }, [feed.messages, pinnedIds, channelName, uiHandlers, onOpenThread, onOpenPinned])-- const jumpToSeq = useCallback((seq: number) => {- const message = actionContext.current.messages.find((item) => item.seq === seq)- if (message) setScrollTargetId(message.id)- else setContextTarget({ serverId, channelId, label: channelName, seq })- }, [serverId, channelId, channelName])-- const openMessageContext = useCallback(- (target: { serverId: string; channelId: string; label: string; seq: number }) => setContextTarget(target),- [],- )-- useEffect(() => {- useCommunityStore.getState().registerUiHandlers({ jumpToSeq, openMessageContext })- return () => useCommunityStore.getState().registerUiHandlers({ jumpToSeq: undefined, openMessageContext: undefined })- }, [jumpToSeq, openMessageContext])-- const seqParam = searchParams.get("seq")- useEffect(() => {- if (!seqParam) return- const seq = Number(seqParam)- if (!Number.isFinite(seq)) return- setContextTarget({ serverId, channelId, label: channelName, seq })- router.replace(`/c/channels/${serverParam}/${channelId}`, { scroll: false })- }, [seqParam, serverId, channelId, channelName, router, serverParam])-- const messageScope = useMemo(- () => ({ kind: "channel" as const, id: channelId, serverId }),- [channelId, serverId],- )-- const runAcceptedIntent = useCallback(- async (nonce: string) => {- const streamStore = useMessageStreamStore.getState()- const payload = streamStore.getRetryPayload(messageScope, nonce)- if (!payload) return- let uploadedAttachments: UploadedAttachment[] | undefined- if (payload.localUploads.length > 0 && payload.uploadStatus === "settled") {- const projected = payload.message.attachments- if (projected?.length === payload.localUploads.length) {- uploadedAttachments = projected.map((attachment, index) => {- const local = payload.localUploads[index]- return {- id: attachment.url.slice(attachment.url.lastIndexOf("/") + 1),- filename: local.file.name,- contentType: local.file.type,- size: local.file.size,- ...(attachment.kind === "image" && attachment.thumbnailUrl !== undefined- ? { hasThumbnail: true }- : {}),- width: local.width,- height: local.height,- }- })- }- }- if (payload.localUploads.length > 0 && !uploadedAttachments) {- const results = await Promise.all(- payload.localUploads.map((upload) =>- uploadFileAsync({- target: { channelId },- file: upload.file,- thumbnailBlob: upload.thumbnailBlob,- width: upload.width,- height: upload.height,- }).catch((error) => {- toastApiError(error, "Failed to attach file")- return null- }),- ),- )- if (results.some((result) => result === null)) {- streamStore.dispatch(messageScope, { type: "uploadFailed", nonce })- return- }- uploadedAttachments = zipUploadResultsWithDimensions(results, [...payload.localUploads])- streamStore.dispatch(messageScope, {- type: "uploadSettled",- nonce,- attachments: uploadedAttachments.map((attachment) =>- toAttachmentVm(channelId, attachment)),- })- }- try {- await sendMessageAsync({- serverId,- channelId,- forumParentChannelId,- content: payload.message.content ?? "",- replyToId: payload.message.replyTo?.id,- mentionType: payload.mentionType,- attachments: uploadedAttachments,- nonce,- author: {- id: viewer.id,- name: viewer.name,- avatar: viewer.avatar,- },- })- } catch {- return- }- },- [messageScope, uploadFileAsync, channelId, forumParentChannelId, sendMessageAsync, serverId, viewer.id, viewer.name, viewer.avatar],- )-- const messageActions = useMemo(() => ({- onToggleReaction: (id: string, emoji: string) =>- toggleReactionApi({ serverId, channelId, messageId: id, emoji, userId: viewer.id }),- onReact: (id: string, emoji: string) =>- toggleReactionApi({ serverId, channelId, messageId: id, emoji, userId: viewer.id }),- onReply: (id: string) => {- const message = actionContext.current.messages.find((item) => item.id === id)- if (message) {- setReplyTo({- id: message.id,- authorName: message.authorName ?? "",- text: message.content ?? "",- })- }- },- onPin: (id: string) => {- if (actionContext.current.pinnedIds.has(id)) {- unpinMessageMutate({ channelId, messageId: id }, {- onSuccess: () => toast("Message unpinned"),- onError: (error) => toastApiError(error, "Failed to unpin message"),- })- return- }- pinMessageMutate({ channelId, messageId: id }, {- onSuccess: () => toast("Message pinned"),- onError: (error) => toastApiError(error, "Failed to pin message"),- })- actionContext.current.onOpenPinned()- },- onMark: (id: string) => toggleMark(channelId, id),- onCreateThread: async (id: string) => {- const message = actionContext.current.messages.find((item) => item.id === id)- const name = deriveThreadName(message?.content, actionContext.current.channelName)- try {- const data = await createThreadAsync({ serverId, channelId, messageId: id, name })- actionContext.current.onOpenThread(data.id)- } catch (error) {- toastApiError(error, "Failed to create thread")- }- },- onCopy: (id: string) => {- const message = actionContext.current.messages.find((item) => item.id === id)- if (!message?.content) return- void navigator.clipboard?.writeText(message.content)- toast("Copied to clipboard")- },- onEdit: (id: string) => {- const message = actionContext.current.messages.find((item) => item.id === id)- if (!message?.content || message.authorId !== viewer.id || message.seq === undefined) return- const content = window.prompt("Edit message", message.content)- if (!content || content === message.content) return- editMessage({ serverId, channelId, messageId: id, content }, {- onError: (error) => toastApiError(error, "Failed to edit message"),- })- },- onRetry: (id: string) => {- const message = actionContext.current.messages.find((item) => item.id === id)- if (!message?.clientNonce) return- useMessageStreamStore.getState().dispatch(messageScope, {- type: "retry",- nonce: message.clientNonce,- })- void runAcceptedIntent(message.clientNonce)- },- onDismiss: (id: string) => {- const message = actionContext.current.messages.find((item) => item.id === id)- if (!message?.clientNonce) return- useMessageStreamStore.getState().dispatch(messageScope, {- type: "dismissFailed",- nonce: message.clientNonce,- })- },- onPreviewImage: (image: ImagePreview) => actionContext.current.uiHandlers.previewImage?.(image),- onPreviewAttachment: (attachment: FileAttachment) => actionContext.current.uiHandlers.previewAttachment?.(attachment),- onDownloadFile: (url: string, name: string) => {- const link = document.createElement("a")- link.href = url- link.download = name- link.click()- },- }), [- channelId,- serverId,- viewer.id,- toggleReactionApi,- unpinMessageMutate,- pinMessageMutate,- toggleMark,- createThreadAsync,- editMessage,- messageScope,- runAcceptedIntent,- ])-- const acceptMessage = useCallback((- markdown: string,- attachments?: SendAttachment[],- mentionType?: MentionType,- ): boolean => {- if (!markdown && !attachments?.length) return false- const nonce = sendNonce()- const createdPreviewUrls: string[] = []- const accepted = useMessageStreamStore.getState().accept(messageScope, {- nonce,- tempId: tempMessageId(),- message: {- type: "chat",- authorId: viewer.id,- authorName: viewer.name,- authorAvatar: viewer.avatar,- content: markdown,- createdAt: new Date().toISOString(),- ...(replyTo ? { replyTo: toOptimisticReplyPreview(replyTo) } : {}),- },- localUploads: attachments?.map((attachment) => {- const previewObjectUrl = attachment.previewObjectUrl ?? URL.createObjectURL(attachment.file)- if (!attachment.previewObjectUrl) createdPreviewUrls.push(previewObjectUrl)- return {- file: attachment.file,- thumbnailBlob: attachment.thumbnailBlob,- previewObjectUrl,- width: attachment.width,- height: attachment.height,- }- }) ?? [],- mentionType,- })- if (!accepted) {- for (const url of createdPreviewUrls) URL.revokeObjectURL(url)- return false- }- void runAcceptedIntent(nonce)- communityWsResetTypingThrottle({ channelId })- setReplyTo(null)- return true- }, [channelId, messageScope, replyTo, runAcceptedIntent, viewer.avatar, viewer.id, viewer.name])-- const value = useMemo<MessageChannelControllerValue>(() => ({- feed,- pinnedIds,- replyTo,- setReplyTo,- searchQuery,- searchResults,- search,- scrollTargetId,- setScrollTargetId,- consumeScrollTarget,- contextTarget,- setContextTarget,- openContextSeq,- onSheetReply,- jumpToSeq,- messageActions,- threadActions: { ...messageActions, onCreateThread: undefined },- acceptMessage,- handleTyping: () => communityWsSendTyping({ channelId }),- typingUsers: typingUserIds.map((id) => typingNames[id] ?? resolveUserName(id)),- }), [- feed,- pinnedIds,- replyTo,- searchQuery,- searchResults,- search,- scrollTargetId,- consumeScrollTarget,- contextTarget,- openContextSeq,- onSheetReply,- jumpToSeq,- messageActions,- acceptMessage,- channelId,- typingUserIds,- typingNames,- resolveUserName,- ])-- // eslint-disable-next-line react-hooks/refs -- render prop receives callbacks that read the latest ref only on user actions- return children(value)-}--export type MessageChannelControllerValue = {- feed: MessageFeed- pinnedIds: Set<string>- replyTo: { id: string; authorName: string; text: string } | null- setReplyTo: (reply: { id: string; authorName: string; text: string } | null) => void- searchQuery: string- searchResults: Msg[]- search: (query: string) => void- scrollTargetId: string | null- setScrollTargetId: (targetId: string | null) => void- consumeScrollTarget: (targetId: string) => void- contextTarget: { serverId: string; channelId: string; label: string; seq: number } | null- setContextTarget: (target: { serverId: string; channelId: string; label: string; seq: number } | null) => void- openContextSeq: (seq: number) => void- onSheetReply: (target: { id: string; authorName: string; text: string }) => void- jumpToSeq: (seq: number) => void- messageActions: {- onToggleReaction: (id: string, emoji: string) => void- onReact: (id: string, emoji: string) => void- onReply: (id: string) => void- onPin: (id: string) => void- 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- onPreviewAttachment: (attachment: FileAttachment) => void- onDownloadFile: (url: string, name: string) => void- }- threadActions: Omit<MessageChannelControllerValue["messageActions"], "onCreateThread"> & {- onCreateThread: undefined- }- acceptMessage: (markdown: string, attachments?: SendAttachment[], mentionType?: MentionType) => boolean- handleTyping: () => void- typingUsers: string[]-}diff --git a/src/web/src/components/community/message-list.tsx b/src/web/src/components/community/message-list.tsxdeleted file mode 100644index bb814d565..000000000--- a/src/web/src/components/community/message-list.tsx+++ /dev/null@@ -1,598 +0,0 @@-"use client"--import { useCallback, useEffect, useMemo, useRef, useState } from "react"-import { ArrowDown, ImageIcon, X } from "lucide-react"-import { tid } from "@/lib/community/testids"-import { DateDivider, NewDivider } from "./dividers"-import { MessageRow } from "./message-row"-import { MessageShareDialog } from "./message-share-dialog"-import { TypingIndicator } from "./typing-indicator"-import { ChannelIcon } from "./channel-icon"-import { Button } from "@/components/ui/button"-import { Skeleton } from "@/components/ui/skeleton"-import type { RenderMsg } from "./_types"-import { NumberTicker } from "@/components/ui/number-ticker"-import { useScrollAnchor } from "@/hooks/community/use-scroll-anchor"-import { flattenMessageItems } from "./message-list-items"-import { VirtualRows } from "./virtual-cursor-list"-import { useVirtualCursorSentinel } from "@/hooks/community/use-virtual-cursor-sentinel"-import type { FileAttachment, ImagePreview, Msg, OpenProfile } from "./_types"--// Channel message list — welcome hero, date dividers, messages (with the NEW divider),-// and typing indicator. Data via props.-export function MessageList({- channel, messages, loading, pinnedIds, newDividerBefore, typingUsers, onOpenThread, onOpenProfile,- onToggleReaction, onReact,- onReply, onPin, onMark, onCreateThread, onCopy, onEdit, onRetry, onDismiss, onPreviewImage, onPreviewAttachment, onDownloadFile,- resolveUserName, scrollToMessageId, hero, variant = "channel", onScrollRoot, viewerUserId, initialScrollReady = true,- onScrollTargetConsumed,- hasMore, isFetchingOlder, onLoadOlder,- hasMoreNewer, isFetchingNewer, onLoadNewer, onJumpToPresent, presentVersion, unreadCount,-}: {- channel: string- messages: Msg[]- loading?: boolean- pinnedIds?: Set<string>- newDividerBefore?: string- typingUsers?: string[]- onOpenThread: (id: string) => void- onOpenProfile?: OpenProfile- onToggleReaction?: (id: string, emoji: string) => void- onReact?: (id: string, emoji: string) => void- onReply?: (id: string) => void- onPin?: (id: string) => void- 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- onPreviewAttachment?: (attachment: FileAttachment) => void- onDownloadFile?: (url: string, name: string) => void- resolveUserName?: (userId: string) => string- scrollToMessageId?: string | null- hero?: React.ReactNode- // Explicit skeleton-shape selector — replaces the old `dm={!!hero}`- // inference, which silently misfired the moment a channel-context loading- // `hero` was introduced (the skeleton's DM/channel shape and the `hero`- // slot are orthogonal concerns; `hero`'s presence was never a reliable- // signal for which one this view is).- variant?: "channel" | "dm"- /**- * Called with the scroll-root element once it mounts (and `null` on- * unmount). Consumers (e.g. `useChannelWatermark`) use this to observe- * `[data-msg-id]` rows against the correct viewport root rather than the- * page's default viewport.- */- onScrollRoot?: (el: HTMLDivElement | null) => void- // Viewer id — enables "scroll to bottom when the viewer sends a message".- // Without this the auto-follow only fires at mount time; incoming peer- // messages never pull the view.- viewerUserId?: string- // Gate for the mount-time initial scroll. Owners that need to wait for- // async NEW-divider anchor data (`useChannelReadStateSnapshot`) pass- // `false` until the snapshot resolves; otherwise the effect fires with a- // stale `newDividerBefore = undefined` and snaps to bottom before the- // anchor is known.- initialScrollReady?: boolean- onScrollTargetConsumed?: (id: string) => void- // Reverse-infinite scroll. When `hasMore` is true a top sentinel is- // rendered; when it enters the viewport (via IntersectionObserver on the- // scroll root) `onLoadOlder()` fires. The prepended rows are scroll-- // anchored below (see `useScrollAnchor`) so the user's visual position- // stays fixed.- hasMore?: boolean- isFetchingOlder?: boolean- onLoadOlder?: () => void- // Forward-infinite scroll (bi-directional pagination — A2). When the- // initial page is an anchor window in the middle of history, the tail is- // NOT the newest message; a bottom sentinel is rendered until the user- // scrolls into it to request newer rows. Legacy newest-attached mode- // leaves `hasMoreNewer` undefined/false — no bottom sentinel.- hasMoreNewer?: boolean- isFetchingNewer?: boolean- onLoadNewer?: () => void- // `↓ N` pill — when there are messages further ahead than the loaded- // window, clicking jumps back to the present. Falls back to the DOM- // `belowCount` scroll-to-bottom when we're already tail-attached.- onJumpToPresent?: () => void- presentVersion?: number- // Server-derived unread count (`latestSeq - viewerLastReadSeq`). Drives- // the `↓ N` badge when `hasMoreNewer` is true — DOM math can't see rows- // that haven't been fetched yet.- unreadCount?: number-}) {- const [jumped, setJumped] = useState<string | null>(null)-- // Flattened one row per divider/message — see `message-list-items.ts`.- // Memoized so a re-render triggered by unrelated state (typing indicator- // ticks, presence updates, etc.) doesn't re-walk the full message list- // every time.- const items = useMemo(() => flattenMessageItems(messages, newDividerBefore, !!hasMore), [messages, newDividerBefore, hasMore])- const scrollTargetLoaded = !!scrollToMessageId- && messages.some((message) => message.id === scrollToMessageId)- const scrollAnchorReady = scrollToMessageId ? scrollTargetLoaded : initialScrollReady-- // ── Multi-message "share as image" (Gus uiux #128/#142) ──────────────────- // Clicking Share on a row enters select mode with that row pre-selected; more- // rows can be checked; a bottom bar shares the N selected messages as one card.- // State lives here (not the page) so both channel + DM lists get it for free,- // and this is where the flattened `items` (with `grouped`) already are.- const [selectMode, setSelectMode] = useState(false)- const [selectedIds, setSelectedIds] = useState<Set<string>>(() => new Set())- const [shareOpen, setShareOpen] = useState(false)- // Stable id-based handlers (kept out of the row memo's way, mirroring the- // action bundle's discipline). `selectedIds`/`selectMode` changing identity is- // fine — only the derived per-row boolean reaches each memoized row.- const onEnterSelectId = useCallback((id: string) => {- setSelectMode(true)- setSelectedIds(new Set([id]))- }, [])- const onToggleSelectId = useCallback((id: string) => {- setSelectedIds((prev) => {- const next = new Set(prev)- if (next.has(id)) next.delete(id)- else next.add(id)- return next- })- }, [])- const exitSelect = useCallback(() => {- setSelectMode(false)- setSelectedIds(new Set())- }, [])- // The selected messages, in stream order, with `grouped` recomputed over the- // SELECTED subset (the card collapses avatars against adjacent *selected*- // messages, not the full stream). Same-author + within the 7-min group window.- const selectedMessages = useMemo<RenderMsg[]>(() => {- if (selectedIds.size === 0) return []- const picked = items.flatMap((it) => (it.kind === "message" && selectedIds.has(it.m.id) ? [it.m] : []))- let prev: RenderMsg | null = null- return picked.map((m) => {- const grouped = !!(prev && !m.replyTo && prev.authorName === m.authorName- && prev.createdAt && m.createdAt- && new Date(m.createdAt).getTime() - new Date(prev.createdAt).getTime() < 7 * 60 * 1000)- prev = m- return { ...m, grouped }- })- }, [items, selectedIds])-- // The hero ("Beginning of the channel…" copy, or a caller-supplied- // `hero` node such as the thread-opener) renders OUTSIDE the virtualized- // range, directly above it in the same scroll container — its height must- // be measured and fed to `useScrollAnchor` so the virtualizer's- // `scrollMargin` accounts for it AND so hero-resize compensation can hold- // the viewer's visual position (see `use-scroll-anchor.ts`'s module doc- // comment — `scrollMargin` alone does not do this automatically).- const heroRef = useRef<HTMLDivElement>(null)- const [heroHeight, setHeroHeight] = useState(0)- // True once the ResizeObserver below has reported a real height at least- // once. Gates `useScrollAnchor`'s mount action — see its `heroMeasured`- // doc comment: firing mount before this is true uses `scrollMargin`'s- // default (0), which mis-targets the NEW-divider `scrollToIndex` case.- // Never reset back to `false` — once real, the hero's height stays a- // known quantity even if `hasMore`/`hero` change later and this effect- // re-observes.- const [heroMeasured, setHeroMeasured] = useState(false)- // `isLoading` drives which content renders INSIDE the tree below, rather- // than an early `return` producing a structurally different element tree- // — the same `<MessageList>` instance (and the same `scrollRef`-bearing- // div) stays mounted across the loading→loaded transition (the page-level- // fix in the 4 community pages is what stops the unwanted REMOUNT; this- // internal change is what keeps the two states on one DOM structure, per- // DESIGN.md's "Fade, don't swap" — same dimensions/position/layout flow,- // ready for a real crossfade later). Declared here (not further down,- // where it's also used) because the hero-measurement effect below needs- // it in its dependency array.- const isLoading = !!loading && messages.length === 0- useEffect(() => {- const el = heroRef.current- // The hero div doesn't exist in the DOM at all while `isLoading` is- // true (it's inside the loading/loaded ternary below) — bails without- // measuring, same as before. Critically, `isLoading` is now a dep: the- // loading→loaded transition is what makes `heroRef.current` non-null- // for the FIRST time, and without `isLoading` in the dep list this- // effect would never re-run for that transition when `hasMore`/`hero`- // happen to be unchanged across it (the common case — a plain channel- // with no thread-opener, `hasMore` staying false on first load) —- // `heroMeasured` would then never flip true, and `useScrollAnchor`'s- // mount action would wait forever. This was the actual bug behind a- // report of "channel refresh flashes at the tail then scrolls to the- // top hero, unreads never clear."- if (!el) return- const ro = new ResizeObserver((entries) => {- const h = entries[0]?.borderBoxSize?.[0]?.blockSize ?? el.offsetHeight- setHeroHeight(h)- setHeroMeasured(true)- })- ro.observe(el)- setHeroHeight(el.offsetHeight)- setHeroMeasured(true)- return () => ro.disconnect()- }, [isLoading, hasMore, hero])-- // All automatic scroll-anchor decisions (mount / self-send / peer-follow /- // hero-swap) plus the `useVirtualizer` instance live in this hook — see- // `use-scroll-anchor.ts`. Older-message prepend compensation is NOT- // decided here — it's delegated to the virtualizer's own `anchorTo: "end"`- // config.- const { scrollRef, virtualizer, belowCount, scrollToBottom, jumpTo: jumpToIndex, onImageLoad } = useScrollAnchor({- items,- newDividerBefore,- initialScrollReady: scrollAnchorReady,- hasMoreNewer,- presentVersion,- viewerUserId,- heroHeight,- heroMeasured,- })-- // Publish the scroll root to interested consumers (watermark observer).- // The callback identity may vary across renders; only re-invoke when the- // element itself changes.- useEffect(() => {- if (!onScrollRoot) return- onScrollRoot(scrollRef.current)- return () => onScrollRoot(null)- }, [onScrollRoot, scrollRef])-- // Top sentinel — when it intersects the scroll root's viewport, request the- // next older page. Mirrors the pattern in member-list.tsx: root is the- // scroll container (NOT the page viewport), rootMargin `200px` so the- // fetch kicks in before the user hits the true edge. Rendered before the- // virtualized range (same DOM position the hero occupies when `hasMore`- // is false) — this needs NO virtualizer-specific rework: an- // IntersectionObserver on a real sentinel node works identically whether- // the sibling content is virtualized or not.- // The observer MUST stay stable across fetches. A fresh IntersectionObserver- // fires its callback immediately for an already-intersecting target, so if- // this effect re-ran on every `isFetchingOlder`/`onLoadOlder` change (both- // flip on each fetch — `fetchOlder` is `useCallback([query])`, a new identity- // per TanStack state tick), each load would tear down and recreate the- // observer, which then re-fires against the still-visible sentinel and kicks- // off the next load — cascading until `hasMore` goes false (i.e. loading ALL- // history in one scroll). Instead: create the observer ONCE per scroll- // container and read the mutable guards from refs, so it only fires on a- // genuine scroll-in transition.- const topSentinelRef = useVirtualCursorSentinel({- scrollRef,- hasMore,- isFetching: isFetchingOlder,- onLoad: onLoadOlder,- edge: "start",- })-- // Bottom sentinel — symmetric to the top one. Only mounted when the loaded- // window is not tail-attached (`hasMoreNewer === true`). Appended rows from- // a newer-fetch prepend to `pages[0]` in cache order → after the sort in- // `mergeMessagesPages` they land at the natural tail of `messages`, which- // grows the container downward and leaves the viewer's scrollTop untouched.- // No compensating scroll needed. Rendered after the virtualized range.- // Same stable-observer discipline as the top sentinel above — read the- // mutable guards from a ref so a fetch-state tick never recreates the- // observer (which would re-fire against the still-visible sentinel and- // cascade through all newer pages).- const bottomSentinelRef = useVirtualCursorSentinel({- scrollRef,- hasMore: hasMoreNewer,- isFetching: isFetchingNewer,- onLoad: onLoadNewer,- edge: "end",- })-- // `jumpTo` — click a reply pill, scroll to (and briefly highlight) an- // earlier message. Replaces the old `querySelector('[data-msg-id="..."]')`- // + `scrollIntoView` DOM lookup, which only worked if the target row- // happened to already be mounted — with virtualization, `useScrollAnchor`'s- // `jumpTo` looks the target up by INDEX via `virtualizer.scrollToIndex`- // instead. If the target isn't in the currently loaded page window at all,- // this is a documented no-op — same limitation the old DOM lookup had (it- // also required the row to be loaded, just not further required it to be- // within the virtualization window).- const jumpClearTimerRef = useRef<number | null>(null)- const jumpVisibilityFrameRef = useRef<number | null>(null)- const jumpTo = useCallback((id: string, behavior: ScrollBehavior = "smooth") => {- if (jumpClearTimerRef.current !== null) clearTimeout(jumpClearTimerRef.current)- if (jumpVisibilityFrameRef.current !== null) window.cancelAnimationFrame(jumpVisibilityFrameRef.current)- setJumped(id)- jumpToIndex(id, behavior)- let attempts = 0- const armClear = () => {- jumpVisibilityFrameRef.current = null- const timeout = window.setTimeout(() => {- setJumped((v) => (v === id ? null : v))- if (jumpClearTimerRef.current === timeout) jumpClearTimerRef.current = null- }, 1600)- jumpClearTimerRef.current = timeout- }- const waitUntilVisible = () => {- const root = scrollRef.current- const row = root- ? Array.from(root.querySelectorAll<HTMLElement>("[data-msg-id]"))- .find((element) => element.dataset.msgId === id)- : undefined- if (root && row) {- const rootRect = root.getBoundingClientRect()- const rowRect = row.getBoundingClientRect()- if (rowRect.bottom > rootRect.top && rowRect.top < rootRect.bottom) {- armClear()- return- }- }- attempts += 1- if (attempts >= 120) {- armClear()- return- }- jumpVisibilityFrameRef.current = window.requestAnimationFrame(waitUntilVisible)- }- jumpVisibilityFrameRef.current = window.requestAnimationFrame(waitUntilVisible)- }, [jumpToIndex, scrollRef])- useEffect(() => () => {- if (jumpClearTimerRef.current !== null) clearTimeout(jumpClearTimerRef.current)- if (jumpVisibilityFrameRef.current !== null) window.cancelAnimationFrame(jumpVisibilityFrameRef.current)- }, [])-- const consumedScrollTargetRef = useRef<string | null>(null)- useEffect(() => {- if (!scrollToMessageId) {- consumedScrollTargetRef.current = null- return- }- if (consumedScrollTargetRef.current === scrollToMessageId) return- if (!scrollTargetLoaded || !heroMeasured) return- consumedScrollTargetRef.current = scrollToMessageId- jumpTo(scrollToMessageId, "auto")- onScrollTargetConsumed?.(scrollToMessageId)- }, [- scrollToMessageId,- scrollTargetLoaded,- heroMeasured,- jumpTo,- onScrollTargetConsumed,- ])-- // ↓ N pill precedence:- // - When there are messages the client hasn't fetched yet- // (`hasMoreNewer`), show the server-derived `unreadCount` (may be- // larger than the DOM `belowCount`) and click → `onJumpToPresent`- // resets the query to newest, cutting out multi-RTT page walks.- // - Otherwise fall back to `belowCount` and `scrollToBottom` — the- // tail-attached path unchanged from pre-A2.- const jumpMode = !!hasMoreNewer- const pillCount = jumpMode- ? ((unreadCount ?? belowCount) || 0)- : belowCount- const pillOnClick = jumpMode- ? (onJumpToPresent ?? scrollToBottom)- : scrollToBottom-- return (- <div className="relative flex min-h-0 flex-1 flex-col">- <ScrollDownButton- count={isLoading ? 0 : pillCount}- mode={jumpMode ? "jump" : "scroll"}- onClick={pillOnClick}- />- {/* Select-mode action bar — overlay (absolute, like ScrollDownButton) so- it doesn't perturb the scroll viewport's height / trigger a remeasure.- "Share N" is disabled at 0; Cancel exits. */}- {selectMode && (- <div className="absolute inset-x-0 bottom-3 z-20 flex justify-center px-4">- <div className="flex items-center gap-2 rounded-full border border-border/60 bg-card px-2 py-1.5 shadow-(--e2)">- <span className="px-2 text-sm text-muted-foreground">{selectedIds.size} selected</span>- <Button size="sm" variant="ghost" onClick={exitSelect}>- <X /> Cancel- </Button>- <Button size="sm" disabled={selectedIds.size === 0} onClick={() => setShareOpen(true)}>- <ImageIcon /> Share {selectedIds.size} as image- </Button>- </div>- </div>- )}- {shareOpen && selectedMessages.length > 0 && (- <MessageShareDialog- m={selectedMessages}- open={shareOpen}- onClose={() => { setShareOpen(false); exitSelect() }}- />- )}- <TypingIndicator names={isLoading ? [] : typingUsers ?? []} />- <div ref={scrollRef} className="flex-1 overflow-x-clip overflow-y-auto thin-scrollbar">- <div className="flex min-h-full flex-col justify-end px-4 py-8">- {isLoading ? (- <MessageListSkeletonContent variant={variant} />- ) : (- <>- {/*- When `hasMore` is true the hero's "Beginning of …" copy would- lie — there's more history above — so we swap it for the top- sentinel + inline "Loading older messages…" indicator. Once- the last page loads (`hasMore === false`) the hero returns- and reads as "you've reached the top". Rendered OUTSIDE the- virtualized range (real DOM, natural height) — its measured- height (`heroRef`'s ResizeObserver, see above) feeds the- virtualizer's `scrollMargin` and hero-swap compensation.- */}- <div ref={heroRef} className="mb-6">- {hasMore ? (- <div- ref={topSentinelRef}- className="flex h-8 items-center justify-center text-xs text-muted-foreground"- >- {isFetchingOlder ? "Loading older messages…" : ""}- </div>- ) : (- hero ?? (- <>- <div className="mb-2 grid size-12 place-items-center rounded-full bg-muted/60">- <ChannelIcon className="text-xl text-muted-foreground" />- </div>- <h2 className="text-xl font-semibold leading-tight">{channel}</h2>- <p className="mt-2 text-sm text-muted-foreground">Beginning of the channel. Say hello, share what you're working on, or drop a link.</p>- </>- )- )}- </div>-- <VirtualRows- items={items}- virtualizer={virtualizer}- itemKey={(item) => item.key}- renderItem={(item) => (- <>- {item.kind === "date-divider" && <DateDivider label={item.label} />}- {item.kind === "new-divider" && <NewDivider dateLabel={item.dateLabel} />}- {item.kind === "message" && (- // `data-msg-id` anchors the IntersectionObserver in- // `useChannelWatermark` — every currently-rendered- // row is a candidate for the read pointer (the hook- // only ever observes rows that exist in the DOM,- // which virtualization doesn't change).- <div data-msg-id={item.m.id} data-testid={tid.message(item.m.id)}>- <MessageRow- m={item.m}- viewerUserId={viewerUserId}- pinned={pinnedIds?.has(item.m.id)}- highlighted={jumped === item.m.id}- onOpenThread={onOpenThread}- onOpenProfile={onOpenProfile}- onToggleReactionId={onToggleReaction}- onReactId={onReact}- onReplyId={onReply}- onPinId={onPin}- onMarkId={onMark}- onCreateThreadId={onCreateThread}- onCopyId={onCopy}- onEditId={item.m.authorId === viewerUserId ? onEdit : undefined}- onRetryId={onRetry}- onDismissId={onDismiss}- onJumpToId={jumpTo}- onPreviewImage={onPreviewImage}- onPreviewAttachment={onPreviewAttachment}- onDownloadFile={onDownloadFile}- resolveUserName={resolveUserName}- onImageLoad={onImageLoad}- selectMode={selectMode}- selected={selectedIds.has(item.m.id)}- onToggleSelectId={onToggleSelectId}- onEnterSelectId={onEnterSelectId}- />- </div>- )}- </>- )}- />-- {hasMoreNewer && (- <div- ref={bottomSentinelRef}- className="mt-6 flex h-8 items-center justify-center text-xs text-muted-foreground"- >- {isFetchingNewer ? "Loading newer messages…" : ""}- </div>- )}- </>- )}- </div>- </div>- </div>- )-}--// Floating "↓ N" pill that appears when the user has scrolled up and there-// are still messages below the viewport. `count === 0` hides the button-// entirely (fade + slide-down, matches the shared scroll-to-bottom pill's-// visual language).-//-// `mode="jump"` — the loaded window is not tail-attached (bi-directional-// pagination has more newer rows to fetch); click jumps to present rather-// than a plain scroll. `mode="scroll"` — legacy tail-attached path.-function ScrollDownButton({- count,- mode = "scroll",- onClick,-}: {- count: number- mode?: "scroll" | "jump"- onClick: () => void-}) {- const visible = count > 0- const aria = mode === "jump"- ? `Jump to present, ${count} unread below`- : `Scroll to bottom, ${count} more below`- return (- <div- className={`pointer-events-none absolute bottom-3 left-1/2 z-10 -translate-x-1/2 transition-all duration-200 ease-out ${- visible ? "translate-y-0 opacity-100" : "translate-y-2 opacity-0"- }`}- >- <button- type="button"- onClick={onClick}- aria-label={aria}- className={`pointer-events-auto flex h-8 items-center gap-1.5 rounded-full border border-border bg-background/90 pl-2 pr-3 text-xs font-medium text-foreground shadow-(--e1) backdrop-blur-sm transition-colors hover:bg-accent ${- visible ? "" : "pointer-events-none"- }`}- >- <ArrowDown className="size-3.5 text-muted-foreground" />- <NumberTicker value={count} />- </button>- </div>- )-}--// Loading placeholder content — rendered INSIDE `<MessageList>`'s own-// scroll-container tree (see `isLoading` above), not as a separately--// returned component with its own wrapper divs. This is what makes the-// loading→loaded transition a props change on one mounted instance rather-// than a swap between two structurally different trees. `variant` swaps the-// channel-style hero (small round icon + title + caption) for the DM hero-// shape (larger avatar + bigger title + caption) — an explicit prop now-// (previously inferred from `!!hero`, which silently misfired whenever a-// caller passed a channel-context loading `hero`; `hero` and the skeleton's-// DM/channel shape are orthogonal concerns).-function MessageListSkeletonContent({ variant }: { variant: "channel" | "dm" }) {- const clusters: number[][] = [- [220, 140],- [180],- [260, 90, 200],- [120, 240],- [200],- ]- return (- <>- <div className="mb-6">- {variant === "dm" ? (- <>- <Skeleton className="mb-3 size-16 rounded-full" />- <Skeleton className="h-7 w-48 rounded" />- <Skeleton className="mt-2 h-3.5 w-72 rounded" />- </>- ) : (- <>- <Skeleton className="mb-2 size-12 rounded-full" />- <Skeleton className="h-5 w-40 rounded" />- <Skeleton className="mt-2 h-3.5 w-80 max-w-full rounded" />- </>- )}- </div>- <div className="flex flex-col gap-3">- {clusters.map((lines, i) => (- <div key={i} className="flex gap-3 pt-1.5">- <Skeleton className="size-10 shrink-0 rounded-full" />- <div className="flex min-w-0 flex-1 flex-col gap-2">- <div className="flex items-center gap-2">- <Skeleton className="h-4 w-24 rounded" />- <Skeleton className="h-3 w-14 rounded" />- </div>- {lines.map((w, j) => (- <Skeleton key={j} className="h-3.5 rounded" style={{ width: w }} />- ))}- </div>- </div>- ))}- </div>- </>- )-}diff --git a/src/web/src/components/community/attachment-card.test.ts b/src/web/src/components/community/messages/attachment-card.test.tssimilarity index 98%rename from src/web/src/components/community/attachment-card.test.tsrename to src/web/src/components/community/messages/attachment-card.test.tsindex ed41d8595..4fe4b9984 100644--- a/src/web/src/components/community/attachment-card.test.ts+++ b/src/web/src/components/community/messages/attachment-card.test.ts@@ -2,7 +2,7 @@ import React from "react"import TestRenderer, { act } from "react-test-renderer"import { describe, expect, it, vi } from "vitest"import { AttachmentCard } from "./attachment-card"-import type { FileAttachment } from "./_types"+import type { FileAttachment } from "@/lib/community/models/message"function attachment(overrides: Partial<FileAttachment> = {}): FileAttachment {return {diff --git a/src/web/src/components/community/attachment-card.tsx b/src/web/src/components/community/messages/attachment-card.tsxsimilarity index 97%rename from src/web/src/components/community/attachment-card.tsxrename to src/web/src/components/community/messages/attachment-card.tsxindex 83ff68ae2..cb1030d08 100644--- a/src/web/src/components/community/attachment-card.tsx+++ b/src/web/src/components/community/messages/attachment-card.tsx@@ -14,7 +14,7 @@ import {FileVideo,Presentation,} from "lucide-react"-import type { FileAttachment } from "./_types"+import type { FileAttachment } from "@/lib/community/models/message"import { MediaAttachmentBlock } from "./media-attachment-block"import { tid } from "@/lib/community/testids"import {diff --git a/src/web/src/components/community/attachment-layout.ts b/src/web/src/components/community/messages/attachment-layout.tssimilarity index 100%rename from src/web/src/components/community/attachment-layout.tsrename to src/web/src/components/community/messages/attachment-layout.tsdiff --git a/src/web/src/components/community/attachment-preview-sheet.test.ts b/src/web/src/components/community/messages/attachment-preview-sheet.test.tssimilarity index 99%rename from src/web/src/components/community/attachment-preview-sheet.test.tsrename to src/web/src/components/community/messages/attachment-preview-sheet.test.tsindex 0c8bf8fd6..693c3bc77 100644--- a/src/web/src/components/community/attachment-preview-sheet.test.ts+++ b/src/web/src/components/community/messages/attachment-preview-sheet.test.ts@@ -2,7 +2,7 @@ import React from "react"import TestRenderer, { act } from "react-test-renderer"import { afterEach, describe, expect, it, vi } from "vitest"import { AttachmentPreviewSheet, readAttachmentText } from "./attachment-preview-sheet"-import type { FileAttachment } from "./_types"+import type { FileAttachment } from "@/lib/community/models/message"vi.mock("@/components/ui/sheet", () => ({Sheet: ({ children }: { children: React.ReactNode }) => React.createElement("div", null, children),diff --git a/src/web/src/components/community/attachment-preview-sheet.tsx b/src/web/src/components/community/messages/attachment-preview-sheet.tsxsimilarity index 99%rename from src/web/src/components/community/attachment-preview-sheet.tsxrename to src/web/src/components/community/messages/attachment-preview-sheet.tsxindex 232daedb0..33248fd80 100644--- a/src/web/src/components/community/attachment-preview-sheet.tsx+++ b/src/web/src/components/community/messages/attachment-preview-sheet.tsx@@ -15,7 +15,7 @@ import { SheetResizeHandle, useSheetResize } from "@/components/ui/sheet-resize-import { cn } from "@/lib/utils"import { MessageBody } from "./message-body"import { CodePreview } from "./code-preview"-import type { FileAttachment } from "./_types"+import type { FileAttachment } from "@/lib/community/models/message"import { tid } from "@/lib/community/testids"import {formatAttachmentSize,diff --git a/src/web/src/components/community/channel-ref-pill.test.ts b/src/web/src/components/community/messages/channel-ref-pill.test.tssimilarity index 100%rename from src/web/src/components/community/channel-ref-pill.test.tsrename to src/web/src/components/community/messages/channel-ref-pill.test.tsdiff --git a/src/web/src/components/community/channel-ref-pill.tsx b/src/web/src/components/community/messages/channel-ref-pill.tsxsimilarity index 100%rename from src/web/src/components/community/channel-ref-pill.tsxrename to src/web/src/components/community/messages/channel-ref-pill.tsxdiff --git a/src/web/src/components/community/code-preview.test.ts b/src/web/src/components/community/messages/code-preview.test.tssimilarity index 100%rename from src/web/src/components/community/code-preview.test.tsrename to src/web/src/components/community/messages/code-preview.test.tsdiff --git a/src/web/src/components/community/code-preview.tsx b/src/web/src/components/community/messages/code-preview.tsxsimilarity index 100%rename from src/web/src/components/community/code-preview.tsxrename to src/web/src/components/community/messages/code-preview.tsxdiff --git a/src/web/src/components/community/messages/composer-facade.contract.test.ts b/src/web/src/components/community/messages/composer-facade.contract.test.tsnew file mode 100644index 000000000..25d634ffa--- /dev/null+++ b/src/web/src/components/community/messages/composer-facade.contract.test.ts@@ -0,0 +1,99 @@+import { existsSync, readFileSync } from "node:fs"+import { dirname, resolve } from "node:path"+import { fileURLToPath } from "node:url"+import type { ComponentProps, ComponentRef } from "react"+import { describe, expect, expectTypeOf, it } from "vitest"+import { Composer } from "./composer"+import type { ComposerHandle, ComposerProps } from "./composer"++const messagesDirectory = dirname(fileURLToPath(import.meta.url))+const webRoot = resolve(messagesDirectory, "../../../..")+const readWeb = (path: string) =>+ readFileSync(resolve(webRoot, path), "utf8")++describe("Composer public facade", () => {+ it("keeps the exact props and five-method forwarded handle", () => {+ expectTypeOf<ComponentProps<typeof Composer>>().toEqualTypeOf<ComposerProps>()+ expectTypeOf<ComponentRef<typeof Composer>>().toEqualTypeOf<ComposerHandle>()+ expectTypeOf<keyof ComposerHandle>().toEqualTypeOf<+ | "focusEditor"+ | "submitNow"+ | "resetAfterSubmit"+ | "isEmpty"+ | "openFilePicker"+ >()+ })++ it("retains the original-path eight-export facade", () => {+ const source = readWeb("src/components/community/messages/composer.tsx")+ const namesFromBlocks = (pattern: RegExp) =>+ [...source.matchAll(pattern)].flatMap((match) =>+ match[1]+ .split(",")+ .map((part) => part.trim().split(/\s+as\s+/)[1] ?? part.trim())+ .filter(Boolean),+ )+ const typeExports = namesFromBlocks(/export\s+type\s*\{([^}]*)\}/gs)+ const valueExports = [+ ...namesFromBlocks(/export\s*\{([^}]*)\}/gs),+ ...[...source.matchAll(/export\s+(?:const|function|class)\s+(\w+)/g)].map(+ (match) => match[1],+ ),+ ]+ expect(new Set(typeExports)).toEqual(+ new Set(["ComposerHandle", "ComposerProps", "SendAttachment"]),+ )+ expect(new Set(valueExports)).toEqual(+ new Set([+ "Composer",+ "ComposerSkeleton",+ "pendingFilesToSendAttachments",+ "clipboardFiles",+ "popoverStyle",+ ]),+ )+ expect(source).not.toMatch(/export\s+(?:default|\*)/)+ expect(source).toContain("useComposerController(props, ref)")+ expect(source).toContain("<ComposerView {...viewProps} />")+ expect(source).not.toContain("useEditor(")+ expect(source).not.toContain("useFileAttachments(")+ })++ it("keeps every direct importer on the facade and out of internals", () => {+ const importers = [+ "src/app/c/me/[dmId]/page.tsx",+ "src/components/community/channels/thread-channel-surface.tsx",+ "src/components/community/channels/channel-route.tsx",+ "src/components/community/channels/text-channel-surface.tsx",+ "src/components/community/messages/create-forum-thread.tsx",+ "src/components/community/messages/message-channel-controller.tsx",+ "src/components/community/channels/thread-channel-surface.test.ts",+ ]+ for (const importer of importers) {+ const source = readWeb(importer)+ expect(source).toMatch(/(?:from|import\()\s*["'][^"']*\/composer["']/)+ expect(source).not.toMatch(+ /composer-(?:types|file-utils|view|suggestion-popups)|use-composer-(?:controller|suggestions)/,+ )+ }+ })++ it("keeps every production owner below 400 lines without a barrel", () => {+ const owners = [+ "composer.tsx",+ "composer-types.ts",+ "composer-file-utils.ts",+ "use-composer-controller.ts",+ "use-composer-suggestions.ts",+ "composer-suggestion-popups.tsx",+ "composer-view.tsx",+ ]+ for (const owner of owners) {+ const source = readWeb(`src/components/community/messages/${owner}`)+ expect(source.split("\n").length, owner).toBeLessThan(400)+ }+ expect(+ existsSync(resolve(webRoot, "src/components/community/messages/index.ts")),+ ).toBe(false)+ })+})diff --git a/src/web/src/components/community/messages/composer-file-utils.ts b/src/web/src/components/community/messages/composer-file-utils.tsnew file mode 100644index 000000000..a07fc1cde--- /dev/null+++ b/src/web/src/components/community/messages/composer-file-utils.ts@@ -0,0 +1,28 @@+import type { PendingFile } from "@/hooks/use-file-attachments"+import type { SendAttachment } from "@/lib/community/models/message"++export function pendingFilesToSendAttachments(+ pendingFiles: PendingFile[],+): SendAttachment[] | undefined {+ if (pendingFiles.length === 0) return undefined+ return pendingFiles.map((pendingFile) => ({+ file: pendingFile.file,+ thumbnailBlob: pendingFile.thumbnailBlob ?? undefined,+ previewObjectUrl: pendingFile.thumbnailUrl ?? undefined,+ width: pendingFile.width,+ height: pendingFile.height,+ }))+}++export function clipboardFiles(+ items: DataTransferItemList | undefined,+): File[] {+ if (!items) return []+ const files: File[] = []+ for (let index = 0; index < items.length; index++) {+ if (items[index].kind !== "file") continue+ const file = items[index].getAsFile()+ if (file) files.push(file)+ }+ return files+}diff --git a/src/web/src/components/community/messages/composer-suggestion-popups.test.ts b/src/web/src/components/community/messages/composer-suggestion-popups.test.tsnew file mode 100644index 000000000..ac5534d8d--- /dev/null+++ b/src/web/src/components/community/messages/composer-suggestion-popups.test.ts@@ -0,0 +1,250 @@+import { createElement } from "react"+import TestRenderer, { act } from "react-test-renderer"+import { beforeEach, describe, expect, it, vi } from "vitest"++const mocks = vi.hoisted(() => ({+ createPortal: vi.fn(),+ nextScrollTop: vi.fn(),+}))++vi.mock("react-dom", () => ({+ createPortal: (...args: unknown[]) => mocks.createPortal(...args),+}))+vi.mock("@/lib/community/popup-scroll", () => ({+ nextListScrollTop: (...args: unknown[]) => mocks.nextScrollTop(...args),+}))+vi.mock("../avatar", () => ({+ Avatar: (props: Record<string, unknown>) => createElement("avatar", props),+}))+vi.mock("../channels/channel-icon", () => ({+ ChannelIcon: (props: Record<string, unknown>) =>+ createElement("channel-icon", props),+}))++import {+ ChannelRefList,+ CommunityMentionList,+ popoverStyle,+} from "./composer-suggestion-popups"+import {+ EMPTY_CHANNEL_REF_STATE,+ type ChannelRefPopupState,+} from "@/lib/community/channel-ref-extension"+import {+ EMPTY_MENTION_STATE,+ type MentionPopupState,+} from "@/lib/community/mention-extension"++function rect(top: number, left = 40): DOMRect {+ return {+ top,+ bottom: top + 16,+ left,+ right: left + 4,+ width: 4,+ height: 16,+ x: left,+ y: top,+ toJSON() {},+ }+}++describe("Composer suggestion popups", () => {+ let listNode: {+ scrollTop: number+ clientHeight: number+ querySelector: ReturnType<typeof vi.fn>+ }++ beforeEach(() => {+ const body = { nodeName: "BODY" }+ vi.stubGlobal("document", { body })+ mocks.createPortal.mockReset()+ mocks.createPortal.mockImplementation((node) => node)+ mocks.nextScrollTop.mockReset()+ mocks.nextScrollTop.mockReturnValue(77)+ listNode = {+ scrollTop: 10,+ clientHeight: 100,+ querySelector: vi.fn(() => ({ offsetTop: 150, offsetHeight: 20 })),+ }+ })++ it("self-nulls while closed and preserves viewport placement", async () => {+ let mention!: TestRenderer.ReactTestRenderer+ let channel!: TestRenderer.ReactTestRenderer+ await act(async () => {+ mention = TestRenderer.create(+ createElement(CommunityMentionList, { state: EMPTY_MENTION_STATE }),+ )+ channel = TestRenderer.create(+ createElement(ChannelRefList, { state: EMPTY_CHANNEL_REF_STATE }),+ )+ })+ expect(mention.toJSON()).toBeNull()+ expect(channel.toJSON()).toBeNull()+ expect(mocks.createPortal).not.toHaveBeenCalled()++ await act(async () => {+ mention.update(+ createElement(CommunityMentionList, {+ state: {+ items: [{ kind: "everyone", id: "everyone", label: "everyone" }],+ selectedIndex: 0,+ command: vi.fn(),+ rect: rect(500),+ },+ }),+ )+ })+ expect(mention.toJSON()).not.toBeNull()+ expect(mocks.createPortal).toHaveBeenLastCalledWith(+ expect.anything(),+ document.body,+ )++ expect(popoverStyle(rect(500), 1024, 768)).toEqual({+ top: 496,+ left: 40,+ transform: "translateY(-100%)",+ })+ expect(popoverStyle(rect(100, 1000), 1024, 768)).toEqual({+ top: 120,+ left: 760,+ })+ })++ it("renders virtual/member rows in order and selects on mousedown", async () => {+ const command = vi.fn()+ const state: MentionPopupState = {+ items: [+ { kind: "everyone", id: "everyone", label: "everyone" },+ {+ kind: "member",+ id: "member-1",+ userId: "user-1",+ label: "Ada#0001",+ name: "Ada",+ discriminator: "0001",+ avatar: "A",+ status: "online",+ },+ ],+ selectedIndex: 1,+ command,+ rect: rect(500),+ }+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(+ createElement(CommunityMentionList, { state }),+ {+ createNodeMock: (element) =>+ element.props.className?.includes("max-h-60") ? listNode : {},+ },+ )+ })+ expect(mocks.createPortal).toHaveBeenCalledWith(+ expect.anything(),+ document.body,+ )+ expect(mocks.nextScrollTop).toHaveBeenCalledWith(10, 100, 150, 20)+ expect(listNode.scrollTop).toBe(77)+ const json = JSON.stringify(renderer.toJSON())+ expect(json.indexOf("@everyone")).toBeLessThan(json.indexOf("Members"))+ expect(json).toContain("Ada")+ expect(+ renderer.root.find(+ (node) =>+ node.type === "span" &&+ node.props.className?.includes("tracking-wide"),+ ).children,+ ).toEqual(["#", "0001"])+ expect(json).toContain("Notify everyone")++ const selected = renderer.root.find(+ (node) => node.type === "button" && node.props["aria-selected"] === true,+ )+ const preventDefault = vi.fn()+ await act(async () => selected.props.onMouseDown({ preventDefault }))+ expect(preventDefault).toHaveBeenCalledOnce()+ expect(command).toHaveBeenCalledWith({ id: "member-1", label: "Ada#0001" })+ })++ it("adds server prefixes only for cross-server channel results", async () => {+ const command = vi.fn()+ const state: ChannelRefPopupState = {+ items: [+ {+ id: "channel-1",+ name: "general",+ serverId: "server-1",+ serverName: "One",+ },+ {+ id: "channel-2",+ name: "random",+ serverId: "server-2",+ serverName: "Two",+ },+ ],+ selectedIndex: 0,+ command,+ rect: rect(500),+ }+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(createElement(ChannelRefList, { state }), {+ createNodeMock: (element) =>+ element.props.className?.includes("max-h-60") ? listNode : {},+ })+ })+ const prefixes = renderer.root+ .findAll(+ (node) =>+ node.type === "span" &&+ node.props.className === "text-muted-foreground",+ )+ .map((node) => node.children)+ expect(prefixes).toEqual([+ ["One", " / "],+ ["Two", " / "],+ ])++ const first = renderer.root.findAllByType("button")[0]+ const preventDefault = vi.fn()+ await act(async () => first.props.onMouseDown({ preventDefault }))+ expect(preventDefault).toHaveBeenCalledOnce()+ expect(command).toHaveBeenCalledWith({+ id: "channel-1",+ label: "general",+ serverId: "server-1",+ serverName: "One",+ })++ await act(async () => {+ renderer.update(+ createElement(ChannelRefList, {+ state: {+ ...state,+ items: [+ state.items[0],+ {+ ...state.items[1],+ serverId: "server-1",+ serverName: "One",+ },+ ],+ },+ }),+ )+ })+ expect(+ renderer.root.findAll(+ (node) =>+ node.type === "span" &&+ node.props.className === "text-muted-foreground",+ ),+ ).toHaveLength(0)+ })+})diff --git a/src/web/src/components/community/messages/composer-suggestion-popups.tsx b/src/web/src/components/community/messages/composer-suggestion-popups.tsxnew file mode 100644index 000000000..93c53a9fd--- /dev/null+++ b/src/web/src/components/community/messages/composer-suggestion-popups.tsx@@ -0,0 +1,239 @@+import { useEffect, useRef, type CSSProperties } from "react"+import { createPortal } from "react-dom"+import { Users } from "lucide-react"+import { Avatar } from "../avatar"+import { ChannelIcon } from "../channels/channel-icon"+import { nextListScrollTop } from "@/lib/community/popup-scroll"+import { tid } from "@/lib/community/testids"+import {+ toChannelRefCommandProps,+ type ChannelRefCandidate,+ type ChannelRefPopupState,+} from "@/lib/community/channel-ref-extension"+import type {+ MentionItem,+ MentionPopupState,+} from "@/lib/community/mention-extension"++const POPUP_WIDTH = 256+const POPUP_MAX_HEIGHT = 240+const VIEWPORT_MARGIN = 8++export function popoverStyle(+ rect: DOMRect,+ viewportWidth: number,+ viewportHeight: number,+): CSSProperties {+ const maxLeft = Math.max(+ VIEWPORT_MARGIN,+ viewportWidth - POPUP_WIDTH - VIEWPORT_MARGIN,+ )+ const left = Math.min(rect.left, maxLeft)+ const flipBelow =+ rect.top < POPUP_MAX_HEIGHT + VIEWPORT_MARGIN &&+ rect.bottom + POPUP_MAX_HEIGHT + VIEWPORT_MARGIN <= viewportHeight+ return flipBelow+ ? { top: rect.bottom + 4, left }+ : { top: rect.top - 4, left, transform: "translateY(-100%)" }+}++function viewportSize(): { w: number; h: number } {+ if (typeof window === "undefined") {+ return { w: POPUP_WIDTH, h: POPUP_MAX_HEIGHT }+ }+ return { w: window.innerWidth, h: window.innerHeight }+}++function scrollSelectedRowIntoView(list: HTMLDivElement | null): void {+ if (!list) return+ const row = list.querySelector<HTMLElement>('[aria-selected="true"]')+ if (!row) return+ list.scrollTop = nextListScrollTop(+ list.scrollTop,+ list.clientHeight,+ row.offsetTop,+ row.offsetHeight,+ )+}++export function CommunityMentionList({+ state,+}: {+ state: MentionPopupState+}) {+ const listRef = useRef<HTMLDivElement>(null)+ const { items, selectedIndex, command, rect } = state+ useEffect(() => {+ scrollSelectedRowIntoView(listRef.current)+ }, [selectedIndex])+ if (!rect || items.length === 0 || !command) return null++ const firstMemberIndex = items.findIndex((item) => item.kind === "member")+ const hasVirtual = items.some((item) => item.kind !== "member")+ const showMembersHeader = hasVirtual && firstMemberIndex > 0+ const viewport = viewportSize()++ return createPortal(+ <div+ className="fixed z-100 w-64 rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-(--e2)"+ style={popoverStyle(rect, viewport.w, viewport.h)}+ >+ <div+ ref={listRef}+ className="relative max-h-60 overflow-x-hidden overflow-y-auto thin-scrollbar"+ >+ {items.map((item, index) => (+ <MentionRow+ key={`${item.kind}:${item.id}`}+ item={item}+ selected={index === selectedIndex}+ showMembersHeader={+ showMembersHeader && index === firstMemberIndex+ }+ onSelect={() => command({ id: item.id, label: item.label })}+ />+ ))}+ </div>+ </div>,+ document.body,+ )+}++export function ChannelRefList({ state }: { state: ChannelRefPopupState }) {+ const listRef = useRef<HTMLDivElement>(null)+ const { items, selectedIndex, command, rect } = state+ useEffect(() => {+ scrollSelectedRowIntoView(listRef.current)+ }, [selectedIndex])+ if (!rect || items.length === 0 || !command) return null++ const spansMultipleServers = items.some(+ (item) => item.serverId !== items[0]?.serverId,+ )+ const viewport = viewportSize()+ return createPortal(+ <div+ className="fixed z-100 w-64 rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-(--e2)"+ style={popoverStyle(rect, viewport.w, viewport.h)}+ >+ <div+ ref={listRef}+ className="relative max-h-60 overflow-x-hidden overflow-y-auto thin-scrollbar"+ >+ {items.map((item, index) => (+ <ChannelRefRow+ key={item.id}+ item={item}+ selected={index === selectedIndex}+ showServerPrefix={spansMultipleServers}+ onSelect={() => command(toChannelRefCommandProps(item))}+ />+ ))}+ </div>+ </div>,+ document.body,+ )+}++function ChannelRefRow({+ item,+ selected,+ showServerPrefix,+ onSelect,+}: {+ item: ChannelRefCandidate+ selected: boolean+ showServerPrefix: boolean+ onSelect: () => void+}) {+ return (+ <button+ type="button"+ role="option"+ aria-selected={selected}+ className={[+ "flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm transition-colors",+ selected ? "bg-accent" : "hover:bg-accent/50",+ ].join(" ")}+ onMouseDown={(event) => {+ event.preventDefault()+ onSelect()+ }}+ >+ <ChannelIcon className="size-3.5 text-muted-foreground" />+ <span className="font-medium">+ {showServerPrefix && (+ <span className="text-muted-foreground">{item.serverName} / </span>+ )}+ {item.name}+ </span>+ </button>+ )+}++function MentionRow({+ item,+ selected,+ showMembersHeader,+ onSelect,+}: {+ item: MentionItem+ selected: boolean+ showMembersHeader: boolean+ onSelect: () => void+}) {+ return (+ <>+ {showMembersHeader && (+ <div className="-mx-1 mt-1 border-t border-border/60 px-2 pt-2 pb-1 text-xs font-semibold text-muted-foreground">+ Members+ </div>+ )}+ <button+ type="button"+ role="option"+ data-testid={tid.mentionOption(item.id)}+ aria-selected={selected}+ className={[+ "flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm transition-colors",+ selected ? "bg-accent" : "hover:bg-accent/50",+ ].join(" ")}+ onMouseDown={(event) => {+ event.preventDefault()+ onSelect()+ }}+ >+ {item.kind === "member" ? (+ <Avatar+ label={item.avatar}+ seed={item.userId}+ size={24}+ presence={item.status}+ ringColor="var(--popover)"+ />+ ) : (+ <span className="grid size-6 place-items-center rounded-full bg-primary/15 text-primary">+ <Users className="size-3.5" />+ </span>+ )}+ <span className="font-medium">+ {item.kind === "member" ? (+ <>+ {item.name}+ <span className="ml-1 text-xs font-normal tracking-wide text-muted-foreground">+ #{item.discriminator}+ </span>+ </>+ ) : (+ `@${item.label}`+ )}+ </span>+ {item.kind !== "member" && (+ <span className="ml-auto text-xs text-muted-foreground">+ Notify everyone+ </span>+ )}+ </button>+ </>+ )+}diff --git a/src/web/src/components/community/messages/composer-types.ts b/src/web/src/components/community/messages/composer-types.tsnew file mode 100644index 000000000..f49ef60ef--- /dev/null+++ b/src/web/src/components/community/messages/composer-types.ts@@ -0,0 +1,59 @@+import type { MentionType } from "@alook/shared"+import type { ChannelRefCandidate } from "@/lib/community/channel-ref-extension"+import type { MentionContext } from "@/lib/community/mention-extension"+import type { SendAttachment } from "@/lib/community/models/message"+import type { Member } from "@/lib/community/models/people"++type ComposerMode = "chat" | "forumThreadBody"++export type ComposerHandle = {+ focusEditor: () => void+ submitNow: () => void+ resetAfterSubmit: () => void+ isEmpty: () => boolean+ openFilePicker: () => void+}++type ComposerBaseProps = {+ channel: string+ context: MentionContext+ members: Member[]+ onSearchMembers?: (query: string) => void+ channelRefCandidates?: ChannelRefCandidate[]+ onChannelRefIntent?: () => void+ onTyping?: () => void+ replyingTo?: string+ onCancelReply?: () => void+ autoFocus?: boolean+ mode?: ComposerMode+ placeholder?: string+ hideEmoji?: boolean+ hideAttach?: boolean+ onDirty?: (hasContent: boolean) => void+ draftKey?: string+}++type ComposerAcceptedSend = {+ sendContract: "accepted"+ mode?: "chat"+ onAcceptSend: (+ markdown: string,+ attachments?: SendAttachment[],+ mentionType?: MentionType,+ ) => boolean+ onDeferredSubmit?: never+}++type ComposerDeferredSend = {+ sendContract: "deferred"+ mode: "forumThreadBody"+ onDeferredSubmit: (+ markdown: string,+ attachments?: SendAttachment[],+ mentionType?: MentionType,+ ) => void | Promise<void>+ onAcceptSend?: never+}++export type ComposerProps = ComposerBaseProps &+ (ComposerAcceptedSend | ComposerDeferredSend)diff --git a/src/web/src/components/community/messages/composer-view.test.ts b/src/web/src/components/community/messages/composer-view.test.tsnew file mode 100644index 000000000..22e24a7a5--- /dev/null+++ b/src/web/src/components/community/messages/composer-view.test.ts@@ -0,0 +1,336 @@+import { createElement } from "react"+import TestRenderer, { act } from "react-test-renderer"+import { describe, expect, it, vi } from "vitest"++vi.mock("@tiptap/react", () => ({+ EditorContent: (props: Record<string, unknown>) =>+ createElement("editor-content", props),+}))+vi.mock("lucide-react", () => ({+ FileIcon: (props: Record<string, unknown>) => createElement("file-icon", props),+ ImageIcon: (props: Record<string, unknown>) =>+ createElement("image-icon", props),+ PlusCircle: (props: Record<string, unknown>) =>+ createElement("plus-icon", props),+ Smile: (props: Record<string, unknown>) => createElement("smile-icon", props),+ Upload: (props: Record<string, unknown>) =>+ createElement("upload-icon", props),+ X: (props: Record<string, unknown>) => createElement("x-icon", props),+}))+vi.mock("@/components/ui/dropdown-menu", () => ({+ DropdownMenu: (props: Record<string, unknown>) =>+ createElement("dropdown-menu", props),+ DropdownMenuTrigger: (props: Record<string, unknown>) =>+ createElement(+ "dropdown-trigger",+ props,+ props.render as never,+ props.children as never,+ ),+ DropdownMenuContent: (props: Record<string, unknown>) =>+ createElement("dropdown-content", props),+ DropdownMenuItem: (props: Record<string, unknown>) =>+ createElement("dropdown-item", props),+}))+vi.mock("@/components/ui/skeleton", () => ({+ Skeleton: (props: Record<string, unknown>) => createElement("skeleton", props),+}))+vi.mock("./emoji-picker", () => ({+ EmojiPickerPopover: (props: Record<string, unknown>) =>+ createElement("emoji-picker", props),+}))+vi.mock("./composer-suggestion-popups", () => ({+ CommunityMentionList: (props: Record<string, unknown>) =>+ createElement("mention-popup", props),+ ChannelRefList: (props: Record<string, unknown>) =>+ createElement("channel-popup", props),+}))++import {+ ComposerSkeleton,+ ComposerView,+ type ComposerViewProps,+} from "./composer-view"+import type { PendingFile } from "@/hooks/use-file-attachments"+import {+ EMPTY_CHANNEL_REF_STATE,+} from "@/lib/community/channel-ref-extension"+import { EMPTY_MENTION_STATE } from "@/lib/community/mention-extension"+import { tid } from "@/lib/community/testids"++function baseProps(+ overrides: Partial<ComposerViewProps> = {},+): ComposerViewProps {+ return {+ isForumThreadBody: false,+ dragging: false,+ onDragEnter: vi.fn(),+ onDragLeave: vi.fn(),+ onDragOver: vi.fn(),+ onDrop: vi.fn(),+ mentionPopup: EMPTY_MENTION_STATE,+ channelRefPopup: EMPTY_CHANNEL_REF_STATE,+ pendingFiles: [],+ removePendingFile: vi.fn(),+ fileInputRef: { current: null },+ onFileSelect: vi.fn(),+ editor: null,+ hideAttach: false,+ hideEmoji: false,+ onAttachOpenChange: vi.fn(),+ onUploadFile: vi.fn(),+ onEmojiPick: vi.fn(),+ ...overrides,+ }+}++describe("ComposerView", () => {+ it("keeps popup, reply, icon-only pending, drag, editor, and control order", async () => {+ const removePendingFile = vi.fn()+ const onCancelReply = vi.fn()+ const onFileSelect = vi.fn()+ const onDragEnter = vi.fn()+ const onDragLeave = vi.fn()+ const onDragOver = vi.fn()+ const onDrop = vi.fn()+ const mentionPopup = {+ ...EMPTY_MENTION_STATE,+ items: [{ kind: "everyone" as const, id: "everyone", label: "everyone" }],+ }+ const channelRefPopup = {+ ...EMPTY_CHANNEL_REF_STATE,+ items: [+ {+ id: "channel-1",+ name: "general",+ serverId: "server-1",+ serverName: "One",+ },+ ],+ }+ const image = new File(["image"], "photo.png", { type: "image/png" })+ const textFile = new File(["text"], "notes.txt", { type: "text/plain" })+ const pendingFiles = [+ { file: image, thumbnailUrl: "blob:image", width: 640, height: 480 },+ { file: textFile, thumbnailUrl: null, thumbnailBlob: null },+ ] as PendingFile[]+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(+ createElement(+ ComposerView,+ baseProps({+ replyingTo: "Ada",+ onCancelReply,+ pendingFiles,+ removePendingFile,+ dragging: true,+ onFileSelect,+ onDragEnter,+ onDragLeave,+ onDragOver,+ onDrop,+ mentionPopup,+ channelRefPopup,+ }),+ ),+ )+ })++ const root = renderer.toJSON() as TestRenderer.ReactTestRendererJSON+ const topTypes = (root.children ?? [])+ .filter((child): child is TestRenderer.ReactTestRendererJSON =>+ typeof child === "object" && child !== null,+ )+ .map((child) => child.type)+ expect(topTypes.slice(0, 2)).toEqual(["mention-popup", "channel-popup"])+ expect(renderer.root.findByType("mention-popup").props.state).toBe(+ mentionPopup,+ )+ expect(renderer.root.findByType("channel-popup").props.state).toBe(+ channelRefPopup,+ )+ const renderedText = renderer.root+ .findAll(() => true)+ .flatMap((node) => node.children)+ .filter((child): child is string => typeof child === "string")+ .join(" ")+ expect(renderedText).toContain("Replying to")+ expect(renderedText).toContain("Ada")+ expect(renderedText).toContain("photo.png")+ expect(renderedText).toContain("notes.txt")+ expect(renderedText).toContain("Drop files here")+ expect(renderer.root.findAllByType("image-icon")).toHaveLength(1)+ expect(renderer.root.findAllByType("file-icon")).toHaveLength(1)+ expect(renderer.root.findAllByType("img")).toHaveLength(0)++ const hostRoot = renderer.root.findAllByType("div")[0]+ const dragEvent = { type: "drag" }+ await act(async () => {+ hostRoot.props.onDragEnter(dragEvent)+ hostRoot.props.onDragLeave(dragEvent)+ hostRoot.props.onDragOver(dragEvent)+ hostRoot.props.onDrop(dragEvent)+ })+ expect(onDragEnter).toHaveBeenCalledWith(dragEvent)+ expect(onDragLeave).toHaveBeenCalledWith(dragEvent)+ expect(onDragOver).toHaveBeenCalledWith(dragEvent)+ expect(onDrop).toHaveBeenCalledWith(dragEvent)++ await act(async () =>+ renderer.root+ .find(+ (node) =>+ node.type === "button" &&+ node.props["aria-label"] === "Cancel reply",+ )+ .props.onClick(),+ )+ expect(onCancelReply).toHaveBeenCalledOnce()++ const removeButtons = renderer.root.findAll(+ (node) =>+ node.type === "button" && node.props["aria-label"] === "Remove file",+ )+ await act(async () => removeButtons[1].props.onClick())+ expect(removePendingFile).toHaveBeenCalledWith(1)+ const input = renderer.root.findByType("input")+ expect(input.props).toMatchObject({+ type: "file",+ multiple: true,+ className: "hidden",+ })+ const changeEvent = { target: { files: [] } }+ await act(async () => input.props.onChange(changeEvent))+ expect(onFileSelect).toHaveBeenCalledWith(changeEvent)+ expect(+ renderer.root.find(+ (node) => node.props["data-testid"] === tid.composerInput,+ ).props.className,+ ).toContain("px-12")+ expect(+ renderer.root.find(+ (node) => node.props["data-testid"] === tid.composerAttach,+ ).props["aria-label"],+ ).toBe("Add")+ for (const label of ["Cancel reply", "Remove file", "Add", "Emoji picker"]) {+ expect(+ renderer.root.findAll(+ (node) => node.type === "button" && node.props["aria-label"] === label,+ ).length,+ label,+ ).toBeGreaterThan(0)+ }+ expect(+ renderer.root.find(+ (node) =>+ node.type === "div" &&+ node.props.className?.includes("focus-within:ring-2"),+ ).props.className,+ ).toContain("rounded-b-xl")+ expect(+ renderer.root.find(+ (node) =>+ node.type === "div" && node.props.className?.includes("flex-wrap"),+ ).props.className,+ ).not.toContain("rounded-t-xl")+ expect(renderer.root.findAllByType("dropdown-menu")).toHaveLength(1)+ expect(renderer.root.findAllByType("emoji-picker")).toHaveLength(1)++ await act(async () => {+ renderer.update(+ createElement(+ ComposerView,+ baseProps({ pendingFiles, removePendingFile }),+ ),+ )+ })+ expect(+ renderer.root.find(+ (node) =>+ node.type === "div" && node.props.className?.includes("flex-wrap"),+ ).props.className,+ ).toContain("rounded-t-xl border-t")+ })++ it("forwards only event wiring and honors forum/hide flags", async () => {+ const onAttachOpenChange = vi.fn()+ const onUploadFile = vi.fn()+ const onEmojiPick = vi.fn()+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(+ createElement(+ ComposerView,+ baseProps({ onAttachOpenChange, onUploadFile, onEmojiPick }),+ ),+ )+ })+ await act(async () =>+ renderer.root.findByType("dropdown-menu").props.onOpenChange(false),+ )+ await act(async () =>+ renderer.root.findByType("dropdown-item").props.onClick(),+ )+ await act(async () =>+ renderer.root.findByType("emoji-picker").props.onPick("🌱"),+ )+ expect(onAttachOpenChange).toHaveBeenCalledWith(false)+ expect(onUploadFile).toHaveBeenCalledOnce()+ expect(onEmojiPick).toHaveBeenCalledWith("🌱")+ expect(+ renderer.root.find(+ (node) =>+ node.type === "div" &&+ node.props.className?.includes("focus-within:ring-2"),+ ).props.className,+ ).toContain("rounded-xl")++ await act(async () => {+ renderer.update(+ createElement(+ ComposerView,+ baseProps({+ isForumThreadBody: true,+ hideAttach: true,+ hideEmoji: true,+ }),+ ),+ )+ })+ expect(renderer.root.findAllByType("dropdown-menu")).toHaveLength(0)+ expect(renderer.root.findAllByType("emoji-picker")).toHaveLength(0)+ expect(renderer.root.findAllByType("div")[0].props.className).toBe(+ "relative",+ )+ expect(+ renderer.root.find(+ (node) => node.props["data-testid"] === tid.composerInput,+ ).props.className,+ ).toContain("px-2")+ expect(renderer.root.findByType("editor-content").props.className).toContain(+ "max-h-60",+ )+ })++ it("keeps the exact ComposerSkeleton footprint", async () => {+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(createElement(ComposerSkeleton))+ })+ const skeletons = renderer.root.findAllByType("skeleton")+ expect(skeletons).toHaveLength(3)+ expect(skeletons.map((node) => node.props.className)).toEqual([+ "h-5 w-2/5 rounded",+ "absolute left-2 bottom-2 size-8 rounded-full",+ "absolute right-2 bottom-2 size-8 rounded-full",+ ])+ expect(renderer.toJSON()).toMatchObject({+ type: "div",+ props: { className: "relative px-3 pb-3 pt-0" },+ })+ expect(JSON.stringify(renderer.toJSON())).toContain(+ "relative rounded-xl bg-muted px-12 py-3 shadow-(--e1) ring-1 ring-border/40",+ )+ })+})diff --git a/src/web/src/components/community/messages/composer-view.tsx b/src/web/src/components/community/messages/composer-view.tsxnew file mode 100644index 000000000..7b0d8e25d--- /dev/null+++ b/src/web/src/components/community/messages/composer-view.tsx@@ -0,0 +1,208 @@+import type {+ ChangeEventHandler,+ DragEventHandler,+ RefObject,+} from "react"+import { EditorContent, type Editor } from "@tiptap/react"+import { FileIcon, ImageIcon, PlusCircle, Smile, Upload, X } from "lucide-react"+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu"+import { Skeleton } from "@/components/ui/skeleton"+import type { PendingFile } from "@/hooks/use-file-attachments"+import type { ChannelRefPopupState } from "@/lib/community/channel-ref-extension"+import type { MentionPopupState } from "@/lib/community/mention-extension"+import { tid } from "@/lib/community/testids"+import { EmojiPickerPopover } from "./emoji-picker"+import {+ ChannelRefList,+ CommunityMentionList,+} from "./composer-suggestion-popups"++export type ComposerViewProps = {+ isForumThreadBody: boolean+ dragging: boolean+ onDragEnter: DragEventHandler<HTMLDivElement>+ onDragLeave: DragEventHandler<HTMLDivElement>+ onDragOver: DragEventHandler<HTMLDivElement>+ onDrop: DragEventHandler<HTMLDivElement>+ mentionPopup: MentionPopupState+ channelRefPopup: ChannelRefPopupState+ replyingTo?: string+ onCancelReply?: () => void+ pendingFiles: PendingFile[]+ removePendingFile: (index: number) => void+ fileInputRef: RefObject<HTMLInputElement | null>+ onFileSelect: ChangeEventHandler<HTMLInputElement>+ editor: Editor | null+ hideAttach: boolean+ hideEmoji: boolean+ onAttachOpenChange: (open: boolean) => void+ onUploadFile: () => void+ onEmojiPick: (emoji: string) => void+}++export function ComposerView({+ isForumThreadBody,+ dragging,+ onDragEnter,+ onDragLeave,+ onDragOver,+ onDrop,+ mentionPopup,+ channelRefPopup,+ replyingTo,+ onCancelReply,+ pendingFiles,+ removePendingFile,+ fileInputRef,+ onFileSelect,+ editor,+ hideAttach,+ hideEmoji,+ onAttachOpenChange,+ onUploadFile,+ onEmojiPick,+}: ComposerViewProps) {+ return (+ <div+ className={+ isForumThreadBody ? "relative" : "relative px-3 pb-3 pt-0"+ }+ onDragEnter={onDragEnter}+ onDragLeave={onDragLeave}+ onDragOver={onDragOver}+ onDrop={onDrop}+ >+ <CommunityMentionList state={mentionPopup} />+ <ChannelRefList state={channelRefPopup} />++ {replyingTo && (+ <div className="flex items-center gap-2 rounded-t-xl border border-b-0 border-border/40 bg-muted/60 px-4 py-2 text-xs text-muted-foreground">+ <span className="min-w-0 truncate">+ Replying to{" "}+ <span className="font-medium text-foreground">{replyingTo}</span>+ </span>+ <button+ onClick={onCancelReply}+ className="ml-auto grid size-4 shrink-0 place-items-center rounded-full hover:bg-foreground/10 hover:text-foreground"+ aria-label="Cancel reply"+ >+ <X className="size-3.5" />+ </button>+ </div>+ )}++ {pendingFiles.length > 0 && (+ <div+ className={`flex flex-wrap gap-2 border-x border-b border-border/40 bg-muted/40 px-4 py-2 ${replyingTo ? "" : "rounded-t-xl border-t"}`}+ >+ {pendingFiles.map((pendingFile, index) => {+ const isImage = pendingFile.file.type.startsWith("image/")+ return (+ <div+ key={index}+ className="group relative flex items-center gap-2 rounded-md border border-border bg-background px-3 py-2 text-xs"+ >+ {isImage ? (+ <ImageIcon className="size-3.5 text-muted-foreground" />+ ) : (+ <FileIcon className="size-3.5 text-muted-foreground" />+ )}+ <span className="max-w-30 truncate text-foreground">+ {pendingFile.file.name}+ </span>+ <button+ onClick={() => removePendingFile(index)}+ className="grid size-4 shrink-0 place-items-center rounded-full hover:bg-destructive/10 hover:text-destructive"+ aria-label="Remove file"+ >+ <X className="size-3" />+ </button>+ </div>+ )+ })}+ </div>+ )}++ <div+ className={`relative ${+ isForumThreadBody+ ? "bg-transparent ring-0"+ : "bg-muted shadow-(--e1) ring-1 ring-border/40 transition-shadow focus-within:ring-2 focus-within:ring-ring/60"+ } ${replyingTo || pendingFiles.length > 0 ? "rounded-b-xl" : "rounded-xl"}`}+ >+ {dragging && (+ <div+ className={`pointer-events-none absolute inset-0 z-10 grid place-items-center border-2 border-dashed border-ring bg-background/80 ${replyingTo || pendingFiles.length > 0 ? "rounded-b-xl" : "rounded-xl"}`}+ >+ <p className="text-sm font-medium text-muted-foreground">+ Drop files here+ </p>+ </div>+ )}+ <input+ ref={fileInputRef}+ type="file"+ multiple+ onChange={onFileSelect}+ className="hidden"+ />+ <div+ className={`chat-composer relative py-3 ${isForumThreadBody ? "px-2" : "px-12"}`}+ data-testid={tid.composerInput}+ >+ <EditorContent+ editor={editor}+ className={`${isForumThreadBody ? "max-h-60" : "max-h-40"} overflow-y-auto thin-scrollbar text-base chat-input-line-height outline-none`}+ />+ </div>+ {!hideAttach && (+ <DropdownMenu onOpenChange={onAttachOpenChange}>+ <DropdownMenuTrigger+ render={+ <button+ data-testid={tid.composerAttach}+ className="absolute left-2 bottom-2 grid size-8 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground aria-expanded:bg-accent aria-expanded:text-foreground"+ aria-label="Add"+ />+ }+ >+ <PlusCircle className="size-5" />+ </DropdownMenuTrigger>+ <DropdownMenuContent side="top" align="start" className="w-44">+ <DropdownMenuItem onClick={onUploadFile}>+ <Upload className="size-4" /> Upload a File+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ {!hideEmoji && (+ <EmojiPickerPopover side="top" align="end" onPick={onEmojiPick}>+ <button+ className="absolute right-2 bottom-2 grid size-8 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground aria-expanded:bg-accent aria-expanded:text-foreground"+ aria-label="Emoji picker"+ >+ <Smile className="size-5" />+ </button>+ </EmojiPickerPopover>+ )}+ </div>+ </div>+ )+}++export function ComposerSkeleton() {+ return (+ <div className="relative px-3 pb-3 pt-0">+ <div className="relative rounded-xl bg-muted px-12 py-3 shadow-(--e1) ring-1 ring-border/40">+ <Skeleton className="h-5 w-2/5 rounded" />+ <Skeleton className="absolute left-2 bottom-2 size-8 rounded-full" />+ <Skeleton className="absolute right-2 bottom-2 size-8 rounded-full" />+ </div>+ </div>+ )+}diff --git a/src/web/src/components/community/composer.send-lifecycle.test.ts b/src/web/src/components/community/messages/composer.send-lifecycle.test.tssimilarity index 100%rename from src/web/src/components/community/composer.send-lifecycle.test.tsrename to src/web/src/components/community/messages/composer.send-lifecycle.test.tsdiff --git a/src/web/src/components/community/composer.test.ts b/src/web/src/components/community/messages/composer.test.tssimilarity index 100%rename from src/web/src/components/community/composer.test.tsrename to src/web/src/components/community/messages/composer.test.tsdiff --git a/src/web/src/components/community/messages/composer.tsx b/src/web/src/components/community/messages/composer.tsxnew file mode 100644index 000000000..5ba190979--- /dev/null+++ b/src/web/src/components/community/messages/composer.tsx@@ -0,0 +1,23 @@+"use client"++import { forwardRef } from "react"+import type { SendAttachment } from "@/lib/community/models/message"+import { ComposerView, ComposerSkeleton } from "./composer-view"+import { useComposerController } from "./use-composer-controller"+import type { ComposerHandle, ComposerProps } from "./composer-types"++export type { SendAttachment }+export type { ComposerHandle, ComposerProps } from "./composer-types"+export {+ clipboardFiles,+ pendingFilesToSendAttachments,+} from "./composer-file-utils"+export { popoverStyle } from "./composer-suggestion-popups"+export { ComposerSkeleton }++export const Composer = forwardRef<ComposerHandle, ComposerProps>(+ function Composer(props, ref) {+ const viewProps = useComposerController(props, ref)+ return <ComposerView {...viewProps} />+ },+)diff --git a/src/web/src/components/community/create-forum-thread.test.ts b/src/web/src/components/community/messages/create-forum-thread.test.tssimilarity index 100%rename from src/web/src/components/community/create-forum-thread.test.tsrename to src/web/src/components/community/messages/create-forum-thread.test.tsdiff --git a/src/web/src/components/community/create-forum-thread.tsx b/src/web/src/components/community/messages/create-forum-thread.tsxsimilarity index 99%rename from src/web/src/components/community/create-forum-thread.tsxrename to src/web/src/components/community/messages/create-forum-thread.tsxindex 9e594b279..6458e384d 100644--- a/src/web/src/components/community/create-forum-thread.tsx+++ b/src/web/src/components/community/messages/create-forum-thread.tsx@@ -14,7 +14,7 @@ import { onEnterSubmit } from "@/lib/ime"import { toastApiError } from "@/lib/api/client"import { MAX_CHANNEL_NAME_LENGTH, type MentionType } from "@alook/shared"import { Composer, type ComposerHandle, type SendAttachment } from "./composer"-import type { Member } from "./_types"+import type { Member } from "@/lib/community/models/people"import {useUploadFile,zipUploadResultsWithDimensions,diff --git a/src/web/src/components/community/emoji-picker.tsx b/src/web/src/components/community/messages/emoji-picker.tsxsimilarity index 100%rename from src/web/src/components/community/emoji-picker.tsxrename to src/web/src/components/community/messages/emoji-picker.tsxdiff --git a/src/web/src/components/community/image-lightbox.test.ts b/src/web/src/components/community/messages/image-lightbox.test.tssimilarity index 100%rename from src/web/src/components/community/image-lightbox.test.tsrename to src/web/src/components/community/messages/image-lightbox.test.tsdiff --git a/src/web/src/components/community/image-lightbox.tsx b/src/web/src/components/community/messages/image-lightbox.tsxsimilarity index 96%rename from src/web/src/components/community/image-lightbox.tsxrename to src/web/src/components/community/messages/image-lightbox.tsxindex aa46be995..91849282d 100644--- a/src/web/src/components/community/image-lightbox.tsx+++ b/src/web/src/components/community/messages/image-lightbox.tsx@@ -2,7 +2,7 @@import { useState } from "react"import { Dialog, DialogContent } from "@/components/ui/dialog"-import type { ImagePreview } from "./_types"+import type { ImagePreview } from "@/lib/community/models/message"import { tid } from "@/lib/community/testids"// Full-screen image preview. Uses shadcn Dialog for accessibility (focus trap, Esc, aria).diff --git a/src/web/src/components/community/inline-marks.tsx b/src/web/src/components/community/messages/inline-marks.tsxsimilarity index 98%rename from src/web/src/components/community/inline-marks.tsxrename to src/web/src/components/community/messages/inline-marks.tsxindex b358dc827..fdc540c7d 100644--- a/src/web/src/components/community/inline-marks.tsx+++ b/src/web/src/components/community/messages/inline-marks.tsx@@ -2,7 +2,7 @@import { useState } from "react"import type React from "react"-import { ChannelIcon } from "./channel-icon"+import { ChannelIcon } from "../channels/channel-icon"// Pill components the streamdown renderer maps custom tags to (see message-markdown.tsx).diff --git a/src/web/src/components/community/media-attachment-block.test.ts b/src/web/src/components/community/messages/media-attachment-block.test.tssimilarity index 99%rename from src/web/src/components/community/media-attachment-block.test.tsrename to src/web/src/components/community/messages/media-attachment-block.test.tsindex 3e8d625d1..e51879fe0 100644--- a/src/web/src/components/community/media-attachment-block.test.ts+++ b/src/web/src/components/community/messages/media-attachment-block.test.ts@@ -2,7 +2,7 @@ import React from "react"import TestRenderer, { act } from "react-test-renderer"import { describe, expect, it, vi } from "vitest"import { tid } from "@/lib/community/testids"-import type { FileAttachment } from "./_types"+import type { FileAttachment } from "@/lib/community/models/message"import { MediaAttachmentBlock } from "./media-attachment-block"vi.mock("@/components/ui/button", () => ({diff --git a/src/web/src/components/community/media-attachment-block.tsx b/src/web/src/components/community/messages/media-attachment-block.tsxsimilarity index 99%rename from src/web/src/components/community/media-attachment-block.tsxrename to src/web/src/components/community/messages/media-attachment-block.tsxindex 68036c187..0bcf63aa4 100644--- a/src/web/src/components/community/media-attachment-block.tsx+++ b/src/web/src/components/community/messages/media-attachment-block.tsx@@ -5,7 +5,7 @@ import { flushSync } from "react-dom"import { Download, FileAudio, FileVideo, LoaderCircle, Pause, Play, RefreshCw, Square } from "lucide-react"import { Button } from "@/components/ui/button"import { tid } from "@/lib/community/testids"-import type { FileAttachment } from "./_types"+import type { FileAttachment } from "@/lib/community/models/message"type MediaKind = "audio" | "video"type MediaStatus = "idle" | "loading" | "ready" | "blocked" | "error"diff --git a/src/web/src/components/community/message-body.test.ts b/src/web/src/components/community/messages/message-body.test.tssimilarity index 100%rename from src/web/src/components/community/message-body.test.tsrename to src/web/src/components/community/messages/message-body.test.tsdiff --git a/src/web/src/components/community/message-body.tsx b/src/web/src/components/community/messages/message-body.tsxsimilarity index 96%rename from src/web/src/components/community/message-body.tsxrename to src/web/src/components/community/messages/message-body.tsxindex 1c4431583..607235af7 100644--- a/src/web/src/components/community/message-body.tsx+++ b/src/web/src/components/community/messages/message-body.tsx@@ -13,8 +13,9 @@ import {MD_LITERAL_TAGS,buildMdComponents,} from "./message-markdown"-import { CommunityInviteCard } from "./community-invite-card"-import type { MessagePerspective, OpenProfile } from "./_types"+import { CommunityInviteCard } from "../social/community-invite-card"+import type { MessagePerspective } from "@/components/community/messages/message-presentation-types"+import type { OpenProfile } from "@/components/community/social/profile-types"// The sanitize schema Streamdown builds internally when `allowedTags` is// left at its default merge path (verified against Streamdown 2.5.0'sdiff --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.tsnew file mode 100644index 000000000..b2e5e6e69--- /dev/null+++ b/src/web/src/components/community/messages/message-channel-controller-actions.test.ts@@ -0,0 +1,244 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { createMessageActions, type MessageActionContext } from "./message-channel-controller-actions"++const mocks = vi.hoisted(() => ({+ dispatch: vi.fn(),+ toast: vi.fn(),+ toastApiError: vi.fn(),+ deriveThreadName: vi.fn(() => "derived thread"),+}))++vi.mock("@/stores/community/message-stream", () => ({+ useMessageStreamStore: { getState: () => ({ dispatch: mocks.dispatch }) },+}))+vi.mock("sonner", () => ({ toast: mocks.toast }))+vi.mock("@/lib/api/client", () => ({ toastApiError: mocks.toastApiError }))+vi.mock("@alook/shared", () => ({ deriveThreadName: mocks.deriveThreadName }))++function setup() {+ const setReplyTo = vi.fn()+ const toggleReactionApi = vi.fn()+ const unpinMessageMutate = vi.fn()+ 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()+ const previewImage = vi.fn()+ const previewAttachment = vi.fn()+ const actionContext = { current: {+ messages: [{+ id: "m1",+ seq: 4,+ type: "chat" as const,+ authorId: "viewer_1",+ authorName: "Viewer",+ content: "hello",+ createdAt: new Date(0).toISOString(),+ clientNonce: "nonce_1",+ }],+ pinnedIds: new Set<string>(),+ channelName: "general",+ uiHandlers: { previewImage, previewAttachment },+ onOpenThread,+ onOpenPinned,+ } } as { current: MessageActionContext }+ const actions = createMessageActions({+ actionContext,+ serverId: "server_1",+ channelId: "channel_1",+ viewerUserId: "viewer_1",+ setReplyTo,+ toggleReactionApi,+ unpinMessageMutate,+ pinMessageMutate,+ toggleMark,+ createThreadAsync,+ editMessage,+ messageScope: { kind: "channel", id: "channel_1", serverId: "server_1" },+ runAcceptedIntent,+ })+ return {+ actions,+ actionContext,+ setReplyTo,+ toggleReactionApi,+ unpinMessageMutate,+ pinMessageMutate,+ toggleMark,+ createThreadAsync,+ editMessage,+ runAcceptedIntent,+ onOpenThread,+ onOpenPinned,+ previewImage,+ previewAttachment,+ }+}++describe("createMessageActions", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ vi.stubGlobal("navigator", { clipboard: { writeText: vi.fn() } })+ })+ afterEach(() => vi.unstubAllGlobals())++ it("routes reply, reactions, marks, previews, retry, dismiss, and download exactly", async () => {+ const harness = setup()+ const link = { href: "", download: "", click: vi.fn() }+ vi.stubGlobal("document", { createElement: vi.fn(() => link) })+ harness.actions.onReply("m1")+ expect(harness.setReplyTo).toHaveBeenCalledWith({ id: "m1", authorName: "Viewer", text: "hello" })+ harness.actions.onToggleReaction("m1", "👍")+ harness.actions.onReact("m1", "🔥")+ expect(harness.toggleReactionApi).toHaveBeenNthCalledWith(1, {+ serverId: "server_1", channelId: "channel_1", messageId: "m1", emoji: "👍", userId: "viewer_1",+ })+ expect(harness.toggleReactionApi).toHaveBeenNthCalledWith(2, {+ serverId: "server_1", channelId: "channel_1", messageId: "m1", emoji: "🔥", userId: "viewer_1",+ })+ harness.actions.onMark("m1")+ expect(harness.toggleMark).toHaveBeenCalledWith("channel_1", "m1")+ harness.actions.onPreviewImage({ url: "image" })+ harness.actions.onPreviewAttachment({ id: "a1" } as never)+ expect(harness.previewImage).toHaveBeenCalledWith({ url: "image" })+ expect(harness.previewAttachment).toHaveBeenCalledWith({ id: "a1" })+ harness.actions.onRetry("m1")+ expect(mocks.dispatch).toHaveBeenCalledWith(+ { kind: "channel", id: "channel_1", serverId: "server_1" },+ { type: "retry", nonce: "nonce_1" },+ )+ expect(harness.runAcceptedIntent).toHaveBeenCalledWith("nonce_1")+ harness.actions.onDismiss("m1")+ expect(mocks.dispatch).toHaveBeenCalledWith(+ { kind: "channel", id: "channel_1", serverId: "server_1" },+ { type: "dismissFailed", nonce: "nonce_1" },+ )+ const dispatchCount = mocks.dispatch.mock.calls.length+ harness.actions.onRetry("missing")+ harness.actions.onDismiss("missing")+ harness.actionContext.current.messages = [{+ ...harness.actionContext.current.messages[0],+ clientNonce: undefined,+ }]+ harness.actions.onRetry("m1")+ harness.actions.onDismiss("m1")+ expect(mocks.dispatch).toHaveBeenCalledTimes(dispatchCount)+ expect(harness.runAcceptedIntent).toHaveBeenCalledOnce()+ harness.actions.onDownloadFile("/file", "report.txt")+ expect(link).toEqual(expect.objectContaining({ href: "/file", download: "report.txt" }))+ expect(link.click).toHaveBeenCalledOnce()+ })++ it("preserves pin/unpin, thread, copy, and edit guards and callbacks", async () => {+ const harness = setup()+ harness.actions.onPin("m1")+ expect(harness.pinMessageMutate).toHaveBeenCalled()+ expect(harness.onOpenPinned).toHaveBeenCalledOnce()+ const pinOptions = harness.pinMessageMutate.mock.calls[0][1]+ pinOptions.onSuccess()+ expect(mocks.toast).toHaveBeenCalledWith("Message pinned")+ const pinFailure = new Error("pin failed")+ pinOptions.onError(pinFailure)+ expect(mocks.toastApiError).toHaveBeenCalledWith(pinFailure, "Failed to pin message")++ harness.actionContext.current.pinnedIds = new Set(["m1"])+ harness.actions.onPin("m1")+ expect(harness.unpinMessageMutate).toHaveBeenCalled()+ expect(harness.onOpenPinned).toHaveBeenCalledOnce()+ const unpinOptions = harness.unpinMessageMutate.mock.calls[0][1]+ unpinOptions.onSuccess()+ expect(mocks.toast).toHaveBeenCalledWith("Message unpinned")+ const unpinFailure = new Error("unpin failed")+ unpinOptions.onError(unpinFailure)+ expect(mocks.toastApiError).toHaveBeenCalledWith(unpinFailure, "Failed to unpin message")++ let resolveThread: (value: { id: string }) => void = () => {}+ harness.createThreadAsync.mockImplementationOnce(() => new Promise((resolve) => {+ resolveThread = resolve+ }))+ const pendingThread = harness.actions.onCreateThread("m1")+ expect(mocks.deriveThreadName).toHaveBeenCalledWith("hello", "general")+ expect(harness.createThreadAsync).toHaveBeenCalledWith({+ serverId: "server_1", channelId: "channel_1", messageId: "m1", name: "derived thread",+ })+ const latestOpenThread = vi.fn()+ harness.actionContext.current.onOpenThread = latestOpenThread+ resolveThread({ id: "thread_1" })+ await pendingThread+ expect(harness.onOpenThread).not.toHaveBeenCalled()+ expect(latestOpenThread).toHaveBeenCalledWith("thread_1")+ const threadFailure = new Error("thread failed")+ harness.createThreadAsync.mockRejectedValueOnce(threadFailure)+ await harness.actions.onCreateThread("m1")+ expect(mocks.toastApiError).toHaveBeenCalledWith(threadFailure, "Failed to create thread")+ expect(latestOpenThread).toHaveBeenCalledOnce()++ harness.actions.onCopy("m1")+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith("hello")+ expect(mocks.toast).toHaveBeenCalledWith("Copied to clipboard")+ const copyCount = vi.mocked(navigator.clipboard.writeText).mock.calls.length+ harness.actions.onCopy("missing")+ harness.actionContext.current.messages = [{+ ...harness.actionContext.current.messages[0], content: "",+ }]+ harness.actions.onCopy("m1")+ expect(navigator.clipboard.writeText).toHaveBeenCalledTimes(copyCount)++ harness.actionContext.current.messages = [{+ ...harness.actionContext.current.messages[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",+ }, 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")++ 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.actionContext.current.messages = [{+ ...harness.actionContext.current.messages[0], authorId: "peer_1",+ }]+ harness.actions.onEdit("m1")+ harness.actionContext.current.messages = [{+ ...harness.actionContext.current.messages[0], authorId: "viewer_1", seq: undefined,+ }]+ harness.actions.onEdit("m1")+ harness.actionContext.current.messages = [{+ ...harness.actionContext.current.messages[0], seq: 4, content: "",+ }]+ harness.actions.onEdit("m1")+ expect(harness.editMessage).toHaveBeenCalledOnce()+ })++ it("reads latest context through one stable action object and has no delete action", () => {+ const harness = setup()+ const latestReply = vi.fn()+ harness.actionContext.current.messages = [{+ id: "m2",+ type: "chat",+ authorName: "Latest",+ content: "new",+ createdAt: new Date(1).toISOString(),+ }]+ harness.actionContext.current.onOpenThread = latestReply+ harness.actions.onReply("m2")+ expect(harness.setReplyTo).toHaveBeenCalledWith({ id: "m2", authorName: "Latest", text: "new" })+ expect("onDelete" in harness.actions).toBe(false)+ })+})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.tsnew file mode 100644index 000000000..47bc26b8c--- /dev/null+++ b/src/web/src/components/community/messages/message-channel-controller-actions.ts@@ -0,0 +1,164 @@+import type { MutableRefObject } from "react"+import { deriveThreadName } from "@alook/shared"+import { toast } from "sonner"+import { toastApiError } from "@/lib/api/client"+import type { FileAttachment, ImagePreview, Msg } from "@/lib/community/models/message"+import { useMessageStreamStore } from "@/stores/community/message-stream"+import type {+ MessageActions,+ MessageUiHandlers,+ ReplyTarget,+} from "./message-channel-controller-types"++type ChannelMessageScope = {+ kind: "channel"+ id: string+ serverId: string+}++type MutationOptions = {+ onSuccess?: () => void+ onError?: (error: unknown) => void+}++export type MessageActionContext = {+ messages: Msg[]+ pinnedIds: Set<string>+ channelName: string+ uiHandlers: MessageUiHandlers+ onOpenThread: (threadId: string) => void+ onOpenPinned: () => void+}++export function createMessageActions({+ actionContext,+ serverId,+ channelId,+ viewerUserId,+ setReplyTo,+ toggleReactionApi,+ unpinMessageMutate,+ pinMessageMutate,+ toggleMark,+ createThreadAsync,+ editMessage,+ messageScope,+ runAcceptedIntent,+}: {+ actionContext: MutableRefObject<MessageActionContext>+ serverId: string+ channelId: string+ viewerUserId: string+ setReplyTo: (reply: ReplyTarget) => void+ toggleReactionApi: (input: {+ serverId: string+ channelId: string+ messageId: string+ emoji: string+ userId: string+ }) => void+ unpinMessageMutate: (+ input: { channelId: string; messageId: string },+ options?: MutationOptions,+ ) => void+ pinMessageMutate: (+ input: { channelId: string; messageId: string },+ options?: MutationOptions,+ ) => void+ toggleMark: (channelId: string, messageId: string) => void+ createThreadAsync: (input: {+ serverId: string+ channelId: string+ messageId: string+ name: string+ }) => Promise<{ id: string }>+ editMessage: (+ input: { serverId: string; channelId: string; messageId: string; content: string },+ options?: MutationOptions,+ ) => void+ messageScope: ChannelMessageScope+ runAcceptedIntent: (nonce: string) => Promise<void>+}): MessageActions {+ return {+ onToggleReaction: (id, emoji) =>+ toggleReactionApi({ serverId, channelId, messageId: id, emoji, userId: viewerUserId }),+ onReact: (id, emoji) =>+ toggleReactionApi({ serverId, channelId, messageId: id, emoji, userId: viewerUserId }),+ onReply: (id) => {+ const message = actionContext.current.messages.find((item) => item.id === id)+ if (message) {+ setReplyTo({+ id: message.id,+ authorName: message.authorName ?? "",+ text: message.content ?? "",+ })+ }+ },+ onPin: (id) => {+ if (actionContext.current.pinnedIds.has(id)) {+ unpinMessageMutate({ channelId, messageId: id }, {+ onSuccess: () => toast("Message unpinned"),+ onError: (error) => toastApiError(error, "Failed to unpin message"),+ })+ return+ }+ pinMessageMutate({ channelId, messageId: id }, {+ onSuccess: () => toast("Message pinned"),+ onError: (error) => toastApiError(error, "Failed to pin message"),+ })+ actionContext.current.onOpenPinned()+ },+ onMark: (id) => toggleMark(channelId, id),+ onCreateThread: async (id) => {+ const message = actionContext.current.messages.find((item) => item.id === id)+ const name = deriveThreadName(message?.content, actionContext.current.channelName)+ try {+ const data = await createThreadAsync({ serverId, channelId, messageId: id, name })+ actionContext.current.onOpenThread(data.id)+ } catch (error) {+ toastApiError(error, "Failed to create thread")+ }+ },+ onCopy: (id) => {+ const message = actionContext.current.messages.find((item) => item.id === id)+ if (!message?.content) return+ void navigator.clipboard?.writeText(message.content)+ toast("Copied to clipboard")+ },+ onEdit: (id) => {+ const message = actionContext.current.messages.find((item) => item.id === id)+ if (!message?.content || message.authorId !== viewerUserId || message.seq === undefined) return+ const content = window.prompt("Edit message", message.content)+ if (!content || content === message.content) return+ editMessage({ serverId, channelId, messageId: id, content }, {+ onError: (error) => toastApiError(error, "Failed to edit message"),+ })+ },+ onRetry: (id) => {+ const message = actionContext.current.messages.find((item) => item.id === id)+ if (!message?.clientNonce) return+ useMessageStreamStore.getState().dispatch(messageScope, {+ type: "retry",+ nonce: message.clientNonce,+ })+ void runAcceptedIntent(message.clientNonce)+ },+ onDismiss: (id) => {+ const message = actionContext.current.messages.find((item) => item.id === id)+ if (!message?.clientNonce) return+ useMessageStreamStore.getState().dispatch(messageScope, {+ type: "dismissFailed",+ nonce: message.clientNonce,+ })+ },+ onPreviewImage: (image: ImagePreview) => actionContext.current.uiHandlers.previewImage?.(image),+ onPreviewAttachment: (attachment: FileAttachment) =>+ actionContext.current.uiHandlers.previewAttachment?.(attachment),+ onDownloadFile: (url, name) => {+ const link = document.createElement("a")+ link.href = url+ link.download = name+ link.click()+ },+ }+}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.tsnew file mode 100644index 000000000..de9e1034b--- /dev/null+++ b/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts@@ -0,0 +1,153 @@+import { readFileSync } from "node:fs"+import { dirname, resolve } from "node:path"+import { fileURLToPath } from "node:url"+import type { ComponentProps, ComponentRef, ReactNode } from "react"+import type { MentionType } from "@alook/shared"+import { describe, expect, expectTypeOf, it } from "vitest"+import * as facade from "./message-channel-controller"+import type { MessageChannelControllerValue as FacadeControllerValue } from "./message-channel-controller"+import type {+ FileAttachment,+ ImagePreview,+ Msg,+ SendAttachment,+} from "@/lib/community/models/message"+import type { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"++type ExpectedReplyTarget = { id: string; authorName: string; text: string }+type ExpectedContextTarget = {+ serverId: string+ channelId: string+ label: string+ seq: number+}+type ExpectedMessageActions = {+ onToggleReaction: (id: string, emoji: string) => void+ onReact: (id: string, emoji: string) => void+ onReply: (id: string) => void+ onPin: (id: string) => void+ 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+ onPreviewAttachment: (attachment: FileAttachment) => void+ onDownloadFile: (url: string, name: string) => void+}+type ExpectedControllerValue = {+ feed: ReturnType<typeof useChannelMessageFeed>+ pinnedIds: Set<string>+ replyTo: ExpectedReplyTarget | null+ setReplyTo: (reply: ExpectedReplyTarget | null) => void+ searchQuery: string+ searchResults: Msg[]+ search: (query: string) => void+ scrollTargetId: string | null+ setScrollTargetId: (targetId: string | null) => void+ consumeScrollTarget: (targetId: string) => void+ contextTarget: ExpectedContextTarget | null+ setContextTarget: (target: ExpectedContextTarget | null) => void+ openContextSeq: (seq: number) => void+ onSheetReply: (target: ExpectedReplyTarget) => void+ jumpToSeq: (seq: number) => void+ messageActions: ExpectedMessageActions+ threadActions: Omit<ExpectedMessageActions, "onCreateThread"> & { onCreateThread: undefined }+ acceptMessage: (+ markdown: string,+ attachments?: SendAttachment[],+ mentionType?: MentionType,+ ) => boolean+ handleTyping: () => void+ typingUsers: string[]+}+type ExpectedControllerProps = {+ channelId: string+ serverId: string+ serverParam: string+ channelName: string+ forumParentChannelId?: string+ viewer: { id: string; name: string; avatar: string }+ anchorMessageId: string | null+ feed: ReturnType<typeof useChannelMessageFeed>+ uiHandlers: {+ navigate?: (serverId: string, channelId: string) => void+ previewImage?: (image: ImagePreview) => void+ previewAttachment?: (attachment: FileAttachment) => void+ }+ onOpenThread: (threadId: string) => void+ onOpenPinned: () => void+ resolveUserName: (userId: string) => string+ children: (controller: ExpectedControllerValue) => ReactNode+}++const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..")+const source = (path: string) => readFileSync(resolve(webRoot, path), "utf8")++describe("MessageChannelController facade contract", () => {+ it("keeps the exact runtime export and a direct non-component render call", () => {+ expect(Object.keys(facade)).toEqual(["MessageChannelController"])+ expectTypeOf<ComponentProps<typeof facade.MessageChannelController>>()+ .toEqualTypeOf<ExpectedControllerProps>()+ expectTypeOf<ExpectedControllerProps>()+ .toEqualTypeOf<ComponentProps<typeof facade.MessageChannelController>>()+ expectTypeOf<FacadeControllerValue>().toEqualTypeOf<ExpectedControllerValue>()+ expectTypeOf<ExpectedControllerValue>().toEqualTypeOf<FacadeControllerValue>()+ expectTypeOf<ComponentRef<typeof facade.MessageChannelController>>().toEqualTypeOf<never>()+ const text = source("src/components/community/messages/message-channel-controller.tsx")+ expect(text).toContain("useMessageChannelController(props)")+ expect(text).toContain("return renderMessageChannelController(children, value)")+ expect(text).not.toMatch(/<MessageChannelControllerView\b|createElement\(MessageChannelControllerView/)+ expect(text).not.toMatch(/forwardRef|useImperativeHandle/)+ })++ it("keeps production and test consumers on the original path", () => {+ const importers = [+ "src/components/community/channels/thread-channel-surface.tsx",+ "src/components/community/channels/text-channel-surface.tsx",+ "src/components/community/channels/thread-channel-surface.test.ts",+ "src/components/community/channels/text-channel-surface.test.ts",+ ]+ for (const path of importers) {+ const text = source(path)+ expect(text).toMatch(/message-channel-controller["']/)+ expect(text).not.toMatch(/message-channel-controller-(types|state|actions|send|view)/)+ }+ })++ it("keeps hook wiring in one owner and pure helpers hook-free", () => {+ const state = source("src/components/community/messages/message-channel-controller-state.ts")+ const body = state.slice(state.indexOf("export function useMessageChannelController"))+ const actions = source("src/components/community/messages/message-channel-controller-actions.ts")+ const send = source("src/components/community/messages/message-channel-controller-send.ts")+ const orderedHooks = [+ "const router = useRouter()",+ "const searchParams = useSearchParams()",+ "const [replyTo, setReplyTo] = useState<ReplyTarget | null>(null)",+ "const [searchQuery, setSearchQuery] = useState(\"\")",+ "const [searchResults, setSearchResults] = useState<Msg[]>([])",+ "const [scrollTargetId, setScrollTargetId] = useState<string | null>(anchorMessageId)",+ "const [contextTarget, setContextTarget] = useState<MessageContextTarget | null>(null)",+ "useSendMessage()",+ "useToggleReactionApi()",+ "usePinMessage()",+ "useUnpinMessage()",+ "useToggleMark()",+ "useEditMessage()",+ "useCreateThread()",+ "useUploadFile()",+ "useTypingUsersForScope(`ch:${channelId}`)",+ "useTypingNamesForScope(`ch:${channelId}`)",+ ]+ let cursor = -1+ for (const token of orderedHooks) {+ const position = body.indexOf(token, cursor + 1)+ expect(position, token).toBeGreaterThan(cursor)+ cursor = position+ }+ expect(body.match(/\buseState(?:<[^>]+>)?\(/g)).toHaveLength(5)+ expect(actions).not.toMatch(/\buse[A-Z][A-Za-z]+\(/)+ expect(send).not.toMatch(/\buse[A-Z][A-Za-z]+\(/)+ })+})diff --git a/src/web/src/components/community/messages/message-channel-controller-send.test.ts b/src/web/src/components/community/messages/message-channel-controller-send.test.tsnew file mode 100644index 000000000..2eaffcf7f--- /dev/null+++ b/src/web/src/components/community/messages/message-channel-controller-send.test.ts@@ -0,0 +1,355 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { acceptChannelMessage, runAcceptedMessageIntent } from "./message-channel-controller-send"++const mocks = vi.hoisted(() => ({+ accept: vi.fn(),+ getRetryPayload: vi.fn(),+ dispatch: vi.fn(),+ toastApiError: vi.fn(),+ resetTyping: vi.fn(),+ zip: vi.fn(),+ toVm: vi.fn((channelId: string, attachment: { id: string }) => ({+ kind: "file", url: `/api/${channelId}/${attachment.id}`, name: attachment.id, size: 1,+ })),+}))++vi.mock("@/stores/community/message-stream", () => ({+ useMessageStreamStore: { getState: () => ({+ accept: mocks.accept,+ getRetryPayload: mocks.getRetryPayload,+ dispatch: mocks.dispatch,+ }) },+}))+vi.mock("@/hooks/community/mutations", () => ({+ sendNonce: () => "nonce_1",+ tempMessageId: () => "temp_1",+ toAttachmentVm: mocks.toVm,+ zipUploadResultsWithDimensions: mocks.zip,+}))+vi.mock("@/hooks/community/use-community-ws", () => ({+ communityWsResetTypingThrottle: mocks.resetTyping,+}))+vi.mock("@/lib/api/client", () => ({ toastApiError: mocks.toastApiError }))++const scope = { kind: "channel" as const, id: "channel_1", serverId: "server_1" }+const viewer = { id: "viewer_1", name: "Viewer", avatar: "V" }++describe("message channel send helpers", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ vi.useFakeTimers()+ vi.setSystemTime(new Date("2026-01-02T03:04:05.000Z"))+ vi.stubGlobal("URL", {+ createObjectURL: vi.fn(() => "blob:new"),+ revokeObjectURL: vi.fn(),+ })+ })+ afterEach(() => {+ vi.useRealTimers()+ vi.unstubAllGlobals()+ })++ it("rejects empty input and revokes only URLs created by a rejected attempt", () => {+ const runner = vi.fn(async () => {})+ const clearReply = vi.fn()+ expect(acceptChannelMessage({+ markdown: "", messageScope: scope, viewer, replyTo: null,+ runAcceptedIntent: runner, channelId: "channel_1", clearReply,+ })).toBe(false)+ expect(mocks.accept).not.toHaveBeenCalled()++ mocks.accept.mockReturnValue(false)+ const created = new File(["a"], "a.txt", { type: "text/plain" })+ const supplied = new File(["b"], "b.txt", { type: "text/plain" })+ expect(acceptChannelMessage({+ markdown: "hello",+ attachments: [+ { file: created },+ { file: supplied, previewObjectUrl: "blob:supplied" },+ ],+ messageScope: scope,+ viewer,+ replyTo: null,+ runAcceptedIntent: runner,+ channelId: "channel_1",+ clearReply,+ })).toBe(false)+ expect(URL.createObjectURL).toHaveBeenCalledOnce()+ expect(URL.revokeObjectURL).toHaveBeenCalledWith("blob:new")+ expect(URL.revokeObjectURL).not.toHaveBeenCalledWith("blob:supplied")+ expect(runner).not.toHaveBeenCalled()+ expect(mocks.resetTyping).not.toHaveBeenCalled()+ expect(clearReply).not.toHaveBeenCalled()+ })++ it("accepts synchronously with exact optimistic payload before fire-and-forget/reset/clear", () => {+ const order: string[] = []+ const file = new File(["abc"], "a.png", { type: "image/png" })+ const thumbnailBlob = new Blob(["thumb"], { type: "image/jpeg" })+ mocks.accept.mockImplementation((acceptedScope, payload) => {+ order.push("accept")+ expect(acceptedScope).toEqual(scope)+ expect(payload).toEqual({+ nonce: "nonce_1",+ tempId: "temp_1",+ message: {+ type: "chat",+ authorId: "viewer_1",+ authorName: "Viewer",+ authorAvatar: "V",+ content: "hello",+ createdAt: "2026-01-02T03:04:05.000Z",+ replyTo: { id: "reply_1", authorName: "Alice", text: "prior" },+ },+ localUploads: [{+ file,+ thumbnailBlob,+ previewObjectUrl: "blob:new",+ width: 10,+ height: 20,+ }],+ mentionType: "user",+ })+ return true+ })+ const runner = vi.fn(async () => { order.push("run") })+ mocks.resetTyping.mockImplementation(() => order.push("typing"))+ const clearReply = vi.fn(() => order.push("clear"))+ expect(acceptChannelMessage({+ markdown: "hello",+ attachments: [{ file, thumbnailBlob, width: 10, height: 20 }],+ mentionType: "user",+ messageScope: scope,+ viewer,+ replyTo: { id: "reply_1", authorName: "Alice", text: "prior" },+ runAcceptedIntent: runner,+ channelId: "channel_1",+ clearReply,+ })).toBe(true)+ expect(runner).toHaveBeenCalledWith("nonce_1")+ expect(mocks.resetTyping).toHaveBeenCalledWith({ channelId: "channel_1" })+ expect(order).toEqual(["accept", "run", "typing", "clear"])+ expect(URL.revokeObjectURL).not.toHaveBeenCalled()+ })++ it("accepts an attachment-only intent with an exact empty-content optimistic payload", () => {+ const file = new File(["abc"], "only.txt", { type: "text/plain" })+ const runner = vi.fn(async () => {})+ const clearReply = vi.fn()+ mocks.accept.mockReturnValue(true)++ expect(acceptChannelMessage({+ markdown: "",+ attachments: [{ file, previewObjectUrl: "blob:provided" }],+ messageScope: scope,+ viewer,+ replyTo: null,+ runAcceptedIntent: runner,+ channelId: "channel_1",+ clearReply,+ })).toBe(true)+ expect(mocks.accept).toHaveBeenCalledWith(scope, {+ nonce: "nonce_1",+ tempId: "temp_1",+ message: {+ type: "chat",+ authorId: "viewer_1",+ authorName: "Viewer",+ authorAvatar: "V",+ content: "",+ createdAt: "2026-01-02T03:04:05.000Z",+ },+ localUploads: [{+ file,+ thumbnailBlob: undefined,+ previewObjectUrl: "blob:provided",+ width: undefined,+ height: undefined,+ }],+ mentionType: undefined,+ })+ expect(runner).toHaveBeenCalledWith("nonce_1")+ expect(mocks.resetTyping).toHaveBeenCalledWith({ channelId: "channel_1" })+ expect(clearReply).toHaveBeenCalledOnce()+ })++ it("reuses settled projections and dispatches all-or-nothing upload failure without sending", async () => {+ const local = {+ file: new File(["abc"], "a.png", { type: "image/png" }),+ thumbnailBlob: new Blob(["thumb"], { type: "image/jpeg" }),+ previewObjectUrl: "blob:a",+ width: 10,+ height: 20,+ }+ const sendMessageAsync = vi.fn(async () => ({}))+ const uploadFileAsync = vi.fn(async () => ({+ id: "uploaded", filename: "a.png", contentType: "image/png", size: 3,+ }))+ mocks.getRetryPayload.mockReturnValueOnce({+ localUploads: [local],+ uploadStatus: "settled",+ message: {+ content: "hello",+ attachments: [{ kind: "image", url: "/att/existing", thumbnailUrl: "/thumb" }],+ },+ mentionType: "user",+ })+ await runAcceptedMessageIntent({+ messageScope: scope, nonce: "nonce_1", uploadFileAsync, sendMessageAsync,+ channelId: "channel_1", serverId: "server_1", viewer,+ })+ expect(uploadFileAsync).not.toHaveBeenCalled()+ expect(sendMessageAsync).toHaveBeenCalledWith(expect.objectContaining({+ attachments: [expect.objectContaining({+ id: "existing", filename: "a.png", hasThumbnail: true, width: 10, height: 20,+ })],+ nonce: "nonce_1",+ }))++ mocks.getRetryPayload.mockReturnValueOnce({+ localUploads: [local, { ...local, file: new File(["b"], "b.png", { type: "image/png" }) }],+ uploadStatus: "pending",+ message: { content: "again" },+ })+ uploadFileAsync.mockResolvedValueOnce({+ id: "ok", filename: "a.png", contentType: "image/png", size: 3,+ }).mockRejectedValueOnce(new Error("failed"))+ sendMessageAsync.mockClear()+ await runAcceptedMessageIntent({+ messageScope: scope, nonce: "nonce_2", uploadFileAsync, sendMessageAsync,+ channelId: "channel_1", serverId: "server_1", viewer,+ })+ expect(uploadFileAsync).toHaveBeenCalledTimes(2)+ expect(mocks.toastApiError).toHaveBeenCalledWith(expect.any(Error), "Failed to attach file")+ expect(mocks.dispatch).toHaveBeenCalledWith(scope, { type: "uploadFailed", nonce: "nonce_2" })+ expect(sendMessageAsync).not.toHaveBeenCalled()+ })++ it("uploads in parallel, zips dimensions, dispatches settled VMs, then sends the exact payload", async () => {+ const order: string[] = []+ const uploads = [+ {+ file: new File(["a"], "a.png", { type: "image/png" }),+ thumbnailBlob: new Blob(["ta"], { type: "image/jpeg" }),+ previewObjectUrl: "blob:a",+ width: 10,+ height: 20,+ },+ {+ file: new File(["bb"], "b.txt", { type: "text/plain" }),+ previewObjectUrl: "blob:b",+ width: undefined,+ height: undefined,+ },+ ]+ const uploaded = [+ { id: "a1", filename: "a.png", contentType: "image/png", size: 1 },+ { id: "a2", filename: "b.txt", contentType: "text/plain", size: 2 },+ ]+ mocks.getRetryPayload.mockReturnValue({+ localUploads: uploads,+ uploadStatus: "pending",+ message: {+ content: "hello",+ replyTo: { id: "reply_1", authorName: "Alice", text: "prior" },+ },+ mentionType: "user",+ })+ const uploadFileAsync = vi.fn(async ({ file }: { file: File }) => {+ order.push(`upload:${file.name}`)+ return file.name === "a.png" ? uploaded[0] : uploaded[1]+ })+ mocks.zip.mockImplementation((results, localUploads) => {+ order.push("zip")+ expect(results).toEqual(uploaded)+ expect(localUploads).toEqual(uploads)+ return uploaded+ })+ mocks.toVm.mockImplementation((channelId: string, attachment: { id: string }) => {+ order.push(`vm:${attachment.id}`)+ return { kind: "file", url: `/api/${channelId}/${attachment.id}`, name: attachment.id, size: 1 }+ })+ mocks.dispatch.mockImplementation(() => { order.push("dispatch") })+ const sendMessageAsync = vi.fn(async () => { order.push("send") })++ await runAcceptedMessageIntent({+ messageScope: scope,+ nonce: "nonce_upload",+ uploadFileAsync,+ sendMessageAsync,+ channelId: "channel_1",+ forumParentChannelId: "forum_1",+ serverId: "server_1",+ viewer,+ })++ expect(uploadFileAsync).toHaveBeenCalledTimes(2)+ expect(uploadFileAsync).toHaveBeenNthCalledWith(1, {+ target: { channelId: "channel_1" },+ file: uploads[0].file,+ thumbnailBlob: uploads[0].thumbnailBlob,+ width: 10,+ height: 20,+ })+ expect(uploadFileAsync).toHaveBeenNthCalledWith(2, {+ target: { channelId: "channel_1" },+ file: uploads[1].file,+ thumbnailBlob: undefined,+ width: undefined,+ height: undefined,+ })+ expect(mocks.dispatch).toHaveBeenCalledWith(scope, {+ type: "uploadSettled",+ nonce: "nonce_upload",+ attachments: [+ { kind: "file", url: "/api/channel_1/a1", name: "a1", size: 1 },+ { kind: "file", url: "/api/channel_1/a2", name: "a2", size: 1 },+ ],+ })+ expect(sendMessageAsync).toHaveBeenCalledWith({+ serverId: "server_1",+ channelId: "channel_1",+ forumParentChannelId: "forum_1",+ content: "hello",+ replyToId: "reply_1",+ mentionType: "user",+ attachments: uploaded,+ nonce: "nonce_upload",+ author: viewer,+ })+ expect(order).toEqual([+ "upload:a.png", "upload:b.txt", "zip", "vm:a1", "vm:a2", "dispatch", "send",+ ])+ })++ it("no-ops without a retry payload and retains stream state when send rejects", async () => {+ const uploadFileAsync = vi.fn()+ const sendMessageAsync = vi.fn()+ mocks.getRetryPayload.mockReturnValueOnce(undefined)+ await runAcceptedMessageIntent({+ messageScope: scope, nonce: "missing", uploadFileAsync, sendMessageAsync,+ channelId: "channel_1", serverId: "server_1", viewer,+ })+ expect(uploadFileAsync).not.toHaveBeenCalled()+ expect(sendMessageAsync).not.toHaveBeenCalled()+ expect(mocks.dispatch).not.toHaveBeenCalled()++ const failure = new Error("send failed")+ mocks.getRetryPayload.mockReturnValueOnce({+ localUploads: [],+ uploadStatus: "settled",+ message: { content: "keep optimistic" },+ })+ sendMessageAsync.mockRejectedValueOnce(failure)+ await expect(runAcceptedMessageIntent({+ messageScope: scope, nonce: "nonce_failed", uploadFileAsync, sendMessageAsync,+ channelId: "channel_1", serverId: "server_1", viewer,+ })).resolves.toBeUndefined()+ expect(sendMessageAsync).toHaveBeenCalledWith(expect.objectContaining({+ content: "keep optimistic",+ nonce: "nonce_failed",+ }))+ expect(mocks.dispatch).not.toHaveBeenCalled()+ expect(mocks.toastApiError).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/components/community/messages/message-channel-controller-send.ts b/src/web/src/components/community/messages/message-channel-controller-send.tsnew file mode 100644index 000000000..bbd3eee98--- /dev/null+++ b/src/web/src/components/community/messages/message-channel-controller-send.ts@@ -0,0 +1,187 @@+import type { MentionType } from "@alook/shared"+import type { SendAttachment } from "./composer"+import type { ReplyTarget, Viewer } from "./message-channel-controller-types"+import { toOptimisticReplyPreview } from "@/lib/community/reply-preview"+import {+ sendNonce,+ tempMessageId,+ toAttachmentVm,+ zipUploadResultsWithDimensions,+ type UploadedAttachment,+} from "@/hooks/community/mutations"+import { toastApiError } from "@/lib/api/client"+import { useMessageStreamStore } from "@/stores/community/message-stream"+import { communityWsResetTypingThrottle } from "@/hooks/community/use-community-ws"++type ChannelMessageScope = {+ kind: "channel"+ id: string+ serverId: string+}++type UploadFile = (input: {+ target: { channelId: string }+ file: File+ thumbnailBlob?: Blob+ width?: number+ height?: number+}) => Promise<UploadedAttachment>++type SendMessage = (input: {+ serverId: string+ channelId: string+ forumParentChannelId?: string+ content: string+ replyToId?: string+ mentionType?: MentionType+ attachments?: UploadedAttachment[]+ nonce: string+ author: Viewer+}) => Promise<unknown>++export async function runAcceptedMessageIntent({+ messageScope,+ nonce,+ uploadFileAsync,+ sendMessageAsync,+ channelId,+ forumParentChannelId,+ serverId,+ viewer,+}: {+ messageScope: ChannelMessageScope+ nonce: string+ uploadFileAsync: UploadFile+ sendMessageAsync: SendMessage+ channelId: string+ forumParentChannelId?: string+ serverId: string+ viewer: Viewer+}) {+ const streamStore = useMessageStreamStore.getState()+ const payload = streamStore.getRetryPayload(messageScope, nonce)+ if (!payload) return+ let uploadedAttachments: UploadedAttachment[] | undefined+ if (payload.localUploads.length > 0 && payload.uploadStatus === "settled") {+ const projected = payload.message.attachments+ if (projected?.length === payload.localUploads.length) {+ uploadedAttachments = projected.map((attachment, index) => {+ const local = payload.localUploads[index]+ return {+ id: attachment.url.slice(attachment.url.lastIndexOf("/") + 1),+ filename: local.file.name,+ contentType: local.file.type,+ size: local.file.size,+ ...(attachment.kind === "image" && attachment.thumbnailUrl !== undefined+ ? { hasThumbnail: true }+ : {}),+ width: local.width,+ height: local.height,+ }+ })+ }+ }+ if (payload.localUploads.length > 0 && !uploadedAttachments) {+ const results = await Promise.all(+ payload.localUploads.map((upload) =>+ uploadFileAsync({+ target: { channelId },+ file: upload.file,+ thumbnailBlob: upload.thumbnailBlob,+ width: upload.width,+ height: upload.height,+ }).catch((error) => {+ toastApiError(error, "Failed to attach file")+ return null+ }),+ ),+ )+ if (results.some((result) => result === null)) {+ streamStore.dispatch(messageScope, { type: "uploadFailed", nonce })+ return+ }+ uploadedAttachments = zipUploadResultsWithDimensions(+ results as UploadedAttachment[],+ [...payload.localUploads],+ )+ streamStore.dispatch(messageScope, {+ type: "uploadSettled",+ nonce,+ attachments: uploadedAttachments.map((attachment) => toAttachmentVm(channelId, attachment)),+ })+ }+ try {+ await sendMessageAsync({+ serverId,+ channelId,+ forumParentChannelId,+ content: payload.message.content ?? "",+ replyToId: payload.message.replyTo?.id,+ mentionType: payload.mentionType,+ attachments: uploadedAttachments,+ nonce,+ author: viewer,+ })+ } catch {+ return+ }+}++export function acceptChannelMessage({+ markdown,+ attachments,+ mentionType,+ messageScope,+ viewer,+ replyTo,+ runAcceptedIntent,+ channelId,+ clearReply,+}: {+ markdown: string+ attachments?: SendAttachment[]+ mentionType?: MentionType+ messageScope: ChannelMessageScope+ viewer: Viewer+ replyTo: ReplyTarget | null+ runAcceptedIntent: (nonce: string) => Promise<void>+ channelId: string+ clearReply: () => void+}): boolean {+ if (!markdown && !attachments?.length) return false+ const nonce = sendNonce()+ const createdPreviewUrls: string[] = []+ const accepted = useMessageStreamStore.getState().accept(messageScope, {+ nonce,+ tempId: tempMessageId(),+ message: {+ type: "chat",+ authorId: viewer.id,+ authorName: viewer.name,+ authorAvatar: viewer.avatar,+ content: markdown,+ createdAt: new Date().toISOString(),+ ...(replyTo ? { replyTo: toOptimisticReplyPreview(replyTo) } : {}),+ },+ localUploads: attachments?.map((attachment) => {+ const previewObjectUrl = attachment.previewObjectUrl ?? URL.createObjectURL(attachment.file)+ if (!attachment.previewObjectUrl) createdPreviewUrls.push(previewObjectUrl)+ return {+ file: attachment.file,+ thumbnailBlob: attachment.thumbnailBlob,+ previewObjectUrl,+ width: attachment.width,+ height: attachment.height,+ }+ }) ?? [],+ mentionType,+ })+ if (!accepted) {+ for (const url of createdPreviewUrls) URL.revokeObjectURL(url)+ return false+ }+ void runAcceptedIntent(nonce)+ communityWsResetTypingThrottle({ channelId })+ clearReply()+ return true+}diff --git a/src/web/src/components/community/messages/message-channel-controller-state.test.ts b/src/web/src/components/community/messages/message-channel-controller-state.test.tsnew file mode 100644index 000000000..3bd23aaac--- /dev/null+++ b/src/web/src/components/community/messages/message-channel-controller-state.test.ts@@ -0,0 +1,506 @@+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { useMessageChannelController } from "./message-channel-controller-state"+import { avatarInitial } from "@/lib/community/avatar"+import type {+ MessageChannelControllerProps,+} from "./message-channel-controller-types"+import type { MessageChannelControllerValue } from "./message-channel-controller"++const mocks = vi.hoisted(() => {+ const order: string[] = []+ const router = { replace: vi.fn() }+ const storeState = {+ pendingReply: null as null | { channelId: string; target: { id: string; authorName: string; text: string } },+ setPendingReply: vi.fn(),+ registerUiHandlers: vi.fn(),+ }+ 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(),+ onRetry: vi.fn(), onDismiss: vi.fn(), onPreviewImage: vi.fn(),+ onPreviewAttachment: vi.fn(), onDownloadFile: vi.fn(),+ }+ return {+ order,+ router,+ storeState,+ messageActions,+ apiFetch: vi.fn(),+ toastApiError: vi.fn(),+ sendTyping: vi.fn(),+ createActions: vi.fn((_input?: unknown) => messageActions),+ accept: vi.fn(() => true),+ run: vi.fn(async () => {}),+ seq: null as string | null,+ sendMutation: vi.fn(),+ reactionMutation: vi.fn(),+ 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[] },+ typingIds: ["u1"],+ typingNames: { u1: "Alice" },+ }+})++vi.mock("next/navigation", () => ({+ useRouter: () => mocks.router,+ useSearchParams: () => ({ get: (key: string) => key === "seq" ? mocks.seq : null }),+}))+vi.mock("@/lib/api/client", () => ({+ apiFetch: mocks.apiFetch,+ toastApiError: mocks.toastApiError,+}))+vi.mock("@/stores/community", () => {+ const useCommunityStore = Object.assign(+ (selector: (state: typeof mocks.storeState) => unknown) => {+ mocks.order.push("pending-store")+ return selector(mocks.storeState)+ },+ { getState: () => mocks.storeState },+ )+ return {+ useCommunityStore,+ useTypingUsersForScope: (scope: string) => {+ mocks.order.push("typing-users")+ mocks.typingScopes.users.push(scope)+ return mocks.typingIds+ },+ useTypingNamesForScope: (scope: string) => {+ mocks.order.push("typing-names")+ mocks.typingScopes.names.push(scope)+ return mocks.typingNames+ },+ }+})+vi.mock("@/hooks/community/mutations", () => ({+ useSendMessage: () => { mocks.order.push("send"); return { mutateAsync: mocks.sendMutation } },+ useToggleReactionApi: () => { mocks.order.push("reaction"); return mocks.reactionMutation },+ 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 } },+}))+vi.mock("@/hooks/community/use-community-ws", () => ({+ communityWsSendTyping: mocks.sendTyping,+}))+vi.mock("./message-channel-controller-actions", () => ({+ createMessageActions: mocks.createActions,+}))+vi.mock("./message-channel-controller-send", () => ({+ acceptChannelMessage: mocks.accept,+ runAcceptedMessageIntent: mocks.run,+}))++const feed = {+ messages: [{ id: "m1", seq: 1, type: "chat", authorName: "Alice", content: "hi" }],+ pinned: [],+ isError: false,+} as MessageChannelControllerProps["feed"]++function props(overrides: Partial<MessageChannelControllerProps> = {}): Omit<MessageChannelControllerProps, "children"> {+ return {+ channelId: "channel_1",+ serverId: "server_1",+ serverParam: "server_1",+ channelName: "general",+ viewer: { id: "viewer_1", name: "Viewer", avatar: "V" },+ anchorMessageId: "m1",+ feed,+ uiHandlers: {},+ onOpenThread: vi.fn(),+ onOpenPinned: vi.fn(),+ resolveUserName: (id) => id,+ ...overrides,+ }+}++let latest: MessageChannelControllerValue+function Probe({ value }: { value: Omit<MessageChannelControllerProps, "children"> }) {+ const controller = useMessageChannelController(value)+ React.useLayoutEffect(() => { latest = controller }, [controller])+ return null+}++function PassiveActionProbe({+ value,+}: {+ value: Omit<MessageChannelControllerProps, "children">+}) {+ const controller = useMessageChannelController(value)+ React.useLayoutEffect(() => { latest = controller }, [controller])+ React.useEffect(() => { controller.messageActions.onReply("probe") })+ return null+}++describe("useMessageChannelController", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mocks.order.length = 0+ mocks.seq = null+ mocks.storeState.pendingReply = null+ mocks.apiFetch.mockResolvedValue({ results: [] })+ mocks.createActions.mockImplementation(() => mocks.messageActions)+ mocks.typingScopes.users.length = 0+ mocks.typingScopes.names.length = 0+ mocks.typingIds = ["u1"]+ mocks.typingNames = { u1: "Alice" }+ })+ afterEach(() => vi.clearAllMocks())++ it("preserves mutation/selector hook order and final-value identity churn", async () => {+ const valueProps = props()+ let renderer: TestRenderer.ReactTestRenderer+ act(() => { renderer = TestRenderer.create(React.createElement(Probe, { value: valueProps })) })+ expect(mocks.order.slice(0, 11)).toEqual([+ "send", "reaction", "pin", "unpin", "mark", "edit", "thread", "upload",+ "typing-users", "typing-names", "pending-store",+ ])+ expect(mocks.typingScopes.users.length).toBeGreaterThan(0)+ expect(mocks.typingScopes.names.length).toBeGreaterThan(0)+ expect(mocks.typingScopes.users.every((scope) => scope === "ch:channel_1")).toBe(true)+ expect(mocks.typingScopes.names.every((scope) => scope === "ch:channel_1")).toBe(true)+ const firstValue = latest+ const firstActions = latest.messageActions+ const firstThreadActions = latest.threadActions+ const firstTyping = latest.handleTyping+ act(() => { renderer!.update(React.createElement(Probe, { value: valueProps })) })+ expect(latest).toBe(firstValue)+ expect(latest.threadActions).toBe(firstThreadActions)+ expect(latest.handleTyping).toBe(firstTyping)+ expect(latest.feed).toBe(valueProps.feed)++ await act(async () => { await (latest.search as (query: string) => Promise<void>)("hello") })+ expect(latest).not.toBe(firstValue)+ expect(latest.messageActions).toBe(firstActions)+ expect(latest.threadActions).not.toBe(firstThreadActions)+ expect(latest.handleTyping).not.toBe(firstTyping)+ act(() => latest.handleTyping())+ expect(mocks.sendTyping).toHaveBeenCalledWith({ channelId: "channel_1" })++ const afterSearch = latest+ const afterSearchThreadActions = latest.threadActions+ const afterSearchTyping = latest.handleTyping+ const updatedFeed = { ...feed, messages: [...feed.messages] }+ act(() => {+ renderer!.update(React.createElement(Probe, {+ value: { ...valueProps, feed: updatedFeed },+ }))+ })+ expect(latest).not.toBe(afterSearch)+ expect(latest.messageActions).toBe(firstActions)+ expect(latest.threadActions).not.toBe(afterSearchThreadActions)+ expect(latest.handleTyping).not.toBe(afterSearchTyping)+ expect(latest.feed).toBe(updatedFeed)++ const afterFeed = latest+ const latestOpenThread = vi.fn()+ act(() => {+ renderer!.update(React.createElement(Probe, {+ value: { ...valueProps, feed: updatedFeed, onOpenThread: latestOpenThread },+ }))+ })+ expect(latest).toBe(afterFeed)+ expect(latest.messageActions).toBe(firstActions)+ })++ it("keeps scroll target and lets a captured channel-one search complete after channel reset", async () => {+ let resolveOld: (value: unknown) => void = () => {}+ mocks.apiFetch.mockImplementationOnce(() => new Promise((resolve) => { resolveOld = resolve }))+ let renderer: TestRenderer.ReactTestRenderer+ act(() => { renderer = TestRenderer.create(React.createElement(Probe, { value: props() })) })+ let oldPromise: Promise<void>+ act(() => { oldPromise = (latest.search as (query: string) => Promise<void>)("old") })+ expect(mocks.apiFetch).toHaveBeenCalledWith(+ "/api/community/messages/search?q=old&channelId=channel_1",+ )+ act(() => latest.setReplyTo({ id: "r1", authorName: "A", text: "x" }))+ act(() => latest.setContextTarget({+ serverId: "server_1", channelId: "channel_1", label: "general", seq: 42,+ }))+ expect(latest.searchQuery).toBe("old")+ expect(latest.contextTarget?.seq).toBe(42)+ act(() => {+ renderer!.update(React.createElement(Probe, {+ value: props({ channelId: "channel_2", channelName: "random" }),+ }))+ })+ expect(latest.replyTo).toBeNull()+ expect(latest.searchQuery).toBe("")+ expect(latest.searchResults).toEqual([])+ expect(latest.contextTarget).toBeNull()+ expect(latest.scrollTargetId).toBe("m1")++ await act(async () => {+ resolveOld({ results: [{+ message: { id: "old_1", content: "old", authorId: "u1", createdAt: "2026-01-01" },+ author: { name: "Alice", image: null },+ }] })+ await oldPromise!+ })+ expect(latest.searchQuery).toBe("")+ expect(latest.searchResults).toEqual([{+ id: "old_1",+ type: "chat",+ authorName: "Alice",+ authorAvatar: avatarInitial("Alice"),+ content: "old",+ createdAt: "2026-01-01",+ }])+ await act(async () => { await (latest.search as (query: string) => Promise<void>)("") })+ expect(latest.searchResults).toEqual([])+ })++ it("forwards complete accept input, run-helper wiring, and helper-owned reply clearing", async () => {+ const reply = { id: "r1", authorName: "Alice", text: "reply" }+ const attachments = [{ file: {} as File }]+ act(() => {+ TestRenderer.create(React.createElement(Probe, {+ value: props({ forumParentChannelId: "forum_1" }),+ }))+ })+ act(() => latest.setReplyTo(reply))++ let accepted = false+ act(() => { accepted = latest.acceptMessage("hello", attachments, "everyone") })+ expect(accepted).toBe(true)+ expect(mocks.accept).toHaveBeenCalledWith({+ markdown: "hello",+ attachments,+ mentionType: "everyone",+ messageScope: { kind: "channel", id: "channel_1", serverId: "server_1" },+ viewer: { id: "viewer_1", name: "Viewer", avatar: "V" },+ replyTo: reply,+ runAcceptedIntent: expect.any(Function),+ channelId: "channel_1",+ clearReply: expect.any(Function),+ })+ const input = mocks.accept.mock.calls.at(-1)?.[0] as {+ clearReply: () => void+ runAcceptedIntent: (nonce: string) => Promise<void>+ }+ await act(async () => input.runAcceptedIntent("nonce_1"))+ expect(mocks.run).toHaveBeenCalledWith({+ messageScope: { kind: "channel", id: "channel_1", serverId: "server_1" },+ nonce: "nonce_1",+ uploadFileAsync: mocks.uploadMutation,+ sendMessageAsync: mocks.sendMutation,+ channelId: "channel_1",+ forumParentChannelId: "forum_1",+ serverId: "server_1",+ viewer: { id: "viewer_1", name: "Viewer", avatar: "V" },+ })+ act(() => input.clearReply())+ expect(latest.replyTo).toBeNull()+ })++ it("preserves pending/context/seq navigation and UI handler cleanup", () => {+ mocks.seq = "7"+ const navigate = vi.fn()+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(Probe, {+ value: props({ uiHandlers: { navigate } }),+ }))+ })+ expect(latest.contextTarget).toEqual({+ serverId: "server_1", channelId: "channel_1", label: "general", seq: 7,+ })+ expect(mocks.router.replace).toHaveBeenCalledWith(+ "/c/channels/server_1/channel_1", { scroll: false },+ )+ expect(mocks.storeState.registerUiHandlers).toHaveBeenCalledWith({+ jumpToSeq: expect.any(Function), openMessageContext: expect.any(Function),+ })++ act(() => latest.setContextTarget({+ serverId: "server_2", channelId: "channel_2", label: "other", seq: 2,+ }))+ act(() => latest.onSheetReply({ id: "r1", authorName: "Alice", text: "reply" }))+ expect(mocks.storeState.setPendingReply).toHaveBeenCalledWith({+ channelId: "channel_2",+ target: { id: "r1", authorName: "Alice", text: "reply" },+ })+ expect(navigate).toHaveBeenCalledWith("server_2", "channel_2")+ act(() => renderer!.unmount())+ expect(mocks.storeState.registerUiHandlers).toHaveBeenLastCalledWith({+ jumpToSeq: undefined, openMessageContext: undefined,+ })+ })++ it("clears missing anchors only on authoritative error and consumes only the matching target", () => {+ const missingFeed = { ...feed, messages: [], isError: false }+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(Probe, {+ value: props({ feed: missingFeed, anchorMessageId: "missing" }),+ }))+ })+ expect(latest.scrollTargetId).toBe("missing")+ act(() => {+ renderer!.update(React.createElement(Probe, {+ value: props({ feed: { ...missingFeed, isError: true }, anchorMessageId: "missing" }),+ }))+ })+ expect(latest.scrollTargetId).toBeNull()+ act(() => renderer!.unmount())++ act(() => {+ renderer = TestRenderer.create(React.createElement(Probe, { value: props() }))+ })+ act(() => latest.consumeScrollTarget("other"))+ expect(latest.scrollTargetId).toBe("m1")+ act(() => latest.consumeScrollTarget("m1"))+ expect(latest.scrollTargetId).toBeNull()+ })++ it("maps search avatars, reports failures, and retains the current unguarded completion race", async () => {+ const failure = new Error("search down")+ mocks.apiFetch+ .mockResolvedValueOnce({+ results: [+ {+ message: { id: "m2", content: "found", authorId: "u2", createdAt: "2026-01-02" },+ author: { name: "Bob", image: null },+ },+ {+ message: { id: "m3", content: "image", authorId: "u3", createdAt: "2026-01-03" },+ author: { name: "Carol", image: "https://example.test/carol.png" },+ },+ ],+ })+ .mockRejectedValueOnce(failure)+ act(() => { TestRenderer.create(React.createElement(Probe, { value: props() })) })+ await act(async () => { await (latest.search as (query: string) => Promise<void>)("found") })+ expect(mocks.apiFetch).toHaveBeenCalledWith(+ "/api/community/messages/search?q=found&channelId=channel_1",+ )+ expect(latest.searchResults).toEqual([+ {+ id: "m2",+ type: "chat",+ authorName: "Bob",+ authorAvatar: avatarInitial("Bob"),+ content: "found",+ createdAt: "2026-01-02",+ },+ {+ id: "m3",+ type: "chat",+ authorName: "Carol",+ authorAvatar: "https://example.test/carol.png",+ content: "image",+ createdAt: "2026-01-03",+ },+ ])+ await act(async () => { await (latest.search as (query: string) => Promise<void>)("broken") })+ expect(latest.searchResults).toEqual([])+ expect(mocks.toastApiError).toHaveBeenCalledWith(failure, "Search failed")+ })++ it("handles same-channel and pending replies plus loaded/fallback seq jumps", () => {+ const pendingTarget = { id: "pending", authorName: "Pending", text: "reply" }+ mocks.storeState.pendingReply = { channelId: "channel_1", target: pendingTarget }+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(Probe, { value: props() }))+ })+ expect(latest.replyTo).toEqual(pendingTarget)+ expect(mocks.storeState.setPendingReply).toHaveBeenCalledWith(null)++ act(() => latest.setContextTarget({+ serverId: "server_1", channelId: "channel_1", label: "general", seq: 1,+ }))+ const localTarget = { id: "local", authorName: "Local", text: "same" }+ act(() => latest.onSheetReply(localTarget))+ expect(latest.replyTo).toEqual(localTarget)+ expect(latest.contextTarget).toBeNull()++ act(() => latest.setScrollTargetId(null))+ act(() => latest.jumpToSeq(1))+ expect(latest.scrollTargetId).toBe("m1")+ act(() => latest.jumpToSeq(99))+ expect(latest.contextTarget).toEqual({+ serverId: "server_1", channelId: "channel_1", label: "general", seq: 99,+ })+ act(() => latest.openContextSeq(100))+ expect(latest.contextTarget?.seq).toBe(100)+ act(() => latest.setContextTarget(null))+ act(() => latest.openContextSeq(2))+ expect(latest.contextTarget).toEqual({+ serverId: "server_1", channelId: "channel_1", label: "general", seq: 2,+ })+ act(() => renderer!.unmount())+ })++ it("publishes the latest action context in layout before descendant passive actions", () => {+ mocks.createActions.mockImplementation((input) => {+ const { actionContext } = input as {+ actionContext: { current: { onOpenThread: (threadId: string) => void } }+ }+ return {+ ...mocks.messageActions,+ onReply: () => actionContext.current.onOpenThread("from-passive"),+ }+ })+ const first = vi.fn()+ const second = vi.fn()+ const valueProps = props({ onOpenThread: first })+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(PassiveActionProbe, { value: valueProps }))+ })+ expect(first).toHaveBeenCalledWith("from-passive")+ const firstActions = latest.messageActions+ act(() => {+ renderer!.update(React.createElement(PassiveActionProbe, {+ value: { ...valueProps, onOpenThread: second },+ }))+ })+ expect(second).toHaveBeenCalledWith("from-passive")+ expect(latest.messageActions).toBe(firstActions)+ })++ it("ignores non-finite seq params and projects the exact public value surface", () => {+ mocks.seq = "not-a-number"+ mocks.typingIds = ["u1", "u2"]+ mocks.typingNames = { u1: "Alice" }+ const resolveUserName = vi.fn((id: string) => `resolved:${id}`)+ const projectedFeed = { ...feed, pinned: [{ ...feed.messages[0], id: "p1" }] }+ act(() => {+ TestRenderer.create(React.createElement(Probe, {+ value: props({+ feed: projectedFeed,+ resolveUserName,+ }),+ }))+ })+ expect(mocks.router.replace).not.toHaveBeenCalled()+ expect(latest.contextTarget).toBeNull()+ expect(latest.pinnedIds).toEqual(new Set(["p1"]))+ expect(latest.typingUsers).toEqual(["Alice", "resolved:u2"])+ expect(latest.feed).toBe(projectedFeed)+ expect(resolveUserName).toHaveBeenCalledWith("u2")+ expect(Object.keys(latest)).toEqual([+ "feed", "pinnedIds", "replyTo", "setReplyTo", "searchQuery", "searchResults",+ "search", "scrollTargetId", "setScrollTargetId", "consumeScrollTarget",+ "contextTarget", "setContextTarget", "openContextSeq", "onSheetReply", "jumpToSeq",+ "messageActions", "threadActions", "acceptMessage", "handleTyping", "typingUsers",+ ])+ const actionKeys = [+ "onToggleReaction", "onReact", "onReply", "onPin", "onMark", "onCreateThread",+ "onCopy", "onEdit", "onRetry", "onDismiss", "onPreviewImage",+ "onPreviewAttachment", "onDownloadFile",+ ]+ expect(Object.keys(latest.messageActions)).toEqual(actionKeys)+ expect(Object.keys(latest.threadActions)).toEqual(actionKeys)+ expect(latest.threadActions.onCreateThread).toBeUndefined()+ })+})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.tsnew file mode 100644index 000000000..0d59d2844--- /dev/null+++ b/src/web/src/components/community/messages/message-channel-controller-state.ts@@ -0,0 +1,307 @@+"use client"++import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"+import { useRouter, useSearchParams } from "next/navigation"+import type { MentionType } from "@alook/shared"+import { apiFetch, toastApiError } from "@/lib/api/client"+import { avatarInitial } from "@/lib/community/avatar"+import type { Msg } from "@/lib/community/models/message"+import type { SendAttachment } from "./composer"+import {+ useCommunityStore,+ useTypingNamesForScope,+ useTypingUsersForScope,+} from "@/stores/community"+import {+ useCreateThread,+ useEditMessage,+ usePinMessage,+ useSendMessage,+ useToggleMark,+ useToggleReactionApi,+ useUnpinMessage,+ useUploadFile,+} from "@/hooks/community/mutations"+import { communityWsSendTyping } from "@/hooks/community/use-community-ws"+import {+ createMessageActions,+ type MessageActionContext,+} from "./message-channel-controller-actions"+import {+ acceptChannelMessage,+ runAcceptedMessageIntent,+} from "./message-channel-controller-send"+import type {+ MessageChannelControllerProps,+ MessageChannelControllerValue,+ MessageContextTarget,+ ReplyTarget,+} from "./message-channel-controller-types"++export function useMessageChannelController({+ channelId,+ serverId,+ serverParam,+ channelName,+ forumParentChannelId,+ viewer,+ anchorMessageId,+ feed,+ uiHandlers,+ onOpenThread,+ onOpenPinned,+ resolveUserName,+}: Omit<MessageChannelControllerProps, "children">): MessageChannelControllerValue {+ const router = useRouter()+ const searchParams = useSearchParams()+ const [replyTo, setReplyTo] = useState<ReplyTarget | null>(null)+ const [searchQuery, setSearchQuery] = useState("")+ const [searchResults, setSearchResults] = useState<Msg[]>([])+ const [scrollTargetId, setScrollTargetId] = useState<string | null>(anchorMessageId)+ const [contextTarget, setContextTarget] = useState<MessageContextTarget | null>(null)+ const { mutateAsync: sendMessageAsync } = useSendMessage()+ const toggleReactionApi = useToggleReactionApi()+ 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}`)+ const typingNames = useTypingNamesForScope(`ch:${channelId}`)+ const pinnedIds = useMemo(+ () => new Set(feed.pinned.map((message) => message.id)),+ [feed.pinned],+ )+ const consumeScrollTarget = useCallback((targetId: string) => {+ setScrollTargetId((current) => (current === targetId ? null : current))+ }, [])++ useEffect(() => {+ if (!scrollTargetId) return+ if (feed.messages.some((message) => message.id === scrollTargetId)) return+ if (feed.isError) {+ setScrollTargetId((current) => (current === scrollTargetId ? null : current))+ }+ }, [scrollTargetId, feed.messages, feed.isError])++ useEffect(() => {+ setReplyTo(null)+ setSearchQuery("")+ setSearchResults([])+ setContextTarget(null)+ }, [channelId])++ const search = useCallback(async (query: string) => {+ setSearchQuery(query)+ if (!query.trim()) {+ setSearchResults([])+ return+ }+ try {+ const params = new URLSearchParams({ q: query, channelId })+ const data = await apiFetch<{+ results: Array<{+ message: { id: string; content: string; authorId: string; createdAt: string }+ author: { name: string; image: string | null }+ }>+ }>(`/api/community/messages/search?${params}`)+ setSearchResults(data.results.map((result) => ({+ id: result.message.id,+ type: "chat" as const,+ authorName: result.author.name,+ authorAvatar: result.author.image ?? avatarInitial(result.author.name),+ content: result.message.content,+ createdAt: result.message.createdAt,+ })))+ } catch (error) {+ setSearchResults([])+ toastApiError(error, "Search failed")+ }+ }, [channelId])++ const openContextSeq = useCallback((seq: number) => {+ setContextTarget((current) => (+ current ? { ...current, seq } : { serverId, channelId, label: channelName, seq }+ ))+ }, [serverId, channelId, channelName])++ const onSheetReply = useCallback((target: ReplyTarget) => {+ if (contextTarget && contextTarget.channelId !== channelId) {+ useCommunityStore.getState().setPendingReply({ channelId: contextTarget.channelId, target })+ setContextTarget(null)+ uiHandlers.navigate?.(contextTarget.serverId, contextTarget.channelId)+ return+ }+ setReplyTo(target)+ setContextTarget(null)+ }, [contextTarget, channelId, uiHandlers])++ const pendingReply = useCommunityStore((state) => state.pendingReply)+ useEffect(() => {+ if (!pendingReply || pendingReply.channelId !== channelId) return+ setReplyTo(pendingReply.target)+ useCommunityStore.getState().setPendingReply(null)+ }, [pendingReply, channelId])++ const actionContext = useRef<MessageActionContext>({+ messages: feed.messages,+ pinnedIds,+ channelName,+ uiHandlers,+ onOpenThread,+ onOpenPinned,+ })+ useLayoutEffect(() => {+ actionContext.current = {+ messages: feed.messages,+ pinnedIds,+ channelName,+ uiHandlers,+ onOpenThread,+ onOpenPinned,+ }+ }, [feed.messages, pinnedIds, channelName, uiHandlers, onOpenThread, onOpenPinned])++ const jumpToSeq = useCallback((seq: number) => {+ const message = actionContext.current.messages.find((item) => item.seq === seq)+ if (message) setScrollTargetId(message.id)+ else setContextTarget({ serverId, channelId, label: channelName, seq })+ }, [serverId, channelId, channelName])++ const openMessageContext = useCallback((target: MessageContextTarget) => {+ setContextTarget(target)+ }, [])++ useEffect(() => {+ useCommunityStore.getState().registerUiHandlers({ jumpToSeq, openMessageContext })+ return () => useCommunityStore.getState().registerUiHandlers({+ jumpToSeq: undefined,+ openMessageContext: undefined,+ })+ }, [jumpToSeq, openMessageContext])++ const seqParam = searchParams.get("seq")+ useEffect(() => {+ if (!seqParam) return+ const seq = Number(seqParam)+ if (!Number.isFinite(seq)) return+ setContextTarget({ serverId, channelId, label: channelName, seq })+ router.replace(`/c/channels/${serverParam}/${channelId}`, { scroll: false })+ }, [seqParam, serverId, channelId, channelName, router, serverParam])++ const messageScope = useMemo(+ () => ({ kind: "channel" as const, id: channelId, serverId }),+ [channelId, serverId],+ )++ const runAcceptedIntent = useCallback(async (nonce: string) => {+ await runAcceptedMessageIntent({+ messageScope,+ nonce,+ uploadFileAsync,+ sendMessageAsync,+ channelId,+ forumParentChannelId,+ serverId,+ viewer: { id: viewer.id, name: viewer.name, avatar: viewer.avatar },+ })+ }, [+ messageScope,+ uploadFileAsync,+ channelId,+ forumParentChannelId,+ sendMessageAsync,+ serverId,+ viewer.id,+ viewer.name,+ viewer.avatar,+ ])++ // eslint-disable-next-line react-hooks/refs -- helper closes over the ref; current is read only by user actions+ const messageActions = useMemo(() => createMessageActions({+ actionContext,+ serverId,+ channelId,+ viewerUserId: viewer.id,+ setReplyTo,+ toggleReactionApi,+ unpinMessageMutate,+ pinMessageMutate,+ toggleMark,+ createThreadAsync,+ editMessage,+ messageScope,+ runAcceptedIntent,+ }), [+ channelId,+ serverId,+ viewer.id,+ toggleReactionApi,+ unpinMessageMutate,+ pinMessageMutate,+ toggleMark,+ createThreadAsync,+ editMessage,+ messageScope,+ runAcceptedIntent,+ ])++ const acceptMessage = useCallback((+ markdown: string,+ attachments?: SendAttachment[],+ mentionType?: MentionType,+ ): boolean => acceptChannelMessage({+ markdown,+ attachments,+ mentionType,+ messageScope,+ viewer: { id: viewer.id, name: viewer.name, avatar: viewer.avatar },+ replyTo,+ runAcceptedIntent,+ channelId,+ clearReply: () => setReplyTo(null),+ }), [channelId, messageScope, replyTo, runAcceptedIntent, viewer.avatar, viewer.id, viewer.name])++ return useMemo<MessageChannelControllerValue>(() => ({+ feed,+ pinnedIds,+ replyTo,+ setReplyTo,+ searchQuery,+ searchResults,+ search,+ scrollTargetId,+ setScrollTargetId,+ consumeScrollTarget,+ contextTarget,+ setContextTarget,+ openContextSeq,+ onSheetReply,+ jumpToSeq,+ messageActions,+ threadActions: { ...messageActions, onCreateThread: undefined },+ acceptMessage,+ handleTyping: () => communityWsSendTyping({ channelId }),+ typingUsers: typingUserIds.map((id) => typingNames[id] ?? resolveUserName(id)),+ }), [+ feed,+ pinnedIds,+ replyTo,+ searchQuery,+ searchResults,+ search,+ scrollTargetId,+ consumeScrollTarget,+ contextTarget,+ openContextSeq,+ onSheetReply,+ jumpToSeq,+ messageActions,+ acceptMessage,+ channelId,+ typingUserIds,+ typingNames,+ resolveUserName,+ ])+}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.tsnew file mode 100644index 000000000..eb7c87cbe--- /dev/null+++ b/src/web/src/components/community/messages/message-channel-controller-types.ts@@ -0,0 +1,91 @@+import type { ReactNode } from "react"+import type { MentionType } from "@alook/shared"+import type { FileAttachment, ImagePreview, Msg } from "@/lib/community/models/message"+import type { SendAttachment } from "./composer"+import type { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"++type MessageFeed = ReturnType<typeof useChannelMessageFeed>++export type Viewer = {+ id: string+ name: string+ avatar: string+}++export type MessageUiHandlers = {+ navigate?: (serverId: string, channelId: string) => void+ previewImage?: (image: ImagePreview) => void+ previewAttachment?: (attachment: FileAttachment) => void+}++export type ReplyTarget = {+ id: string+ authorName: string+ text: string+}++export type MessageContextTarget = {+ serverId: string+ channelId: string+ label: string+ seq: number+}++export type MessageActions = {+ onToggleReaction: (id: string, emoji: string) => void+ onReact: (id: string, emoji: string) => void+ onReply: (id: string) => void+ onPin: (id: string) => void+ 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+ onPreviewAttachment: (attachment: FileAttachment) => void+ onDownloadFile: (url: string, name: string) => void+}++export type MessageChannelControllerValue = {+ feed: MessageFeed+ pinnedIds: Set<string>+ replyTo: ReplyTarget | null+ setReplyTo: (reply: ReplyTarget | null) => void+ searchQuery: string+ searchResults: Msg[]+ search: (query: string) => void+ scrollTargetId: string | null+ setScrollTargetId: (targetId: string | null) => void+ consumeScrollTarget: (targetId: string) => void+ contextTarget: MessageContextTarget | null+ setContextTarget: (target: MessageContextTarget | null) => void+ openContextSeq: (seq: number) => void+ onSheetReply: (target: ReplyTarget) => void+ jumpToSeq: (seq: number) => void+ messageActions: MessageActions+ threadActions: Omit<MessageActions, "onCreateThread"> & { onCreateThread: undefined }+ acceptMessage: (+ markdown: string,+ attachments?: SendAttachment[],+ mentionType?: MentionType,+ ) => boolean+ handleTyping: () => void+ typingUsers: string[]+}++export type MessageChannelControllerProps = {+ channelId: string+ serverId: string+ serverParam: string+ channelName: string+ forumParentChannelId?: string+ viewer: Viewer+ anchorMessageId: string | null+ feed: MessageFeed+ uiHandlers: MessageUiHandlers+ onOpenThread: (threadId: string) => void+ onOpenPinned: () => void+ resolveUserName: (userId: string) => string+ children: (controller: MessageChannelControllerValue) => ReactNode+}diff --git a/src/web/src/components/community/messages/message-channel-controller-view.test.ts b/src/web/src/components/community/messages/message-channel-controller-view.test.tsnew file mode 100644index 000000000..4ecae254e--- /dev/null+++ b/src/web/src/components/community/messages/message-channel-controller-view.test.ts@@ -0,0 +1,14 @@+import { describe, expect, it, vi } from "vitest"+import { renderMessageChannelController } from "./message-channel-controller-view"+import type { MessageChannelControllerValue } from "./message-channel-controller-types"++describe("renderMessageChannelController", () => {+ it("calls the render prop once with the identical value and returns its node directly", () => {+ const value = { feed: {} } as MessageChannelControllerValue+ const node = { kind: "sentinel" }+ const children = vi.fn(() => node)+ expect(renderMessageChannelController(children, value)).toBe(node)+ expect(children).toHaveBeenCalledOnce()+ expect(children).toHaveBeenCalledWith(value)+ })+})diff --git a/src/web/src/components/community/messages/message-channel-controller-view.ts b/src/web/src/components/community/messages/message-channel-controller-view.tsnew file mode 100644index 000000000..da4b806db--- /dev/null+++ b/src/web/src/components/community/messages/message-channel-controller-view.ts@@ -0,0 +1,9 @@+import type { ReactNode } from "react"+import type { MessageChannelControllerValue } from "./message-channel-controller-types"++export function renderMessageChannelController(+ children: (controller: MessageChannelControllerValue) => ReactNode,+ value: MessageChannelControllerValue,+) {+ return children(value)+}diff --git a/src/web/src/components/community/messages/message-channel-controller.tsx b/src/web/src/components/community/messages/message-channel-controller.tsxnew file mode 100644index 000000000..a6b201ba4--- /dev/null+++ b/src/web/src/components/community/messages/message-channel-controller.tsx@@ -0,0 +1,31 @@+"use client"++import { useMessageChannelController } from "./message-channel-controller-state"+import type {+ MessageChannelControllerProps,+ MessageChannelControllerValue,+} from "./message-channel-controller-types"+import { renderMessageChannelController } from "./message-channel-controller-view"++export type { MessageChannelControllerValue } from "./message-channel-controller-types"++type ComposerSendAttachment = import("./composer").SendAttachment+type MessageChannelControllerFacadeProps = Omit<MessageChannelControllerProps, "children"> & {+ children: (+ controller: Omit<MessageChannelControllerValue, "acceptMessage"> & {+ acceptMessage: (+ markdown: string,+ attachments?: ComposerSendAttachment[],+ mentionType?: Parameters<MessageChannelControllerValue["acceptMessage"]>[2],+ ) => boolean+ },+ ) => ReturnType<MessageChannelControllerProps["children"]>+}++export function MessageChannelController({+ children,+ ...props+}: MessageChannelControllerFacadeProps) {+ const value = useMessageChannelController(props)+ return renderMessageChannelController(children, value)+}diff --git a/src/web/src/components/community/message-context-sheet-header.test.ts b/src/web/src/components/community/messages/message-context-sheet-header.test.tssimilarity index 100%rename from src/web/src/components/community/message-context-sheet-header.test.tsrename to src/web/src/components/community/messages/message-context-sheet-header.test.tsdiff --git a/src/web/src/components/community/message-context-sheet.tsx b/src/web/src/components/community/messages/message-context-sheet.tsxsimilarity index 98%rename from src/web/src/components/community/message-context-sheet.tsxrename to src/web/src/components/community/messages/message-context-sheet.tsxindex 4fad7e8ba..ad3108335 100644--- a/src/web/src/components/community/message-context-sheet.tsx+++ b/src/web/src/components/community/messages/message-context-sheet.tsx@@ -9,17 +9,17 @@ import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/shimport { useSheetResize, SheetResizeHandle } from "@/components/ui/sheet-resize-handle"import { MessageRow } from "./message-row"import { MessageShareDialog } from "./message-share-dialog"-import { ChannelIcon } from "./channel-icon"+import { ChannelIcon } from "../channels/channel-icon"import { Skeleton } from "@/components/ui/skeleton"import { apiFetch, toastApiError } from "@/lib/api/client"import { ApiError } from "@/lib/errors"-import { formatDateLabel } from "./format-time"-import { DateDivider } from "./dividers"+import { formatDateLabel } from "@/lib/community/format-time"+import { DateDivider } from "../dividers"import { useCurrentUser } from "@/contexts/community/current-user"import { useUiHandlers } from "@/stores/community"import { usePinMessage, useUnpinMessage, useCreateThread, useToggleMark } from "@/hooks/community/mutations"-import type { FileAttachment, ImagePreview, Msg, OpenProfile, Reaction, RenderMsg } from "./_types"-import type { MessagesPage } from "@/hooks/community/use-messages"+import type { FileAttachment, ImagePreview, MessagesPage, Msg, Reaction, RenderMsg } from "@/lib/community/models/message"+import type { OpenProfile } from "@/components/community/social/profile-types"export type ReplyTarget = { id: string; authorName: string; text: string }diff --git a/src/web/src/components/community/messages/message-list-controller.test.ts b/src/web/src/components/community/messages/message-list-controller.test.tsnew file mode 100644index 000000000..b3336ea37--- /dev/null+++ b/src/web/src/components/community/messages/message-list-controller.test.ts@@ -0,0 +1,525 @@+import React from "react"+import { readFileSync } from "node:fs"+import { dirname, resolve } from "node:path"+import { fileURLToPath } from "node:url"+import TestRenderer, { act } from "react-test-renderer"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { useMessageListController, type MessageListController } from "./message-list-controller"+import type { ResolvedMessageListProps } from "./message-list-types"++const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..")+const readWebSource = (path: string) => readFileSync(resolve(webRoot, path), "utf8")++const mocks = vi.hoisted(() => ({+ hookOrder: [] as string[],+ scrollInputs: [] as unknown[],+ sentinelInputs: [] as unknown[],+ sentinelRefs: [] as Array<{ current: null }>,+ scrollRef: { current: null as HTMLDivElement | null },+ virtualizer: {},+ jumpToIndex: vi.fn(),+ scrollToBottom: vi.fn(),+ onImageLoad: vi.fn(),+}))++vi.mock("@/hooks/community/use-scroll-anchor", () => ({+ useScrollAnchor: (input: unknown) => {+ mocks.hookOrder.push("anchor")+ mocks.scrollInputs.push(input)+ return {+ scrollRef: mocks.scrollRef,+ virtualizer: mocks.virtualizer,+ belowCount: 2,+ scrollToBottom: mocks.scrollToBottom,+ jumpTo: mocks.jumpToIndex,+ onImageLoad: mocks.onImageLoad,+ }+ },+}))+vi.mock("@/hooks/community/use-virtual-cursor-sentinel", () => ({+ useVirtualCursorSentinel: (input: { edge: string }) => {+ mocks.hookOrder.push(input.edge)+ mocks.sentinelInputs.push(input)+ const ref = { current: null }+ mocks.sentinelRefs.push(ref)+ return ref+ },+}))++const baseMessage = {+ id: "m1",+ type: "chat" as const,+ authorId: "u1",+ authorName: "Alice",+ content: "one",+ createdAt: new Date(0).toISOString(),+}++function props(overrides: Partial<ResolvedMessageListProps> = {}): ResolvedMessageListProps {+ return {+ channel: "general",+ messages: [baseMessage],+ onOpenThread: vi.fn(),+ variant: "channel",+ initialScrollReady: true,+ ...overrides,+ }+}++let latest: MessageListController+function Probe({+ value,+ attachHero = true,+}: {+ value: ResolvedMessageListProps+ attachHero?: boolean+}) {+ const controller = useMessageListController(value)+ React.useLayoutEffect(() => { latest = controller }, [controller])+ return React.createElement(+ React.Fragment,+ null,+ attachHero ? React.createElement("div", { id: "hero", ref: controller.heroRef }) : null,+ React.createElement("div", { id: "scroll", ref: controller.scrollRef }),+ )+}++describe("useMessageListController", () => {+ let resizeCallback: ((entries: Array<{ borderBoxSize?: Array<{ blockSize: number }> }>) => void) | null+ let nextFrameId: number+ let frameCallbacks: Map<number, FrameRequestCallback>+ let requestFrame: ReturnType<typeof vi.fn>+ let cancelFrame: ReturnType<typeof vi.fn>+ let visibleMessageIds: string[]+ const disconnect = vi.fn()+ const heroNode = { offsetHeight: 0 }+ const scrollNode = {+ querySelectorAll: () => visibleMessageIds.map((id) => ({+ dataset: { msgId: id },+ getBoundingClientRect: () => ({ top: 10, bottom: 20 }),+ })),+ getBoundingClientRect: () => ({ top: 0, bottom: 100 }),+ }++ beforeEach(() => {+ resizeCallback = null+ disconnect.mockClear()+ mocks.hookOrder.length = 0+ mocks.scrollInputs.length = 0+ mocks.sentinelInputs.length = 0+ mocks.sentinelRefs.length = 0+ mocks.scrollRef.current = null+ mocks.jumpToIndex.mockClear()+ mocks.scrollToBottom.mockClear()+ nextFrameId = 0+ frameCallbacks = new Map()+ visibleMessageIds = ["m1"]+ heroNode.offsetHeight = 0+ requestFrame = vi.fn((callback: FrameRequestCallback) => {+ const id = ++nextFrameId+ frameCallbacks.set(id, callback)+ return id+ })+ cancelFrame = vi.fn((id: number) => frameCallbacks.delete(id))+ vi.useFakeTimers()+ vi.stubGlobal("ResizeObserver", class {+ constructor(callback: typeof resizeCallback) { resizeCallback = callback }+ observe() {}+ disconnect() { disconnect() }+ })+ vi.stubGlobal("window", {+ setTimeout,+ requestAnimationFrame: requestFrame,+ cancelAnimationFrame: cancelFrame,+ })+ })++ afterEach(() => {+ vi.useRealTimers()+ vi.unstubAllGlobals()+ })++ const createNodeMock = (element: { props?: { id?: string } }) => (+ element.props?.id === "hero" ? heroNode : scrollNode+ )++ const runNextFrame = () => {+ const entry = frameCallbacks.entries().next().value as [number, FrameRequestCallback] | undefined+ if (!entry) throw new Error("expected a pending animation frame")+ frameCallbacks.delete(entry[0])+ act(() => entry[1](0))+ return entry[0]+ }++ it("uses the exact loading predicate and calls anchor/start/end hooks unconditionally in order", () => {+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(Probe, { value: props({ loading: true }) }),+ { createNodeMock },+ )+ })+ expect(latest.isLoading).toBe(false)+ expect(mocks.hookOrder.slice(0, 3)).toEqual(["anchor", "start", "end"])+ expect(mocks.scrollInputs[0]).toEqual({+ items: expect.any(Array),+ newDividerBefore: undefined,+ initialScrollReady: true,+ hasMoreNewer: undefined,+ presentVersion: undefined,+ viewerUserId: undefined,+ heroHeight: 0,+ heroMeasured: false,+ })+ expect(mocks.sentinelInputs.slice(0, 2)).toEqual([+ {+ scrollRef: mocks.scrollRef,+ hasMore: undefined,+ isFetching: undefined,+ onLoad: undefined,+ edge: "start",+ },+ {+ scrollRef: mocks.scrollRef,+ hasMore: undefined,+ isFetching: undefined,+ onLoad: undefined,+ edge: "end",+ },+ ])+ expect(latest.scrollRef).toBe(mocks.scrollRef)+ expect(latest.virtualizer).toBe(mocks.virtualizer)+ expect(latest.topSentinelRef).toBe(mocks.sentinelRefs.at(-2))+ expect(latest.bottomSentinelRef).toBe(mocks.sentinelRefs.at(-1))+ expect(latest.onImageLoad).toBe(mocks.onImageLoad)+ expect(latest.pillCount).toBe(2)+ expect(latest.pillMode).toBe("scroll")+ expect(latest.pillOnClick).toBe(mocks.scrollToBottom)+ act(() => {+ renderer!.update(React.createElement(Probe, {+ value: props({ loading: true, messages: [] }),+ }))+ })+ expect(latest.isLoading).toBe(true)+ expect(mocks.hookOrder.slice(-3)).toEqual(["anchor", "start", "end"])+ })++ it("passes every pagination/anchor input through and gives jump mode server-count precedence", () => {+ const loadOlder = vi.fn()+ const loadNewer = vi.fn()+ const jumpToPresent = vi.fn()+ act(() => {+ TestRenderer.create(React.createElement(Probe, {+ value: props({+ newDividerBefore: "m1",+ initialScrollReady: false,+ hasMore: true,+ isFetchingOlder: true,+ onLoadOlder: loadOlder,+ hasMoreNewer: true,+ isFetchingNewer: true,+ onLoadNewer: loadNewer,+ onJumpToPresent: jumpToPresent,+ presentVersion: 7,+ unreadCount: 9,+ viewerUserId: "viewer_1",+ }),+ }), { createNodeMock })+ })+ expect(mocks.scrollInputs.at(-1)).toEqual({+ items: expect.any(Array),+ newDividerBefore: "m1",+ initialScrollReady: false,+ hasMoreNewer: true,+ presentVersion: 7,+ viewerUserId: "viewer_1",+ heroHeight: 0,+ heroMeasured: true,+ })+ expect(mocks.sentinelInputs.slice(-2)).toEqual([+ {+ scrollRef: mocks.scrollRef,+ hasMore: true,+ isFetching: true,+ onLoad: loadOlder,+ edge: "start",+ },+ {+ scrollRef: mocks.scrollRef,+ hasMore: true,+ isFetching: true,+ onLoad: loadNewer,+ edge: "end",+ },+ ])+ expect(latest.pillCount).toBe(9)+ expect(latest.pillMode).toBe("jump")+ expect(latest.pillOnClick).toBe(jumpToPresent)+ act(() => latest.pillOnClick())+ expect(jumpToPresent).toHaveBeenCalledOnce()+ })++ it("publishes scroll roots cleanup-first and measures zero-height heroes immediately", () => {+ const first = vi.fn()+ const second = vi.fn()+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(Probe, { value: props({ onScrollRoot: first }) }),+ { createNodeMock },+ )+ })+ expect((mocks.scrollInputs.at(-1) as { heroHeight: number; heroMeasured: boolean }))+ .toEqual(expect.objectContaining({ heroHeight: 0, heroMeasured: true }))+ expect(first).toHaveBeenCalledWith(scrollNode)++ act(() => {+ renderer!.update(React.createElement(Probe, { value: props({ onScrollRoot: second }) }))+ })+ expect(first.mock.calls.at(-1)).toEqual([null])+ expect(second).toHaveBeenCalledWith(scrollNode)+ expect(first.mock.invocationCallOrder.at(-1)!).toBeLessThan(second.mock.invocationCallOrder[0])++ act(() => resizeCallback?.([{ borderBoxSize: [{ blockSize: 42 }] }]))+ expect((mocks.scrollInputs.at(-1) as { heroHeight: number; heroMeasured: boolean }))+ .toEqual(expect.objectContaining({ heroHeight: 42, heroMeasured: true }))+ heroNode.offsetHeight = 17+ act(() => resizeCallback?.([{}]))+ expect((mocks.scrollInputs.at(-1) as { heroHeight: number; heroMeasured: boolean }))+ .toEqual(expect.objectContaining({ heroHeight: 17, heroMeasured: true }))+ act(() => {+ renderer!.update(React.createElement(Probe, {+ value: props({ loading: true, messages: [], onScrollRoot: second, hero: "changed" }),+ }))+ })+ expect((mocks.scrollInputs.at(-1) as { heroMeasured: boolean }).heroMeasured).toBe(true)+ act(() => renderer!.unmount())+ expect(disconnect).toHaveBeenCalled()+ })++ it("combines initial readiness with loaded-target readiness and preserves state across channel-only changes", () => {+ const consumed = vi.fn()+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(Probe, {+ value: props({ scrollToMessageId: "m2", onScrollTargetConsumed: consumed }),+ }), { createNodeMock })+ })+ expect((mocks.scrollInputs.at(-1) as { initialScrollReady: boolean }).initialScrollReady).toBe(false)+ act(() => {+ renderer!.update(React.createElement(Probe, {+ value: props({+ messages: [baseMessage, { ...baseMessage, id: "m2" }],+ scrollToMessageId: "m2",+ onScrollTargetConsumed: consumed,+ }),+ }))+ })+ expect((mocks.scrollInputs.at(-1) as { initialScrollReady: boolean }).initialScrollReady).toBe(true)+ expect(consumed).toHaveBeenCalledOnce()+ visibleMessageIds = ["m2"]+ runNextFrame()+ act(() => {+ latest.onEnterSelectId("m2")+ latest.setShareOpen(true)+ })+ expect(latest.jumped).toBe("m2")+ expect(latest.selectedIds).toEqual(new Set(["m2"]))+ expect(latest.shareOpen).toBe(true)++ act(() => {+ renderer!.update(React.createElement(Probe, {+ value: props({+ channel: "random",+ messages: [baseMessage, { ...baseMessage, id: "m2" }],+ scrollToMessageId: "m2",+ onScrollTargetConsumed: consumed,+ }),+ }))+ })+ expect(latest.jumped).toBe("m2")+ expect(latest.selectedIds).toEqual(new Set(["m2"]))+ expect(latest.shareOpen).toBe(true)+ expect(consumed).toHaveBeenCalledOnce()++ act(() => latest.closeShare())+ expect(latest.shareOpen).toBe(false)+ expect(latest.selectMode).toBe(false)+ expect(latest.selectedIds).toEqual(new Set())++ act(() => {+ renderer!.update(React.createElement(Probe, {+ value: props({ initialScrollReady: false, scrollToMessageId: null }),+ }))+ })+ expect((mocks.scrollInputs.at(-1) as { initialScrollReady: boolean }).initialScrollReady).toBe(false)+ act(() => {+ renderer!.update(React.createElement(Probe, {+ value: props({+ messages: [baseMessage, { ...baseMessage, id: "m2" }],+ scrollToMessageId: "m2",+ onScrollTargetConsumed: consumed,+ }),+ }))+ })+ expect(consumed).toHaveBeenCalledTimes(2)+ })++ it("keeps selected-message regrouping asymmetric around replies", () => {+ const reply = { ...baseMessage, id: "reply", replyTo: { id: "p", authorName: "P", text: "x" } }+ const ordinary = { ...baseMessage, id: "ordinary", createdAt: new Date(1000).toISOString() }+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(Probe, { value: props({ messages: [reply, ordinary] }) }),+ { createNodeMock },+ )+ })+ act(() => {+ latest.onEnterSelectId("reply")+ latest.onToggleSelectId("ordinary")+ })+ expect(latest.selectedMessages.map((message) => [message.id, message.grouped]))+ .toEqual([["reply", false], ["ordinary", true]])++ act(() => {+ renderer!.update(React.createElement(Probe, {+ value: props({ messages: [ordinary, reply] }),+ }))+ latest.onEnterSelectId("ordinary")+ latest.onToggleSelectId("reply")+ })+ expect(latest.selectedMessages.map((message) => [message.id, message.grouped]))+ .toEqual([["ordinary", false], ["reply", false]])+ })++ it("closes the share dialog before exiting selection mode", () => {+ const source = readWebSource(+ "src/components/community/messages/message-list-controller.ts",+ )+ const closeShare = source.slice(+ source.indexOf("const closeShare = useCallback"),+ source.indexOf("return {", source.indexOf("const closeShare = useCallback")),+ )+ expect(closeShare.indexOf("setShareOpen(false)")).toBeGreaterThan(-1)+ expect(closeShare.indexOf("setShareOpen(false)")).toBeLessThan(+ closeShare.indexOf("exitSelect()"),+ )+ })++ it("consumes a loaded target after zero-height measurement and clears highlight after visibility", () => {+ const consumed = vi.fn()+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(Probe, {+ value: props({ scrollToMessageId: "m1", onScrollTargetConsumed: consumed }),+ }),+ { createNodeMock },+ )+ })+ expect(mocks.jumpToIndex).toHaveBeenCalledWith("m1", "auto")+ expect(consumed).toHaveBeenCalledWith("m1")+ expect(latest.jumped).toBe("m1")+ runNextFrame()+ act(() => vi.advanceTimersByTime(1599))+ expect(latest.jumped).toBe("m1")+ act(() => vi.advanceTimersByTime(1))+ expect(latest.jumped).toBeNull()+ act(() => renderer!.unmount())+ })++ it("does not consume a loaded target until the hero ref has been measured", () => {+ const consumed = vi.fn()+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(Probe, {+ attachHero: false,+ value: props({ scrollToMessageId: "m1", onScrollTargetConsumed: consumed }),+ }),+ { createNodeMock },+ )+ })+ expect(mocks.jumpToIndex).not.toHaveBeenCalled()+ expect(consumed).not.toHaveBeenCalled()++ act(() => {+ renderer!.update(React.createElement(Probe, {+ attachHero: true,+ value: props({+ hero: "mounted",+ scrollToMessageId: "m1",+ onScrollTargetConsumed: consumed,+ }),+ }))+ })+ expect(mocks.jumpToIndex).toHaveBeenCalledWith("m1", "auto")+ expect(consumed).toHaveBeenCalledWith("m1")+ act(() => renderer!.unmount())+ })++ it("bounds invisible-target polling and gives the newest pending frame and timer ownership", () => {+ visibleMessageIds = []+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(Probe, { value: props() }),+ { createNodeMock },+ )+ })+ act(() => latest.jumpTo("m1", "auto"))+ for (let index = 0; index < 120; index += 1) runNextFrame()+ expect(requestFrame).toHaveBeenCalledTimes(120)+ expect(frameCallbacks.size).toBe(0)+ expect(latest.jumped).toBe("m1")+ act(() => vi.advanceTimersByTime(1600))+ expect(latest.jumped).toBeNull()++ visibleMessageIds = []+ act(() => latest.jumpTo("m1", "smooth"))+ const replacedFrame = [...frameCallbacks.keys()][0]+ act(() => latest.jumpTo("m2", "smooth"))+ expect(cancelFrame).toHaveBeenCalledWith(replacedFrame)+ expect(frameCallbacks.has(replacedFrame)).toBe(false)+ expect(latest.jumped).toBe("m2")+ visibleMessageIds = ["m2"]+ runNextFrame()++ act(() => vi.advanceTimersByTime(400))+ visibleMessageIds = ["m1"]+ act(() => latest.jumpTo("m1", "smooth"))+ runNextFrame()+ expect(vi.getTimerCount()).toBe(1)+ act(() => vi.advanceTimersByTime(1200))+ expect(latest.jumped).toBe("m1")+ act(() => vi.advanceTimersByTime(399))+ expect(latest.jumped).toBe("m1")+ act(() => vi.advanceTimersByTime(1))+ expect(latest.jumped).toBeNull()+ expect(mocks.jumpToIndex.mock.calls.slice(-3)).toEqual([+ ["m1", "smooth"],+ ["m2", "smooth"],+ ["m1", "smooth"],+ ])++ act(() => latest.jumpTo("m1"))+ runNextFrame()+ expect(vi.getTimerCount()).toBe(1)+ act(() => renderer!.unmount())+ expect(vi.getTimerCount()).toBe(0)++ visibleMessageIds = []+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(Probe, { value: props() }),+ { createNodeMock },+ )+ })+ act(() => latest.jumpTo("m1"))+ const pendingFrame = [...frameCallbacks.keys()][0]+ act(() => renderer!.unmount())+ expect(cancelFrame).toHaveBeenCalledWith(pendingFrame)+ expect(vi.getTimerCount()).toBe(0)+ })+})diff --git a/src/web/src/components/community/messages/message-list-controller.ts b/src/web/src/components/community/messages/message-list-controller.tsnew file mode 100644index 000000000..3767b9232--- /dev/null+++ b/src/web/src/components/community/messages/message-list-controller.ts@@ -0,0 +1,240 @@+"use client"++import { useCallback, useEffect, useMemo, useRef, useState } from "react"+import type { RenderMsg } from "@/lib/community/models/message"+import { flattenMessageItems } from "@/lib/community/message-list-items"+import { useScrollAnchor } from "@/hooks/community/use-scroll-anchor"+import { useVirtualCursorSentinel } from "@/hooks/community/use-virtual-cursor-sentinel"+import type { ResolvedMessageListProps } from "./message-list-types"++export function useMessageListController({+ messages,+ loading,+ newDividerBefore,+ scrollToMessageId,+ initialScrollReady,+ hasMore,+ hasMoreNewer,+ isFetchingOlder,+ isFetchingNewer,+ onLoadOlder,+ onLoadNewer,+ onJumpToPresent,+ presentVersion,+ unreadCount,+ viewerUserId,+ hero,+ onScrollRoot,+ onScrollTargetConsumed,+}: ResolvedMessageListProps) {+ const [jumped, setJumped] = useState<string | null>(null)++ const items = useMemo(+ () => flattenMessageItems(messages, newDividerBefore, !!hasMore),+ [messages, newDividerBefore, hasMore],+ )+ const scrollTargetLoaded = !!scrollToMessageId+ && messages.some((message) => message.id === scrollToMessageId)+ const scrollAnchorReady = scrollToMessageId ? scrollTargetLoaded : initialScrollReady++ const [selectMode, setSelectMode] = useState(false)+ const [selectedIds, setSelectedIds] = useState<Set<string>>(() => new Set())+ const [shareOpen, setShareOpen] = useState(false)+ const onEnterSelectId = useCallback((id: string) => {+ setSelectMode(true)+ setSelectedIds(new Set([id]))+ }, [])+ const onToggleSelectId = useCallback((id: string) => {+ setSelectedIds((prev) => {+ const next = new Set(prev)+ if (next.has(id)) next.delete(id)+ else next.add(id)+ return next+ })+ }, [])+ const exitSelect = useCallback(() => {+ setSelectMode(false)+ setSelectedIds(new Set())+ }, [])+ const selectedMessages = useMemo<RenderMsg[]>(() => {+ if (selectedIds.size === 0) return []+ const picked = items.flatMap((item) => (+ item.kind === "message" && selectedIds.has(item.m.id) ? [item.m] : []+ ))+ let prev: RenderMsg | null = null+ return picked.map((message) => {+ const grouped = !!(+ prev+ && !message.replyTo+ && prev.authorName === message.authorName+ && prev.createdAt+ && message.createdAt+ && new Date(message.createdAt).getTime() - new Date(prev.createdAt).getTime() < 7 * 60 * 1000+ )+ prev = message+ return { ...message, grouped }+ })+ }, [items, selectedIds])++ const heroRef = useRef<HTMLDivElement>(null)+ const [heroHeight, setHeroHeight] = useState(0)+ const [heroMeasured, setHeroMeasured] = useState(false)+ const isLoading = !!loading && messages.length === 0+ useEffect(() => {+ const element = heroRef.current+ if (!element) return+ const observer = new ResizeObserver((entries) => {+ const height = entries[0]?.borderBoxSize?.[0]?.blockSize ?? element.offsetHeight+ setHeroHeight(height)+ setHeroMeasured(true)+ })+ observer.observe(element)+ setHeroHeight(element.offsetHeight)+ setHeroMeasured(true)+ return () => observer.disconnect()+ }, [isLoading, hasMore, hero])++ const {+ scrollRef,+ virtualizer,+ belowCount,+ scrollToBottom,+ jumpTo: jumpToIndex,+ onImageLoad,+ } = useScrollAnchor({+ items,+ newDividerBefore,+ initialScrollReady: scrollAnchorReady,+ hasMoreNewer,+ presentVersion,+ viewerUserId,+ heroHeight,+ heroMeasured,+ })++ useEffect(() => {+ if (!onScrollRoot) return+ onScrollRoot(scrollRef.current)+ return () => onScrollRoot(null)+ }, [onScrollRoot, scrollRef])++ const topSentinelRef = useVirtualCursorSentinel({+ scrollRef,+ hasMore,+ isFetching: isFetchingOlder,+ onLoad: onLoadOlder,+ edge: "start",+ })+ const bottomSentinelRef = useVirtualCursorSentinel({+ scrollRef,+ hasMore: hasMoreNewer,+ isFetching: isFetchingNewer,+ onLoad: onLoadNewer,+ edge: "end",+ })++ const jumpClearTimerRef = useRef<number | null>(null)+ const jumpVisibilityFrameRef = useRef<number | null>(null)+ const jumpTo = useCallback((id: string, behavior: ScrollBehavior = "smooth") => {+ if (jumpClearTimerRef.current !== null) clearTimeout(jumpClearTimerRef.current)+ if (jumpVisibilityFrameRef.current !== null) {+ window.cancelAnimationFrame(jumpVisibilityFrameRef.current)+ }+ setJumped(id)+ jumpToIndex(id, behavior)+ let attempts = 0+ const armClear = () => {+ jumpVisibilityFrameRef.current = null+ const timeout = window.setTimeout(() => {+ setJumped((value) => (value === id ? null : value))+ if (jumpClearTimerRef.current === timeout) jumpClearTimerRef.current = null+ }, 1600)+ jumpClearTimerRef.current = timeout+ }+ const waitUntilVisible = () => {+ const root = scrollRef.current+ const row = root+ ? Array.from(root.querySelectorAll<HTMLElement>("[data-msg-id]"))+ .find((element) => element.dataset.msgId === id)+ : undefined+ if (root && row) {+ const rootRect = root.getBoundingClientRect()+ const rowRect = row.getBoundingClientRect()+ if (rowRect.bottom > rootRect.top && rowRect.top < rootRect.bottom) {+ armClear()+ return+ }+ }+ attempts += 1+ if (attempts >= 120) {+ armClear()+ return+ }+ jumpVisibilityFrameRef.current = window.requestAnimationFrame(waitUntilVisible)+ }+ jumpVisibilityFrameRef.current = window.requestAnimationFrame(waitUntilVisible)+ }, [jumpToIndex, scrollRef])+ useEffect(() => () => {+ if (jumpClearTimerRef.current !== null) clearTimeout(jumpClearTimerRef.current)+ if (jumpVisibilityFrameRef.current !== null) {+ window.cancelAnimationFrame(jumpVisibilityFrameRef.current)+ }+ }, [])++ const consumedScrollTargetRef = useRef<string | null>(null)+ useEffect(() => {+ if (!scrollToMessageId) {+ consumedScrollTargetRef.current = null+ return+ }+ if (consumedScrollTargetRef.current === scrollToMessageId) return+ if (!scrollTargetLoaded || !heroMeasured) return+ consumedScrollTargetRef.current = scrollToMessageId+ jumpTo(scrollToMessageId, "auto")+ onScrollTargetConsumed?.(scrollToMessageId)+ }, [+ scrollToMessageId,+ scrollTargetLoaded,+ heroMeasured,+ jumpTo,+ onScrollTargetConsumed,+ ])++ const jumpMode = !!hasMoreNewer+ const pillCount = jumpMode ? ((unreadCount ?? belowCount) || 0) : belowCount+ const pillOnClick = jumpMode+ ? (onJumpToPresent ?? scrollToBottom)+ : scrollToBottom++ const closeShare = useCallback(() => {+ setShareOpen(false)+ exitSelect()+ }, [exitSelect])++ return {+ items,+ isLoading,+ jumped,+ selectMode,+ selectedIds,+ selectedMessages,+ shareOpen,+ setShareOpen,+ exitSelect,+ closeShare,+ onEnterSelectId,+ onToggleSelectId,+ heroRef,+ scrollRef,+ virtualizer,+ topSentinelRef,+ bottomSentinelRef,+ onImageLoad,+ jumpTo,+ pillCount,+ pillMode: jumpMode ? "jump" as const : "scroll" as const,+ pillOnClick,+ }+}++export type MessageListController = ReturnType<typeof useMessageListController>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.tsnew file mode 100644index 000000000..577e85b02--- /dev/null+++ b/src/web/src/components/community/messages/message-list-facade.contract.test.ts@@ -0,0 +1,92 @@+import { readFileSync } from "node:fs"+import { dirname, resolve } from "node:path"+import { fileURLToPath } from "node:url"+import type { ComponentProps, ComponentRef, ReactNode } from "react"+import { describe, expect, expectTypeOf, it } from "vitest"+import * as facade from "./message-list"+import type { FileAttachment, ImagePreview, Msg } from "@/lib/community/models/message"+import type { OpenProfile } from "@/components/community/social/profile-types"++type ExpectedMessageListProps = {+ channel: string+ messages: Msg[]+ loading?: boolean+ pinnedIds?: Set<string>+ newDividerBefore?: string+ typingUsers?: string[]+ onOpenThread: (id: string) => void+ onOpenProfile?: OpenProfile+ onToggleReaction?: (id: string, emoji: string) => void+ onReact?: (id: string, emoji: string) => void+ onReply?: (id: string) => void+ onPin?: (id: string) => void+ 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+ onPreviewAttachment?: (attachment: FileAttachment) => void+ onDownloadFile?: (url: string, name: string) => void+ resolveUserName?: (userId: string) => string+ scrollToMessageId?: string | null+ hero?: ReactNode+ variant?: "channel" | "dm"+ onScrollRoot?: (element: HTMLDivElement | null) => void+ viewerUserId?: string+ initialScrollReady?: boolean+ onScrollTargetConsumed?: (id: string) => void+ hasMore?: boolean+ isFetchingOlder?: boolean+ onLoadOlder?: () => void+ hasMoreNewer?: boolean+ isFetchingNewer?: boolean+ onLoadNewer?: () => void+ onJumpToPresent?: () => void+ presentVersion?: number+ unreadCount?: number+}++const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..")+const source = (path: string) => readFileSync(resolve(webRoot, path), "utf8")++describe("MessageList facade contract", () => {+ it("keeps the exact one-value public surface and applies defaults in the facade", () => {+ expect(Object.keys(facade)).toEqual(["MessageList"])+ expectTypeOf<ComponentProps<typeof facade.MessageList>>()+ .toEqualTypeOf<ExpectedMessageListProps>()+ expectTypeOf<ExpectedMessageListProps>()+ .toEqualTypeOf<ComponentProps<typeof facade.MessageList>>()+ expectTypeOf<ComponentRef<typeof facade.MessageList>>().toEqualTypeOf<never>()+ const text = source("src/components/community/messages/message-list.tsx")+ expect(text).toContain('variant = "channel"')+ expect(text).toContain("initialScrollReady = true")+ expect(text).toContain("useMessageListController(resolvedProps)")+ expect(text).toContain("return renderMessageListView(resolvedProps, controller, () => (")+ expect(text).toContain("<VirtualRows")+ expect(text).toContain("items={controller.items}")+ expect(text).toContain("virtualizer={controller.virtualizer}")+ expect(text).toContain("itemKey={(item) => item.key}")+ expect(text).toContain(+ "renderItem={(item) => renderMessageListRow(item, resolvedProps, controller)}",+ )+ expect(text).not.toMatch(/<MessageListView\b|createElement\(MessageListView/)+ expect(text).not.toMatch(/forwardRef|useImperativeHandle/)+ })++ it("keeps all production consumers on the original path", () => {+ const importers = [+ "src/app/c/channels/[serverId]/page.tsx",+ "src/app/c/me/[dmId]/page.tsx",+ "src/components/community/channels/thread-channel-surface.tsx",+ "src/components/community/channels/channel-route.tsx",+ "src/components/community/channels/text-channel-surface.tsx",+ ]+ for (const path of importers) {+ const text = source(path)+ expect(text).toMatch(/messages\/message-list["']/)+ expect(text).not.toMatch(/message-list-(types|controller|view|row)/)+ }+ })+})diff --git a/src/web/src/components/community/messages/message-list-row.test.ts b/src/web/src/components/community/messages/message-list-row.test.tsnew file mode 100644index 000000000..b007346d0--- /dev/null+++ b/src/web/src/components/community/messages/message-list-row.test.ts@@ -0,0 +1,138 @@+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { beforeEach, describe, expect, it, vi } from "vitest"+import { renderMessageListRow } from "./message-list-row"+import { MessageRow } from "./message-row"+import type { FlatItem } from "@/lib/community/message-list-items"+import type { MessageListController } from "./message-list-controller"+import type { ResolvedMessageListProps } from "./message-list-types"++vi.mock("./message-row", () => ({ MessageRow: vi.fn(() => null) }))+vi.mock("../dividers", () => ({+ DateDivider: ({ label }: { label: string }) => React.createElement("date-divider", { label }),+ NewDivider: ({ dateLabel }: { dateLabel?: string }) => React.createElement("new-divider", { dateLabel }),+}))++const mockedMessageRow = vi.mocked(MessageRow)++const callbacks = {+ onOpenThread: vi.fn(),+ onOpenProfile: vi.fn(),+ onToggleReaction: vi.fn(),+ onReact: vi.fn(),+ onReply: vi.fn(),+ onPin: vi.fn(),+ onMark: vi.fn(),+ onCreateThread: vi.fn(),+ onCopy: vi.fn(),+ onEdit: vi.fn(),+ onRetry: vi.fn(),+ onDismiss: vi.fn(),+ onPreviewImage: vi.fn(),+ onPreviewAttachment: vi.fn(),+ onDownloadFile: vi.fn(),+ resolveUserName: vi.fn(),+}++const props = {+ channel: "general",+ messages: [],+ variant: "channel" as const,+ initialScrollReady: true,+ viewerUserId: "viewer_1",+ pinnedIds: new Set(["m1"]),+ ...callbacks,+} satisfies ResolvedMessageListProps++const controller = {+ jumped: "m1",+ selectMode: true,+ selectedIds: new Set(["m1"]),+ jumpTo: vi.fn(),+ onImageLoad: vi.fn(),+ onToggleSelectId: vi.fn(),+ onEnterSelectId: vi.fn(),+} as unknown as MessageListController++describe("renderMessageListRow", () => {+ beforeEach(() => vi.clearAllMocks())++ it("renders divider branches without mounting MessageRow", () => {+ let date: TestRenderer.ReactTestRenderer+ let unread: TestRenderer.ReactTestRenderer+ act(() => {+ date = TestRenderer.create(renderMessageListRow(+ { kind: "date-divider", key: "d", label: "Today" } as FlatItem,+ props,+ controller,+ ))+ unread = TestRenderer.create(renderMessageListRow(+ { kind: "new-divider", key: "n", dateLabel: "Today" } as FlatItem,+ props,+ controller,+ ))+ })+ expect(date!.root.findByType("date-divider").props.label).toBe("Today")+ expect(unread!.root.findByType("new-divider").props.dateLabel).toBe("Today")+ expect(mockedMessageRow).not.toHaveBeenCalled()+ })++ it("projects every row identity/action prop and gates edit to the viewer", () => {+ const message = {+ id: "m1",+ type: "chat" as const,+ authorId: "viewer_1",+ authorName: "Viewer",+ content: "hello",+ createdAt: new Date(0).toISOString(),+ grouped: false,+ }+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(renderMessageListRow(+ { kind: "message", key: "m1", m: message } as FlatItem,+ props,+ controller,+ ))+ })+ const wrapper = renderer!.root.findByProps({ "data-msg-id": "m1" })+ expect(wrapper.props["data-testid"]).toBe("community-message-m1")+ expect(mockedMessageRow).toHaveBeenCalledWith(expect.objectContaining({+ m: message,+ viewerUserId: "viewer_1",+ pinned: true,+ highlighted: true,+ onOpenThread: callbacks.onOpenThread,+ onOpenProfile: callbacks.onOpenProfile,+ onToggleReactionId: callbacks.onToggleReaction,+ onReactId: callbacks.onReact,+ onReplyId: callbacks.onReply,+ onPinId: callbacks.onPin,+ onMarkId: callbacks.onMark,+ onCreateThreadId: callbacks.onCreateThread,+ onCopyId: callbacks.onCopy,+ onEditId: callbacks.onEdit,+ onRetryId: callbacks.onRetry,+ onDismissId: callbacks.onDismiss,+ onJumpToId: controller.jumpTo,+ onPreviewImage: callbacks.onPreviewImage,+ onPreviewAttachment: callbacks.onPreviewAttachment,+ onDownloadFile: callbacks.onDownloadFile,+ resolveUserName: callbacks.resolveUserName,+ onImageLoad: controller.onImageLoad,+ selectMode: true,+ selected: true,+ onToggleSelectId: controller.onToggleSelectId,+ onEnterSelectId: controller.onEnterSelectId,+ }), undefined)++ act(() => {+ renderer!.update(renderMessageListRow(+ { kind: "message", key: "m1", m: { ...message, authorId: "peer_1" } } as FlatItem,+ props,+ controller,+ ))+ })+ expect(mockedMessageRow.mock.calls.at(-1)?.[0].onEditId).toBeUndefined()+ })+})diff --git a/src/web/src/components/community/messages/message-list-row.tsx b/src/web/src/components/community/messages/message-list-row.tsxnew file mode 100644index 000000000..7d68031c6--- /dev/null+++ b/src/web/src/components/community/messages/message-list-row.tsx@@ -0,0 +1,51 @@+import { DateDivider, NewDivider } from "../dividers"+import { tid } from "@/lib/community/testids"+import { MessageRow } from "./message-row"+import type { FlatItem } from "@/lib/community/message-list-items"+import type { MessageListController } from "./message-list-controller"+import type { ResolvedMessageListProps } from "./message-list-types"++export function renderMessageListRow(+ item: FlatItem,+ props: ResolvedMessageListProps,+ controller: MessageListController,+) {+ return (+ <>+ {item.kind === "date-divider" && <DateDivider label={item.label} />}+ {item.kind === "new-divider" && <NewDivider dateLabel={item.dateLabel} />}+ {item.kind === "message" && (+ <div data-msg-id={item.m.id} data-testid={tid.message(item.m.id)}>+ <MessageRow+ m={item.m}+ viewerUserId={props.viewerUserId}+ pinned={props.pinnedIds?.has(item.m.id)}+ highlighted={controller.jumped === item.m.id}+ onOpenThread={props.onOpenThread}+ onOpenProfile={props.onOpenProfile}+ onToggleReactionId={props.onToggleReaction}+ onReactId={props.onReact}+ onReplyId={props.onReply}+ onPinId={props.onPin}+ 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}+ onPreviewImage={props.onPreviewImage}+ onPreviewAttachment={props.onPreviewAttachment}+ onDownloadFile={props.onDownloadFile}+ resolveUserName={props.resolveUserName}+ onImageLoad={controller.onImageLoad}+ selectMode={controller.selectMode}+ selected={controller.selectedIds.has(item.m.id)}+ onToggleSelectId={controller.onToggleSelectId}+ onEnterSelectId={controller.onEnterSelectId}+ />+ </div>+ )}+ </>+ )+}diff --git a/src/web/src/components/community/messages/message-list-types.ts b/src/web/src/components/community/messages/message-list-types.tsnew file mode 100644index 000000000..3634a8f66--- /dev/null+++ b/src/web/src/components/community/messages/message-list-types.ts@@ -0,0 +1,49 @@+import type { ReactNode } from "react"+import type { FileAttachment, ImagePreview, Msg } from "@/lib/community/models/message"+import type { OpenProfile } from "@/components/community/social/profile-types"++export type MessageListProps = {+ channel: string+ messages: Msg[]+ loading?: boolean+ pinnedIds?: Set<string>+ newDividerBefore?: string+ typingUsers?: string[]+ onOpenThread: (id: string) => void+ onOpenProfile?: OpenProfile+ onToggleReaction?: (id: string, emoji: string) => void+ onReact?: (id: string, emoji: string) => void+ onReply?: (id: string) => void+ onPin?: (id: string) => void+ 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+ onPreviewAttachment?: (attachment: FileAttachment) => void+ onDownloadFile?: (url: string, name: string) => void+ resolveUserName?: (userId: string) => string+ scrollToMessageId?: string | null+ hero?: ReactNode+ variant?: "channel" | "dm"+ onScrollRoot?: (el: HTMLDivElement | null) => void+ viewerUserId?: string+ initialScrollReady?: boolean+ onScrollTargetConsumed?: (id: string) => void+ hasMore?: boolean+ isFetchingOlder?: boolean+ onLoadOlder?: () => void+ hasMoreNewer?: boolean+ isFetchingNewer?: boolean+ onLoadNewer?: () => void+ onJumpToPresent?: () => void+ presentVersion?: number+ unreadCount?: number+}++export type ResolvedMessageListProps = MessageListProps & {+ variant: "channel" | "dm"+ initialScrollReady: boolean+}diff --git a/src/web/src/components/community/messages/message-list-view.test.ts b/src/web/src/components/community/messages/message-list-view.test.tsnew file mode 100644index 000000000..67a70f2ec--- /dev/null+++ b/src/web/src/components/community/messages/message-list-view.test.ts@@ -0,0 +1,235 @@+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { beforeEach, describe, expect, it, vi } from "vitest"+import { renderMessageListView } from "./message-list-view"+import { TypingIndicator } from "./typing-indicator"+import { MessageShareDialog } from "./message-share-dialog"+import { Button } from "@/components/ui/button"+import type { MessageListController } from "./message-list-controller"+import type { ResolvedMessageListProps } from "./message-list-types"++vi.mock("./typing-indicator", () => ({+ TypingIndicator: vi.fn(({ names }: { names: string[] }) => React.createElement("typing", { names })),+}))+vi.mock("./message-share-dialog", () => ({ MessageShareDialog: vi.fn(() => null) }))+vi.mock("@/components/ui/number-ticker", () => ({+ NumberTicker: ({ value }: { value: number }) => React.createElement("ticker", { value }),+}))++const mockedTyping = vi.mocked(TypingIndicator)+const mockedShareDialog = vi.mocked(MessageShareDialog)++function props(overrides: Partial<ResolvedMessageListProps> = {}): ResolvedMessageListProps {+ return {+ channel: "general",+ messages: [{+ id: "m1",+ type: "chat",+ authorName: "Alice",+ content: "hi",+ createdAt: new Date(0).toISOString(),+ }],+ loading: true,+ typingUsers: ["Alice"],+ onOpenThread: vi.fn(),+ variant: "channel",+ initialScrollReady: true,+ ...overrides,+ }+}++function controller(overrides: Partial<MessageListController> = {}): MessageListController {+ return {+ items: [{ kind: "message", key: "m1", m: props().messages[0] }],+ isLoading: false,+ jumped: null,+ selectMode: false,+ selectedIds: new Set(),+ selectedMessages: [],+ shareOpen: false,+ setShareOpen: vi.fn(),+ exitSelect: vi.fn(),+ closeShare: vi.fn(),+ onEnterSelectId: vi.fn(),+ onToggleSelectId: vi.fn(),+ heroRef: { current: null },+ scrollRef: { current: null },+ virtualizer: {} as MessageListController["virtualizer"],+ topSentinelRef: { current: null },+ bottomSentinelRef: { current: null },+ onImageLoad: vi.fn(),+ jumpTo: vi.fn(),+ pillCount: 3,+ pillMode: "jump",+ pillOnClick: vi.fn(),+ ...overrides,+ } as MessageListController+}++describe("renderMessageListView", () => {+ beforeEach(() => vi.clearAllMocks())++ it("keeps warm non-empty loading data on the loaded DOM with live typing and pill", () => {+ const listProps = props()+ const state = controller()+ const renderRows = vi.fn(() => React.createElement("virtual-rows"))+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(renderMessageListView(listProps, state, renderRows))+ })+ expect(mockedTyping).toHaveBeenCalledWith({ names: ["Alice"] }, undefined)+ expect(renderRows).toHaveBeenCalledOnce()+ expect(renderer!.root.findByProps({ "aria-label": "Jump to present, 3 unread below" })).toBeTruthy()+ expect(renderer!.root.findAllByType("virtual-rows")).toHaveLength(1)+ expect(renderer!.root.findAll((node) => node.props.className === "mb-6")).toHaveLength(1)+ })++ it("keeps the same wrappers while true empty loading hides pill content and typing names", () => {+ const listProps = props({ messages: [] })+ const state = controller({ isLoading: true, pillCount: 8 })+ const renderRows = vi.fn(() => React.createElement("virtual-rows"))+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(renderMessageListView(listProps, state, renderRows))+ })+ expect(renderer!.root.findByType("div").props.className).toBe("relative flex min-h-0 flex-1 flex-col")+ expect(mockedTyping).toHaveBeenCalledWith({ names: [] }, undefined)+ expect(renderRows).not.toHaveBeenCalled()+ expect(renderer!.root.findByProps({ "aria-label": "Jump to present, 0 unread below" }).props.className)+ .toContain("pointer-events-none")+ expect(renderer!.root.findAll((node) => node.props.className === "mb-6")).toHaveLength(1)+ })++ it("wires selection actions and dialog close without changing overlay order", () => {+ const exitSelect = vi.fn()+ const setShareOpen = vi.fn()+ const closeShare = vi.fn()+ const state = controller({+ selectMode: true,+ selectedIds: new Set(["m1"]),+ selectedMessages: props().messages,+ shareOpen: true,+ exitSelect,+ setShareOpen,+ closeShare,+ })+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(renderMessageListView(+ props(),+ state,+ () => React.createElement("virtual-rows"),+ ))+ })+ const [cancel, share] = renderer!.root.findAllByType(Button)+ act(() => cancel.props.onClick())+ expect(exitSelect).toHaveBeenCalledOnce()+ act(() => share.props.onClick())+ expect(setShareOpen).toHaveBeenCalledWith(true)+ expect(mockedShareDialog).toHaveBeenCalledWith(expect.objectContaining({+ m: state.selectedMessages,+ open: true,+ onClose: closeShare,+ }), undefined)+ act(() => mockedShareDialog.mock.calls.at(-1)![0].onClose())+ expect(closeShare).toHaveBeenCalledOnce()++ const outerChildren = renderer!.root.findByType("div").children+ expect(outerChildren.findIndex((child) => typeof child !== "string"+ && child.props?.className?.includes("bottom-3 z-20")))+ .toBeLessThan(outerChildren.findIndex((child) => typeof child !== "string"+ && child.type === TypingIndicator))+ })++ it("keeps both sentinels and the direct rows callback in the exact loaded DOM positions", () => {+ const topNode = { edge: "top" }+ const bottomNode = { edge: "bottom" }+ const scrollNode = { edge: "scroll" }+ const heroNode = { edge: "hero" }+ const state = controller({+ topSentinelRef: { current: null },+ bottomSentinelRef: { current: null },+ scrollRef: { current: null },+ heroRef: { current: null },+ })+ const renderRows = vi.fn(() => React.createElement("virtual-rows", { marker: "rows" }))+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(renderMessageListView(+ props({+ hasMore: true,+ isFetchingOlder: true,+ hasMoreNewer: true,+ isFetchingNewer: true,+ }),+ state,+ renderRows,+ ), {+ createNodeMock: (element) => {+ const className = element.props.className as string | undefined+ if (className === "mb-6") return heroNode+ if (className?.includes("overflow-y-auto")) return scrollNode+ if (className?.includes("mt-6 flex h-8")) return bottomNode+ if (className?.includes("flex h-8")) return topNode+ return null+ },+ })+ })+ expect(state.heroRef.current).toBe(heroNode)+ expect(state.scrollRef.current).toBe(scrollNode)+ expect(state.topSentinelRef.current).toBe(topNode)+ expect(state.bottomSentinelRef.current).toBe(bottomNode)+ expect(renderRows).toHaveBeenCalledOnce()+ expect(renderer!.root.findByProps({ marker: "rows" })).toBeTruthy()+ expect(renderer!.root.findAllByType("div").some((node) =>+ node.children.includes("Loading older messages…"))).toBe(true)+ expect(renderer!.root.findAllByType("div").some((node) =>+ node.children.includes("Loading newer messages…"))).toBe(true)++ const content = renderer!.root.findByProps({+ className: "flex min-h-full flex-col justify-end px-4 py-8",+ })+ const elementChildren = content.children.filter((child) => typeof child !== "string")+ expect(elementChildren).toHaveLength(3)+ expect(elementChildren[0].props.className).toBe("mb-6")+ expect(elementChildren[1].type).toBe("virtual-rows")+ expect(elementChildren[2].props.className).toContain("mt-6")++ act(() => {+ renderer!.update(renderMessageListView(+ props({+ hasMore: true,+ isFetchingOlder: false,+ hasMoreNewer: true,+ isFetchingNewer: false,+ }),+ state,+ renderRows,+ ))+ })+ expect(renderer!.root.findAll((node) =>+ node.children.includes("Loading older messages…"))).toHaveLength(0)+ expect(renderer!.root.findAll((node) =>+ node.children.includes("Loading newer messages…"))).toHaveLength(0)+ expect(renderer!.root.findAllByProps({+ className: "flex h-8 items-center justify-center text-xs text-muted-foreground",+ })).toHaveLength(1)+ expect(renderer!.root.findAllByProps({+ className: "mt-6 flex h-8 items-center justify-center text-xs text-muted-foreground",+ })).toHaveLength(1)++ act(() => {+ renderer!.update(renderMessageListView(+ props({ hasMore: false, hasMoreNewer: false }),+ state,+ renderRows,+ ))+ })+ expect(renderer!.root.findAllByProps({+ className: "flex h-8 items-center justify-center text-xs text-muted-foreground",+ })).toHaveLength(0)+ expect(renderer!.root.findAllByProps({+ className: "mt-6 flex h-8 items-center justify-center text-xs text-muted-foreground",+ })).toHaveLength(0)+ })+})diff --git a/src/web/src/components/community/messages/message-list-view.tsx b/src/web/src/components/community/messages/message-list-view.tsxnew file mode 100644index 000000000..0c966a2bb--- /dev/null+++ b/src/web/src/components/community/messages/message-list-view.tsx@@ -0,0 +1,178 @@+import type { ReactNode } from "react"+import { ArrowDown, ImageIcon, X } from "lucide-react"+import { Button } from "@/components/ui/button"+import { Skeleton } from "@/components/ui/skeleton"+import { NumberTicker } from "@/components/ui/number-ticker"+import { ChannelIcon } from "../channels/channel-icon"+import { MessageShareDialog } from "./message-share-dialog"+import { TypingIndicator } from "./typing-indicator"+import type { MessageListController } from "./message-list-controller"+import type { ResolvedMessageListProps } from "./message-list-types"++export function renderMessageListView(+ props: ResolvedMessageListProps,+ controller: MessageListController,+ renderRows: () => ReactNode,+) {+ return (+ <div className="relative flex min-h-0 flex-1 flex-col">+ <ScrollDownButton+ count={controller.isLoading ? 0 : controller.pillCount}+ mode={controller.pillMode}+ onClick={controller.pillOnClick}+ />+ {controller.selectMode && (+ <div className="absolute inset-x-0 bottom-3 z-20 flex justify-center px-4">+ <div className="flex items-center gap-2 rounded-full border border-border/60 bg-card px-2 py-1.5 shadow-(--e2)">+ <span className="px-2 text-sm text-muted-foreground">+ {controller.selectedIds.size} selected+ </span>+ <Button size="sm" variant="ghost" onClick={controller.exitSelect}>+ <X /> Cancel+ </Button>+ <Button+ size="sm"+ disabled={controller.selectedIds.size === 0}+ onClick={() => controller.setShareOpen(true)}+ >+ <ImageIcon /> Share {controller.selectedIds.size} as image+ </Button>+ </div>+ </div>+ )}+ {controller.shareOpen && controller.selectedMessages.length > 0 && (+ <MessageShareDialog+ m={controller.selectedMessages}+ open={controller.shareOpen}+ onClose={controller.closeShare}+ />+ )}+ <TypingIndicator names={controller.isLoading ? [] : props.typingUsers ?? []} />+ <div+ ref={controller.scrollRef}+ className="flex-1 overflow-x-clip overflow-y-auto thin-scrollbar"+ >+ <div className="flex min-h-full flex-col justify-end px-4 py-8">+ {controller.isLoading ? (+ <MessageListSkeletonContent variant={props.variant} />+ ) : (+ <>+ <div ref={controller.heroRef} className="mb-6">+ {props.hasMore ? (+ <div+ ref={controller.topSentinelRef}+ className="flex h-8 items-center justify-center text-xs text-muted-foreground"+ >+ {props.isFetchingOlder ? "Loading older messages…" : ""}+ </div>+ ) : (+ props.hero ?? (+ <>+ <div className="mb-2 grid size-12 place-items-center rounded-full bg-muted/60">+ <ChannelIcon className="text-xl text-muted-foreground" />+ </div>+ <h2 className="text-xl font-semibold leading-tight">{props.channel}</h2>+ <p className="mt-2 text-sm text-muted-foreground">+ Beginning of the channel. Say hello, share what you're working on, or drop a link.+ </p>+ </>+ )+ )}+ </div>++ {renderRows()}++ {props.hasMoreNewer && (+ <div+ ref={controller.bottomSentinelRef}+ className="mt-6 flex h-8 items-center justify-center text-xs text-muted-foreground"+ >+ {props.isFetchingNewer ? "Loading newer messages…" : ""}+ </div>+ )}+ </>+ )}+ </div>+ </div>+ </div>+ )+}++function ScrollDownButton({+ count,+ mode = "scroll",+ onClick,+}: {+ count: number+ mode?: "scroll" | "jump"+ onClick: () => void+}) {+ const visible = count > 0+ const aria = mode === "jump"+ ? `Jump to present, ${count} unread below`+ : `Scroll to bottom, ${count} more below`+ return (+ <div+ className={`pointer-events-none absolute bottom-3 left-1/2 z-10 -translate-x-1/2 transition-all duration-200 ease-out ${+ visible ? "translate-y-0 opacity-100" : "translate-y-2 opacity-0"+ }`}+ >+ <button+ type="button"+ onClick={onClick}+ aria-label={aria}+ className={`pointer-events-auto flex h-8 items-center gap-1.5 rounded-full border border-border bg-background/90 pl-2 pr-3 text-xs font-medium text-foreground shadow-(--e1) backdrop-blur-sm transition-colors hover:bg-accent ${+ visible ? "" : "pointer-events-none"+ }`}+ >+ <ArrowDown className="size-3.5 text-muted-foreground" />+ <NumberTicker value={count} />+ </button>+ </div>+ )+}++function MessageListSkeletonContent({ variant }: { variant: "channel" | "dm" }) {+ const clusters: number[][] = [+ [220, 140],+ [180],+ [260, 90, 200],+ [120, 240],+ [200],+ ]+ return (+ <>+ <div className="mb-6">+ {variant === "dm" ? (+ <>+ <Skeleton className="mb-3 size-16 rounded-full" />+ <Skeleton className="h-7 w-48 rounded" />+ <Skeleton className="mt-2 h-3.5 w-72 rounded" />+ </>+ ) : (+ <>+ <Skeleton className="mb-2 size-12 rounded-full" />+ <Skeleton className="h-5 w-40 rounded" />+ <Skeleton className="mt-2 h-3.5 w-80 max-w-full rounded" />+ </>+ )}+ </div>+ <div className="flex flex-col gap-3">+ {clusters.map((lines, index) => (+ <div key={index} className="flex gap-3 pt-1.5">+ <Skeleton className="size-10 shrink-0 rounded-full" />+ <div className="flex min-w-0 flex-1 flex-col gap-2">+ <div className="flex items-center gap-2">+ <Skeleton className="h-4 w-24 rounded" />+ <Skeleton className="h-3 w-14 rounded" />+ </div>+ {lines.map((width, lineIndex) => (+ <Skeleton key={lineIndex} className="h-3.5 rounded" style={{ width }} />+ ))}+ </div>+ </div>+ ))}+ </div>+ </>+ )+}diff --git a/src/web/src/components/community/message-list.jump-target.test.ts b/src/web/src/components/community/messages/message-list.jump-target.test.tssimilarity index 100%rename from src/web/src/components/community/message-list.jump-target.test.tsrename to src/web/src/components/community/messages/message-list.jump-target.test.tsdiff --git a/src/web/src/components/community/message-list.mount-identity.test.ts b/src/web/src/components/community/messages/message-list.mount-identity.test.tssimilarity index 100%rename from src/web/src/components/community/message-list.mount-identity.test.tsrename to src/web/src/components/community/messages/message-list.mount-identity.test.tsdiff --git a/src/web/src/components/community/message-list.older-load.test.ts b/src/web/src/components/community/messages/message-list.older-load.test.tssimilarity index 100%rename from src/web/src/components/community/message-list.older-load.test.tsrename to src/web/src/components/community/messages/message-list.older-load.test.tsdiff --git a/src/web/src/components/community/messages/message-list.tsx b/src/web/src/components/community/messages/message-list.tsxnew file mode 100644index 000000000..ce65f93d5--- /dev/null+++ b/src/web/src/components/community/messages/message-list.tsx@@ -0,0 +1,28 @@+"use client"++import { useMessageListController } from "./message-list-controller"+import type { MessageListProps, ResolvedMessageListProps } from "./message-list-types"+import { renderMessageListRow } from "./message-list-row"+import { renderMessageListView } from "./message-list-view"+import { VirtualRows } from "./virtual-cursor-list"++export function MessageList({+ variant = "channel",+ initialScrollReady = true,+ ...props+}: MessageListProps) {+ const resolvedProps: ResolvedMessageListProps = {+ ...props,+ variant,+ initialScrollReady,+ }+ const controller = useMessageListController(resolvedProps)+ return renderMessageListView(resolvedProps, controller, () => (+ <VirtualRows+ items={controller.items}+ virtualizer={controller.virtualizer}+ itemKey={(item) => item.key}+ renderItem={(item) => renderMessageListRow(item, resolvedProps, controller)}+ />+ ))+}diff --git a/src/web/src/components/community/message-markdown.test.ts b/src/web/src/components/community/messages/message-markdown.test.tssimilarity index 100%rename from src/web/src/components/community/message-markdown.test.tsrename to src/web/src/components/community/messages/message-markdown.test.tsdiff --git a/src/web/src/components/community/message-markdown.tsx b/src/web/src/components/community/messages/message-markdown.tsxsimilarity index 100%rename from src/web/src/components/community/message-markdown.tsxrename to src/web/src/components/community/messages/message-markdown.tsxdiff --git a/src/web/src/components/community/message-menu-parity.test.ts b/src/web/src/components/community/messages/message-menu-parity.test.tssimilarity index 98%rename from src/web/src/components/community/message-menu-parity.test.tsrename to src/web/src/components/community/messages/message-menu-parity.test.tsindex 64964475b..97d18cfb0 100644--- a/src/web/src/components/community/message-menu-parity.test.ts+++ b/src/web/src/components/community/messages/message-menu-parity.test.ts@@ -17,7 +17,7 @@import { describe, it, expect } from "vitest"import { messageCanShare } from "./message"import { messageMenuItems } from "./message-menu"-import type { RenderMsg } from "./_types"+import type { RenderMsg } from "@/lib/community/models/message"const msg = (over: Partial<RenderMsg> = {}): RenderMsg =>({ id: "m1", content: "hello", grouped: false, ...over }) as RenderMsgdiff --git a/src/web/src/components/community/message-menu.test.ts b/src/web/src/components/community/messages/message-menu.test.tssimilarity index 100%rename from src/web/src/components/community/message-menu.test.tsrename to src/web/src/components/community/messages/message-menu.test.tsdiff --git a/src/web/src/components/community/message-menu.tsx b/src/web/src/components/community/messages/message-menu.tsxsimilarity index 100%rename from src/web/src/components/community/message-menu.tsxrename to src/web/src/components/community/messages/message-menu.tsxdiff --git a/src/web/src/components/community/messages/message-presentation-types.ts b/src/web/src/components/community/messages/message-presentation-types.tsnew file mode 100644index 000000000..ebef6b645--- /dev/null+++ b/src/web/src/components/community/messages/message-presentation-types.ts@@ -0,0 +1 @@+export type MessagePerspective = "sender" | "recipient" | "neutral"diff --git a/src/web/src/components/community/message-row.tsx b/src/web/src/components/community/messages/message-row.tsxsimilarity index 97%rename from src/web/src/components/community/message-row.tsxrename to src/web/src/components/community/messages/message-row.tsxindex e93340eb9..4f90b5d5e 100644--- a/src/web/src/components/community/message-row.tsx+++ b/src/web/src/components/community/messages/message-row.tsx@@ -2,7 +2,8 @@import { memo, useCallback } from "react"import { Message } from "./message"-import type { FileAttachment, ImagePreview, RenderMsg, OpenProfile } from "./_types"+import type { FileAttachment, ImagePreview, RenderMsg } from "@/lib/community/models/message"+import type { OpenProfile } from "@/components/community/social/profile-types"// A thin, memoized per-row wrapper between the virtualized list and `Message`.//diff --git a/src/web/src/components/community/message-share-dialog.test.ts b/src/web/src/components/community/messages/message-share-dialog.test.tssimilarity index 97%rename from src/web/src/components/community/message-share-dialog.test.tsrename to src/web/src/components/community/messages/message-share-dialog.test.tsindex 00c3010c4..61eb486a4 100644--- a/src/web/src/components/community/message-share-dialog.test.ts+++ b/src/web/src/components/community/messages/message-share-dialog.test.ts@@ -2,12 +2,12 @@ import { describe, expect, it, vi } from "vitest"import React from "react"import TestRenderer, { act } from "react-test-renderer"import { MessageShareDialog } from "./message-share-dialog"-import type { RenderMsg } from "./_types"+import type { RenderMsg } from "@/lib/community/models/message"vi.mock("html-to-image", () => ({ toBlob: vi.fn() }))vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }))vi.mock("next/image", () => ({ default: "img" }))-vi.mock("./avatar", () => ({ Avatar: "mock-avatar" }))+vi.mock("../avatar", () => ({ Avatar: "mock-avatar" }))vi.mock("./message-body", () => ({ MessageBody: ({ text }: { text: string }) => text }))vi.mock("@/components/ui/button", () => ({ Button: "button" }))vi.mock("@/components/ui/dialog", () => {diff --git a/src/web/src/components/community/message-share-dialog.tsx b/src/web/src/components/community/messages/message-share-dialog.tsxsimilarity index 99%rename from src/web/src/components/community/message-share-dialog.tsxrename to src/web/src/components/community/messages/message-share-dialog.tsxindex 3a7630d2f..7ed91baaa 100644--- a/src/web/src/components/community/message-share-dialog.tsx+++ b/src/web/src/components/community/messages/message-share-dialog.tsx@@ -8,12 +8,12 @@ import { Check, Copy, Download, Highlighter, Loader2 } from "lucide-react"import { stripInlineMarkup } from "@alook/shared"import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"import { Button } from "@/components/ui/button"-import { Avatar } from "./avatar"+import { Avatar } from "../avatar"import { MessageBody } from "./message-body"import { attachmentAspectRatio } from "./attachment-layout"import { tid } from "@/lib/community/testids"import { applyHighlightToRange, clearHighlights, hasHighlights } from "@/lib/community/highlight-range"-import type { RenderMsg } from "./_types"+import type { RenderMsg } from "@/lib/community/models/message"// Share one OR several messages as an image. Renders a self-contained "share// card" that mirrors the in-app message blob(s) (avatar / name / content — NOdiff --git a/src/web/src/components/community/message.render.test.ts b/src/web/src/components/community/messages/message.render.test.tssimilarity index 99%rename from src/web/src/components/community/message.render.test.tsrename to src/web/src/components/community/messages/message.render.test.tsindex e64585a4e..c0c3a9c37 100644--- a/src/web/src/components/community/message.render.test.ts+++ b/src/web/src/components/community/messages/message.render.test.ts@@ -3,7 +3,7 @@ import React from "react"import TestRenderer, { act } from "react-test-renderer"import { QueryClient, QueryClientProvider } from "@tanstack/react-query"import { Message, shouldActivateMessageOverlays } from "./message"-import type { RenderMsg } from "./_types"+import type { RenderMsg } from "@/lib/community/models/message"// WS3 render-behavior tests (see plans/community-switch-perf-optimization.md):// - the custom memo comparator bails out despite the per-render `m` clone,diff --git a/src/web/src/components/community/message.test.ts b/src/web/src/components/community/messages/message.test.tssimilarity index 100%rename from src/web/src/components/community/message.test.tsrename to src/web/src/components/community/messages/message.test.tsdiff --git a/src/web/src/components/community/message.tsx b/src/web/src/components/community/messages/message.tsxsimilarity index 98%rename from src/web/src/components/community/message.tsxrename to src/web/src/components/community/messages/message.tsxindex 1c5abf403..efdafbb18 100644--- a/src/web/src/components/community/message.tsx+++ b/src/web/src/components/community/messages/message.tsx@@ -9,19 +9,20 @@ import {} from "lucide-react"import { ContextMenu, ContextMenuTrigger, ContextMenuContent } from "@/components/ui/context-menu"import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent } from "@/components/ui/dropdown-menu"-import { Avatar } from "./avatar"+import { Avatar } from "../avatar"import { MessageBody } from "./message-body"-import { BotApprovalCard } from "./bot-approval-card"+import { BotApprovalCard } from "../social/bot-approval-card"import { EmojiPickerPopover } from "./emoji-picker"import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip"import { NumberTicker } from "@/components/ui/number-ticker"import { MessageContextItems, MessageDropdownItems, hasMessageMenu } from "./message-menu"-import { formatMessageTime } from "./format-time"+import { formatMessageTime } from "@/lib/community/format-time"import { tid } from "@/lib/community/testids"import { avatarInitial } from "@/lib/community/avatar"import { displayName } from "@/lib/community/display-name"import { stripInlineMarkup } from "@alook/shared"-import type { FileAttachment, ImagePreview, RenderMsg, OpenProfile } from "./_types"+import type { FileAttachment, ImagePreview, RenderMsg } from "@/lib/community/models/message"+import type { OpenProfile } from "@/components/community/social/profile-types"import { attachmentAspectRatio } from "./attachment-layout"import { AttachmentCard } from "./attachment-card"diff --git a/src/web/src/components/community/server-ref-pill.test.ts b/src/web/src/components/community/messages/server-ref-pill.test.tssimilarity index 100%rename from src/web/src/components/community/server-ref-pill.test.tsrename to src/web/src/components/community/messages/server-ref-pill.test.tsdiff --git a/src/web/src/components/community/server-ref-pill.tsx b/src/web/src/components/community/messages/server-ref-pill.tsxsimilarity index 100%rename from src/web/src/components/community/server-ref-pill.tsxrename to src/web/src/components/community/messages/server-ref-pill.tsxdiff --git a/src/web/src/components/community/thread-opener.test.ts b/src/web/src/components/community/messages/thread-opener.test.tssimilarity index 100%rename from src/web/src/components/community/thread-opener.test.tsrename to src/web/src/components/community/messages/thread-opener.test.tsdiff --git a/src/web/src/components/community/thread-opener.tsx b/src/web/src/components/community/messages/thread-opener.tsxsimilarity index 96%rename from src/web/src/components/community/thread-opener.tsxrename to src/web/src/components/community/messages/thread-opener.tsxindex aa271f246..ab9e67163 100644--- a/src/web/src/components/community/thread-opener.tsx+++ b/src/web/src/components/community/messages/thread-opener.tsx@@ -1,16 +1,17 @@"use client"import { MessagesSquare, ArrowUpRight } from "lucide-react"-import { Avatar } from "./avatar"+import { Avatar } from "../avatar"import { MessageBody } from "./message-body"import { attachmentAspectRatio } from "./attachment-layout"-import { formatMessageTime } from "./format-time"+import { formatMessageTime } from "@/lib/community/format-time"import { Skeleton } from "@/components/ui/skeleton"import { NumberTicker } from "@/components/ui/number-ticker"import { avatarInitial } from "@/lib/community/avatar"import { useMessage } from "@/hooks/community/use-message"import { tid } from "@/lib/community/testids"-import type { FileAttachment, ImagePreview, OpenProfile } from "./_types"+import type { FileAttachment, ImagePreview } from "@/lib/community/models/message"+import type { OpenProfile } from "@/components/community/social/profile-types"import { AttachmentCard } from "./attachment-card"// Thread opener — the parent message the thread was created from, pinned atdiff --git a/src/web/src/components/community/typing-indicator.tsx b/src/web/src/components/community/messages/typing-indicator.tsxsimilarity index 100%rename from src/web/src/components/community/typing-indicator.tsxrename to src/web/src/components/community/messages/typing-indicator.tsxdiff --git a/src/web/src/components/community/messages/use-composer-controller.test.ts b/src/web/src/components/community/messages/use-composer-controller.test.tsnew file mode 100644index 000000000..c739bbab3--- /dev/null+++ b/src/web/src/components/community/messages/use-composer-controller.test.ts@@ -0,0 +1,824 @@+import { readFileSync } from "node:fs"+import { forwardRef, createElement, createRef } from "react"+import TestRenderer, { act } from "react-test-renderer"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"++const mocks = vi.hoisted(() => ({+ useEditor: vi.fn(),+ useFileAttachments: vi.fn(),+ useSuggestions: vi.fn(),+ clearDraft: vi.fn(),+ readDraft: vi.fn(),+ writeDraft: vi.fn(),+ detectMentionType: vi.fn(),+ addPendingFiles: vi.fn(),+ starterConfigure: vi.fn(),+ placeholderConfigure: vi.fn(),+ buildPasteDom: vi.fn(),+ fromSchema: vi.fn(),+ parseSlice: vi.fn(),+}))++vi.mock("@tiptap/react", () => ({+ useEditor: (...args: unknown[]) => mocks.useEditor(...args),+}))+vi.mock("@tiptap/starter-kit", () => ({+ default: {+ configure: (...args: unknown[]) => mocks.starterConfigure(...args),+ },+}))+vi.mock("@tiptap/extension-placeholder", () => ({+ default: {+ configure: (...args: unknown[]) => mocks.placeholderConfigure(...args),+ },+}))+vi.mock("@tiptap/pm/model", () => ({+ DOMParser: {+ fromSchema: (...args: unknown[]) => mocks.fromSchema(...args),+ },+}))+vi.mock("@/hooks/use-file-attachments", () => ({+ useFileAttachments: (...args: unknown[]) =>+ mocks.useFileAttachments(...args),+}))+vi.mock("@/lib/community/composer-draft", () => ({+ clearComposerDraft: (...args: unknown[]) => mocks.clearDraft(...args),+ readComposerDraft: (...args: unknown[]) => mocks.readDraft(...args),+ writeComposerDraft: (...args: unknown[]) => mocks.writeDraft(...args),+}))+vi.mock("@/lib/community/mention-extension", () => ({+ detectMentionType: (...args: unknown[]) => mocks.detectMentionType(...args),+}))+vi.mock("@/lib/community/paste-plain-text", () => ({+ buildPasteDom: (...args: unknown[]) => mocks.buildPasteDom(...args),+}))+vi.mock("./use-composer-suggestions", () => ({+ useComposerSuggestions: (...args: unknown[]) =>+ mocks.useSuggestions(...args),+}))++import { useComposerController } from "./use-composer-controller"+import type { ComposerHandle, ComposerProps } from "./composer-types"+import type { PendingFile } from "@/hooks/use-file-attachments"++type EditorOptions = {+ editorProps: {+ handleKeyDown: (_view: unknown, event: KeyboardEvent) => boolean+ handlePaste: (_view: unknown, event: ClipboardEvent) => boolean+ clipboardTextParser: (text: string, context: never) => unknown+ }+ onUpdate: (props: { editor: TestEditor }) => void+}++type TestEditor = {+ isEmpty: boolean+ getText: ReturnType<typeof vi.fn>+ getJSON: ReturnType<typeof vi.fn>+ commands: {+ clearContent: ReturnType<typeof vi.fn>+ focus: ReturnType<typeof vi.fn>+ setContent: ReturnType<typeof vi.fn>+ }+ chain: ReturnType<typeof vi.fn>+}++const Harness = forwardRef<ComposerHandle, ComposerProps>(+ function Harness(props, ref) {+ const view = useComposerController(props, ref)+ return createElement("controller-probe", { view })+ },+)++describe("useComposerController", () => {+ let editorOptions: EditorOptions+ let pendingFiles: PendingFile[]+ let editor: TestEditor+ let clearContent: ReturnType<typeof vi.fn>+ let focus: ReturnType<typeof vi.fn>+ let setContent: ReturnType<typeof vi.fn>+ let chainFocus: ReturnType<typeof vi.fn>+ let insertContent: ReturnType<typeof vi.fn>+ let run: ReturnType<typeof vi.fn>+ let setPendingFiles: ReturnType<typeof vi.fn>+ let transferPendingFiles: ReturnType<typeof vi.fn>+ let awaitPendingFiles: ReturnType<typeof vi.fn>+ let resetPopups: ReturnType<typeof vi.fn>+ let filePickerClick: ReturnType<typeof vi.fn>+ let handleDropRaw: ReturnType<typeof vi.fn>+ let mentionPopupRef: { current: { items: unknown[]; command: null | ReturnType<typeof vi.fn> } }+ let channelRefPopupRef: { current: { items: unknown[]; command: null | ReturnType<typeof vi.fn> } }++ beforeEach(() => {+ vi.clearAllMocks()+ pendingFiles = []+ clearContent = vi.fn()+ focus = vi.fn()+ setContent = vi.fn()+ run = vi.fn()+ insertContent = vi.fn(() => ({ run }))+ chainFocus = vi.fn(() => ({ insertContent }))+ setPendingFiles = vi.fn()+ transferPendingFiles = vi.fn()+ awaitPendingFiles = vi.fn(async () => pendingFiles)+ resetPopups = vi.fn()+ filePickerClick = vi.fn()+ handleDropRaw = vi.fn()+ mentionPopupRef = { current: { items: [], command: null } }+ channelRefPopupRef = { current: { items: [], command: null } }+ editor = {+ isEmpty: false,+ getText: vi.fn(() => " hello @everyone "),+ getJSON: vi.fn(() => ({ type: "doc" })),+ commands: {+ clearContent,+ focus,+ setContent,+ },+ chain: vi.fn(() => ({ focus: chainFocus })),+ }+ mocks.starterConfigure.mockReturnValue({ name: "starter-kit" })+ mocks.placeholderConfigure.mockReturnValue({ name: "placeholder" })+ mocks.fromSchema.mockReturnValue({ parseSlice: mocks.parseSlice })+ mocks.useEditor.mockImplementation((options) => {+ editorOptions = options+ return editor+ })+ mocks.useFileAttachments.mockImplementation(() => ({+ pendingFiles,+ setPendingFiles,+ transferPendingFiles,+ awaitPendingFiles,+ addPendingFiles: mocks.addPendingFiles,+ fileInputRef: { current: { click: filePickerClick } },+ handleFileSelect: vi.fn(),+ removePendingFile: vi.fn(),+ dragging: false,+ handleDragEnter: vi.fn(),+ handleDragLeave: vi.fn(),+ handleDragOver: vi.fn(),+ handleDrop: handleDropRaw,+ }))+ mocks.useSuggestions.mockImplementation(() => ({+ mentionPopup: { items: [], selectedIndex: 0, command: null, rect: null },+ mentionPopupRef,+ mentionExtension: { name: "mention" },+ channelRefPopup: { items: [], selectedIndex: 0, command: null, rect: null },+ channelRefPopupRef,+ channelRefExtension: { name: "channel-ref" },+ resetPopups,+ }))+ mocks.detectMentionType.mockReturnValue("everyone")+ mocks.readDraft.mockReturnValue(null)+ })++ afterEach(() => {+ vi.useRealTimers()+ })++ const acceptedProps = (+ onAcceptSend: Extract<+ ComposerProps,+ { sendContract: "accepted" }+ >["onAcceptSend"],+ ): ComposerProps => ({+ channel: "general",+ context: "channel",+ members: [],+ sendContract: "accepted",+ onAcceptSend,+ draftKey: "server/channel",+ })++ const enter = async (shiftKey = false) => {+ const preventDefault = vi.fn()+ await act(async () => {+ editorOptions.editorProps.handleKeyDown({} as never, {+ key: "Enter",+ shiftKey,+ isComposing: false,+ preventDefault,+ } as unknown as KeyboardEvent)+ await Promise.resolve()+ await Promise.resolve()+ })+ return preventDefault+ }++ it("retains everything after false/throw, unlocks, and clears only on accepted true", async () => {+ const file = new File(["x"], "notes.txt", { type: "text/plain" })+ pendingFiles = [{ file, thumbnailUrl: null, thumbnailBlob: null }]+ const reject = vi.fn(() => false)+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(createElement(Harness, acceptedProps(reject)))+ })+ await enter()+ expect(reject).toHaveBeenCalledWith(+ "hello @everyone",+ [+ {+ file,+ previewObjectUrl: undefined,+ width: undefined,+ height: undefined,+ },+ ],+ "everyone",+ )+ expect(clearContent).not.toHaveBeenCalled()+ expect(mocks.clearDraft).not.toHaveBeenCalled()+ expect(transferPendingFiles).not.toHaveBeenCalled()+ expect(resetPopups).not.toHaveBeenCalled()++ const throws = vi.fn(() => {+ throw new Error("rejected")+ })+ await act(async () => {+ renderer.update(createElement(Harness, acceptedProps(throws)))+ })+ await enter()+ expect(throws).toHaveBeenCalledOnce()+ expect(clearContent).not.toHaveBeenCalled()+ expect(transferPendingFiles).not.toHaveBeenCalled()+ expect(resetPopups).not.toHaveBeenCalled()++ const accept = vi.fn(() => true)+ await act(async () => {+ renderer.update(createElement(Harness, acceptedProps(accept)))+ })+ await enter()+ expect(accept).toHaveBeenCalledOnce()+ expect(clearContent).toHaveBeenCalledOnce()+ expect(mocks.clearDraft).toHaveBeenCalledWith("server/channel")+ expect(transferPendingFiles).toHaveBeenCalledOnce()+ expect(resetPopups).toHaveBeenCalledOnce()+ expect(clearContent.mock.invocationCallOrder[0]).toBeLessThan(+ mocks.clearDraft.mock.invocationCallOrder[0],+ )+ expect(mocks.clearDraft.mock.invocationCallOrder[0]).toBeLessThan(+ transferPendingFiles.mock.invocationCallOrder[0],+ )+ expect(transferPendingFiles.mock.invocationCallOrder[0]).toBeLessThan(+ resetPopups.mock.invocationCallOrder[0],+ )+ })++ it("awaits deferred resolve/reject without Composer-owned cleanup", async () => {+ let resolve!: () => void+ const deferred = new Promise<void>((done) => {+ resolve = done+ })+ const submit = vi.fn(() => deferred)+ const props: ComposerProps = {+ channel: "forum",+ context: "channel",+ members: [],+ sendContract: "deferred",+ mode: "forumThreadBody",+ onDeferredSubmit: submit,+ }+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(createElement(Harness, props))+ })+ await enter(true)+ await enter(true)+ expect(submit).toHaveBeenCalledOnce()+ expect(clearContent).not.toHaveBeenCalled()+ await act(async () => {+ resolve()+ await deferred+ })+ expect(clearContent).not.toHaveBeenCalled()+ expect(setPendingFiles).not.toHaveBeenCalled()+ expect(transferPendingFiles).not.toHaveBeenCalled()+ expect(resetPopups).not.toHaveBeenCalled()++ const rejected = vi.fn(async () => {+ throw new Error("mutation failed")+ })+ await act(async () => {+ renderer.update(+ createElement(Harness, { ...props, onDeferredSubmit: rejected }),+ )+ })+ await enter(true)+ expect(rejected).toHaveBeenCalledOnce()+ await enter(true)+ expect(rejected).toHaveBeenCalledTimes(2)+ expect(clearContent).not.toHaveBeenCalled()+ expect(resetPopups).not.toHaveBeenCalled()+ })++ it("reads popup refs at keydown time and preserves handle/paste semantics", async () => {+ const accept = vi.fn(() => true)+ const handleRef = createRef<ComposerHandle>()+ await act(async () => {+ TestRenderer.create(+ createElement(Harness, { ...acceptedProps(accept), ref: handleRef }),+ )+ })+ mentionPopupRef.current = { items: [{}], command: vi.fn() }+ const blocked = vi.fn()+ expect(+ editorOptions.editorProps.handleKeyDown({} as never, {+ key: "Enter",+ shiftKey: false,+ isComposing: false,+ preventDefault: blocked,+ } as unknown as KeyboardEvent),+ ).toBe(false)+ expect(blocked).not.toHaveBeenCalled()+ expect(accept).not.toHaveBeenCalled()++ mentionPopupRef.current = { items: [], command: vi.fn() }+ await enter()+ expect(accept).toHaveBeenCalledOnce()++ const file = new File(["x"], "paste.png", { type: "image/png" })+ const items = {+ 0: { kind: "file", getAsFile: () => file },+ length: 1,+ } as unknown as DataTransferItemList+ const preventDefault = vi.fn()+ expect(+ editorOptions.editorProps.handlePaste({} as never, {+ clipboardData: { items },+ preventDefault,+ } as unknown as ClipboardEvent),+ ).toBe(true)+ expect(preventDefault).toHaveBeenCalledOnce()+ expect(mocks.addPendingFiles).toHaveBeenCalledWith([file])+ expect(+ editorOptions.editorProps.handlePaste({} as never, {+ clipboardData: { items: { length: 0 } },+ preventDefault: vi.fn(),+ } as unknown as ClipboardEvent),+ ).toBe(false)++ handleRef.current?.focusEditor()+ expect(focus).toHaveBeenCalledWith("end")+ handleRef.current?.openFilePicker()+ expect(filePickerClick).toHaveBeenCalledOnce()+ expect(handleRef.current?.isEmpty()).toBe(false)+ const transfersBeforeReset = transferPendingFiles.mock.calls.length+ handleRef.current?.resetAfterSubmit()+ expect(setPendingFiles).toHaveBeenCalledWith([])+ expect(resetPopups).toHaveBeenCalled()+ expect(transferPendingFiles).toHaveBeenCalledTimes(transfersBeforeReset)+ })++ it("retains one TipTap editor instance while render-time configuration reruns", async () => {+ const accept = vi.fn(() => true)+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(+ createElement(Harness, acceptedProps(accept)),+ )+ })+ const firstEditor = renderer.root.findByType("controller-probe").props.view+ .editor+ await act(async () => {+ renderer.update(+ createElement(Harness, {+ ...acceptedProps(accept),+ members: [+ {+ id: "member-1",+ userId: "user-1",+ name: "Ada",+ discriminator: "0001",+ avatar: "A",+ status: "online",+ },+ ],+ }),+ )+ })+ const secondEditor = renderer.root.findByType("controller-probe").props.view+ .editor+ expect(secondEditor).toBe(firstEditor)+ expect(mocks.useEditor).toHaveBeenCalledTimes(2)+ expect(mocks.starterConfigure).toHaveBeenCalledTimes(2)+ expect(mocks.placeholderConfigure).toHaveBeenCalledTimes(2)+ })++ it("restores valid JSON without typing, dirty, or draft-write side effects", async () => {+ const doc = { type: "doc", content: [{ type: "paragraph" }] }+ const onTyping = vi.fn()+ const onDirty = vi.fn()+ mocks.readDraft.mockReturnValue(doc)+ setContent.mockImplementation(() => {+ editorOptions.onUpdate({ editor })+ })+ await act(async () => {+ TestRenderer.create(+ createElement(Harness, {+ ...acceptedProps(() => true),+ onTyping,+ onDirty,+ }),+ )+ })+ expect(mocks.readDraft).toHaveBeenCalledWith("server/channel")+ expect(setContent).toHaveBeenCalledWith(doc, {+ emitUpdate: false,+ errorOnInvalidContent: true,+ })+ expect(onTyping).not.toHaveBeenCalled()+ expect(mocks.writeDraft).not.toHaveBeenCalled()+ expect(mocks.clearDraft).not.toHaveBeenCalled()+ })++ it("clears only a corrupt draft and always releases the restoring guard", async () => {+ const onTyping = vi.fn()+ mocks.readDraft.mockReturnValue({ type: "broken" })+ setContent.mockImplementation(() => {+ throw new Error("invalid content")+ })+ await act(async () => {+ TestRenderer.create(+ createElement(Harness, {+ ...acceptedProps(() => true),+ onTyping,+ }),+ )+ })+ expect(mocks.clearDraft).toHaveBeenCalledTimes(1)+ expect(mocks.clearDraft).toHaveBeenCalledWith("server/channel")++ await act(async () => {+ editorOptions.onUpdate({ editor })+ })+ expect(onTyping).toHaveBeenCalledOnce()+ expect(mocks.writeDraft).toHaveBeenCalledWith("server/channel", {+ type: "doc",+ })+ })++ it("runs leading-edge typing and dirty transitions only from onUpdate", async () => {+ vi.useFakeTimers()+ editor.isEmpty = true+ const onTyping = vi.fn()+ const onDirty = vi.fn()+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(+ createElement(Harness, {+ ...acceptedProps(() => true),+ onTyping,+ onDirty,+ }),+ )+ })+ expect(onTyping).not.toHaveBeenCalled()+ expect(onDirty).not.toHaveBeenCalled()++ editor.isEmpty = false+ await act(async () => {+ editorOptions.onUpdate({ editor })+ editorOptions.onUpdate({ editor })+ })+ expect(onTyping).toHaveBeenCalledOnce()+ expect(onDirty).toHaveBeenCalledTimes(1)+ expect(onDirty).toHaveBeenLastCalledWith(true)+ expect(mocks.writeDraft).toHaveBeenLastCalledWith("server/channel", {+ type: "doc",+ })++ editor.isEmpty = true+ await act(async () => {+ editorOptions.onUpdate({ editor })+ })+ expect(onTyping).toHaveBeenCalledOnce()+ expect(onDirty).toHaveBeenLastCalledWith(false)+ expect(mocks.writeDraft).toHaveBeenLastCalledWith("server/channel", null)++ await act(async () => {+ vi.advanceTimersByTime(3_000)+ })+ editor.isEmpty = false+ await act(async () => {+ editorOptions.onUpdate({ editor })+ })+ expect(onTyping).toHaveBeenCalledTimes(2)+ expect(onDirty.mock.calls.map(([value]) => value)).toEqual([+ true,+ false,+ true,+ ])+ expect(vi.getTimerCount()).toBe(1)+ await act(async () => renderer.unmount())+ expect(vi.getTimerCount()).toBe(1)+ })++ it("skips all draft restore and chat focus effects in forum mode", async () => {+ const props: ComposerProps = {+ channel: "forum",+ context: "channel",+ members: [],+ sendContract: "deferred",+ mode: "forumThreadBody",+ onDeferredSubmit: vi.fn(),+ autoFocus: true,+ draftKey: "ignored/forum",+ }+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(createElement(Harness, props))+ })+ expect(mocks.readDraft).not.toHaveBeenCalled()+ expect(focus).not.toHaveBeenCalled()+ await act(async () => {+ renderer.update(+ createElement(Harness, { ...props, replyingTo: "Ada" }),+ )+ })+ expect(focus).not.toHaveBeenCalled()+ })++ it("preserves autofocus, reply edge, drop, dropdown, upload, and emoji timing", async () => {+ const accept = vi.fn(() => true)+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(+ createElement(Harness, {+ ...acceptedProps(accept),+ autoFocus: true,+ }),+ )+ })+ expect(focus).toHaveBeenCalledWith("end")+ focus.mockClear()++ await act(async () => {+ renderer.update(+ createElement(Harness, {+ ...acceptedProps(accept),+ autoFocus: true,+ members: [],+ }),+ )+ })+ expect(focus).not.toHaveBeenCalled()+ await act(async () => {+ renderer.update(+ createElement(Harness, {+ ...acceptedProps(accept),+ channel: "random",+ draftKey: "server/random",+ autoFocus: true,+ }),+ )+ })+ expect(focus).toHaveBeenCalledTimes(1)+ expect(focus).toHaveBeenLastCalledWith("end")++ focus.mockClear()+ await act(async () => {+ renderer.update(+ createElement(Harness, {+ ...acceptedProps(accept),+ channel: "random",+ draftKey: "server/random",+ replyingTo: "Ada",+ }),+ )+ })+ expect(focus).toHaveBeenCalledTimes(1)+ expect(focus).toHaveBeenLastCalledWith("end")+ await act(async () => {+ renderer.update(+ createElement(Harness, {+ ...acceptedProps(accept),+ channel: "random",+ draftKey: "server/random",+ replyingTo: "Grace",+ }),+ )+ })+ expect(focus).toHaveBeenCalledTimes(1)+ await act(async () => {+ renderer.update(+ createElement(Harness, {+ ...acceptedProps(accept),+ channel: "random",+ draftKey: "server/random",+ }),+ )+ })+ await act(async () => {+ renderer.update(+ createElement(Harness, {+ ...acceptedProps(accept),+ channel: "random",+ draftKey: "server/random",+ replyingTo: "Ada",+ }),+ )+ })+ expect(focus).toHaveBeenCalledTimes(2)++ const view = renderer.root.findByType("controller-probe").props.view+ focus.mockClear()+ await act(async () => view.onDrop({ type: "drop" }))+ expect(handleDropRaw).toHaveBeenCalledOnce()+ expect(focus).toHaveBeenCalledWith()+ expect(handleDropRaw.mock.invocationCallOrder[0]).toBeLessThan(+ focus.mock.invocationCallOrder[0],+ )++ focus.mockClear()+ view.onAttachOpenChange(true)+ expect(focus).not.toHaveBeenCalled()+ view.onAttachOpenChange(false)+ expect(focus).toHaveBeenCalledWith()++ focus.mockClear()+ view.onUploadFile()+ expect(filePickerClick).toHaveBeenCalled()+ expect(focus).toHaveBeenCalledWith()+ expect(filePickerClick.mock.invocationCallOrder.at(-1)).toBeLessThan(+ focus.mock.invocationCallOrder.at(-1),+ )++ view.onEmojiPick("🌱")+ expect(editor.chain).toHaveBeenCalled()+ expect(chainFocus).toHaveBeenCalled()+ expect(insertContent).toHaveBeenCalledWith("🌱")+ expect(run).toHaveBeenCalled()+ expect(chainFocus.mock.invocationCallOrder.at(-1)).toBeLessThan(+ insertContent.mock.invocationCallOrder.at(-1),+ )+ expect(insertContent.mock.invocationCallOrder.at(-1)).toBeLessThan(+ run.mock.invocationCallOrder.at(-1),+ )+ })++ it("uses the same single-flight gate for submitNow and checks editor plus files", async () => {+ let releaseFiles!: () => void+ const fileGate = new Promise<void>((resolve) => {+ releaseFiles = resolve+ })+ awaitPendingFiles.mockImplementation(async () => {+ await fileGate+ return pendingFiles+ })+ const accept = vi.fn(() => true)+ const handleRef = createRef<ComposerHandle>()+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(+ createElement(Harness, { ...acceptedProps(accept), ref: handleRef }),+ )+ })+ handleRef.current?.submitNow()+ handleRef.current?.submitNow()+ expect(awaitPendingFiles).toHaveBeenCalledOnce()+ expect(accept).not.toHaveBeenCalled()+ await act(async () => {+ releaseFiles()+ await fileGate+ await Promise.resolve()+ })+ expect(accept).toHaveBeenCalledOnce()++ editor.isEmpty = true+ pendingFiles = []+ await act(async () => {+ renderer.update(+ createElement(Harness, { ...acceptedProps(accept), ref: handleRef }),+ )+ })+ expect(handleRef.current?.isEmpty()).toBe(true)++ pendingFiles = [+ {+ file: new File(["x"], "pending.txt", { type: "text/plain" }),+ thumbnailUrl: null,+ thumbnailBlob: null,+ },+ ]+ await act(async () => {+ renderer.update(+ createElement(Harness, { ...acceptedProps(accept), ref: handleRef }),+ )+ })+ expect(handleRef.current?.isEmpty()).toBe(false)++ pendingFiles = []+ editor.isEmpty = false+ await act(async () => {+ renderer.update(+ createElement(Harness, { ...acceptedProps(accept), ref: handleRef }),+ )+ })+ expect(handleRef.current?.isEmpty()).toBe(false)+ })++ it("preserves the full key priority matrix and text parser pipeline", async () => {+ const accept = vi.fn(() => true)+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(+ createElement(Harness, acceptedProps(accept)),+ )+ })+ const key = (+ overrides: Partial<KeyboardEvent> = {},+ ): KeyboardEvent =>+ ({+ key: "Enter",+ shiftKey: false,+ isComposing: false,+ preventDefault: vi.fn(),+ ...overrides,+ }) as unknown as KeyboardEvent++ channelRefPopupRef.current = { items: [{}], command: vi.fn() }+ expect(editorOptions.editorProps.handleKeyDown({} as never, key())).toBe(+ false,+ )+ expect(accept).not.toHaveBeenCalled()+ channelRefPopupRef.current = { items: [], command: vi.fn() }+ expect(+ editorOptions.editorProps.handleKeyDown(+ {} as never,+ key({ shiftKey: true }),+ ),+ ).toBe(false)+ expect(+ editorOptions.editorProps.handleKeyDown(+ {} as never,+ key({ isComposing: true }),+ ),+ ).toBe(false)+ expect(accept).not.toHaveBeenCalled()++ const forumProps: ComposerProps = {+ channel: "forum",+ context: "channel",+ members: [],+ sendContract: "deferred",+ mode: "forumThreadBody",+ onDeferredSubmit: vi.fn(),+ }+ await act(async () => {+ renderer.update(createElement(Harness, forumProps))+ })+ const forumSubmit = forumProps.onDeferredSubmit+ expect(editorOptions.editorProps.handleKeyDown({} as never, key())).toBe(+ false,+ )+ expect(+ editorOptions.editorProps.handleKeyDown(+ {} as never,+ key({ shiftKey: true, isComposing: true }),+ ),+ ).toBe(false)+ expect(forumSubmit).not.toHaveBeenCalled()++ const dom = { nodeName: "DIV" }+ const slice = { openStart: 1, openEnd: 1 }+ const schema = { name: "schema" }+ const context = { doc: { type: { schema } } }+ mocks.buildPasteDom.mockReturnValue(dom)+ mocks.parseSlice.mockReturnValue(slice)+ vi.stubGlobal("document", { body: {} })+ expect(+ editorOptions.editorProps.clipboardTextParser(+ "first\nsecond\n\nthird",+ context as never,+ ),+ ).toBe(slice)+ expect(mocks.buildPasteDom).toHaveBeenCalledWith(+ "first\nsecond\n\nthird",+ document,+ )+ expect(mocks.fromSchema).toHaveBeenCalledWith(schema)+ expect(mocks.parseSlice).toHaveBeenCalledWith(dom, {+ preserveWhitespace: true,+ context,+ })+ })++ it("pins the layout/draft/typing ordering boundaries in source", () => {+ const source = readFileSync(new URL("./use-composer-controller.ts", import.meta.url), "utf8")+ const gate = source.indexOf("if (!editor || sendInFlightRef.current) return")+ const awaitFiles = source.indexOf("await awaitPendingFiles()")+ const secondCheck = source.indexOf("lifecycleVersionRef.current !== attemptLifecycle")+ const empty = source.indexOf("editor.isEmpty && preparedFiles.length === 0")+ const markdown = source.indexOf("const markdown =")+ expect(gate).toBeLessThan(awaitFiles)+ expect(awaitFiles).toBeLessThan(secondCheck)+ expect(secondCheck).toBeLessThan(empty)+ expect(empty).toBeLessThan(markdown)+ expect(source).toContain("sendRef.current = send")+ expect(source).toContain("useLayoutEffect(")+ expect(source).toContain("emitUpdate: false")+ expect(source).toContain("errorOnInvalidContent: true")+ expect(source).toContain("restoringDraftRef.current = false")+ expect(source).toContain("3_000")+ expect(source).not.toContain("clearTimeout(")+ })+})diff --git a/src/web/src/components/community/messages/use-composer-controller.ts b/src/web/src/components/community/messages/use-composer-controller.tsnew file mode 100644index 000000000..c94e08746--- /dev/null+++ b/src/web/src/components/community/messages/use-composer-controller.ts@@ -0,0 +1,347 @@+import {+ useEffect,+ useImperativeHandle,+ useLayoutEffect,+ useRef,+ type DragEvent,+ type ForwardedRef,+} from "react"+import { useEditor, type JSONContent } from "@tiptap/react"+import StarterKit from "@tiptap/starter-kit"+import Placeholder from "@tiptap/extension-placeholder"+import { DOMParser as PMDOMParser } from "@tiptap/pm/model"+import { MAX_ATTACHMENT_SIZE_BYTES } from "@alook/shared"+import { useFileAttachments } from "@/hooks/use-file-attachments"+import {+ clearComposerDraft,+ readComposerDraft,+ writeComposerDraft,+} from "@/lib/community/composer-draft"+import { detectMentionType } from "@/lib/community/mention-extension"+import { buildPasteDom } from "@/lib/community/paste-plain-text"+import { clipboardFiles, pendingFilesToSendAttachments } from "./composer-file-utils"+import type { ComposerHandle, ComposerProps } from "./composer-types"+import type { ComposerViewProps } from "./composer-view"+import { useComposerSuggestions } from "./use-composer-suggestions"++export function useComposerController(+ {+ channel,+ context,+ members,+ onSearchMembers,+ channelRefCandidates = [],+ onChannelRefIntent,+ sendContract,+ onAcceptSend,+ onDeferredSubmit,+ onTyping,+ replyingTo,+ onCancelReply,+ autoFocus = false,+ mode = "chat",+ placeholder,+ hideEmoji = false,+ hideAttach = false,+ onDirty,+ draftKey,+ }: ComposerProps,+ ref: ForwardedRef<ComposerHandle>,+): ComposerViewProps {+ const isForumThreadBody = mode === "forumThreadBody"+ const attachments = useFileAttachments({+ maxFileSize: MAX_ATTACHMENT_SIZE_BYTES,+ })+ const {+ pendingFiles,+ setPendingFiles,+ transferPendingFiles,+ awaitPendingFiles,+ addPendingFiles,+ fileInputRef,+ handleFileSelect,+ removePendingFile,+ dragging,+ handleDragEnter,+ handleDragLeave,+ handleDragOver,+ handleDrop: handleDropRaw,+ } = attachments+ const typingTimer = useRef<NodeJS.Timeout | null>(null)+ const sendRef = useRef<() => void>(() => {})+ const sendInFlightRef = useRef<Promise<void> | null>(null)+ const lifecycleVersionRef = useRef(0)+ const draftKeyRef = useRef(draftKey)+ const sendScopeRef = useRef<string | null>(null)+ const sendScopeVersionRef = useRef(0)+ useLayoutEffect(() => {+ const nextScope = `${context}\u0000${channel}\u0000${draftKey ?? ""}`+ if (sendScopeRef.current !== nextScope) {+ sendScopeRef.current = nextScope+ sendScopeVersionRef.current+++ }+ draftKeyRef.current = draftKey+ }, [channel, context, draftKey])+ useLayoutEffect(+ () => () => {+ lifecycleVersionRef.current+++ },+ [],+ )+ const restoringDraftRef = useRef(false)++ const suggestions = useComposerSuggestions({+ members,+ context,+ onSearchMembers,+ channelRefCandidates,+ onChannelRefIntent,+ })++ const fireTyping = () => {+ if (!onTyping || typingTimer.current) return+ onTyping()+ typingTimer.current = setTimeout(() => {+ typingTimer.current = null+ }, 3_000)+ }++ const editor = useEditor({+ immediatelyRender: false,+ extensions: [+ StarterKit.configure({+ heading: false,+ horizontalRule: false,+ codeBlock: false,+ code: false,+ blockquote: false,+ bold: false,+ italic: false,+ strike: false,+ bulletList: false,+ orderedList: false,+ listItem: false,+ listKeymap: false,+ }),+ Placeholder.configure({+ placeholder:+ placeholder ??+ (context === "channel" ? `Message /${channel}` : `Message ${channel}`),+ }),+ suggestions.mentionExtension,+ suggestions.channelRefExtension,+ ],+ editorProps: {+ attributes: {+ class: "outline-none",+ enterkeyhint: isForumThreadBody ? "enter" : "send",+ },+ handleKeyDown: (_view, event) => {+ const mentionOpen =+ suggestions.mentionPopupRef.current.items.length > 0 &&+ suggestions.mentionPopupRef.current.command !== null+ const channelRefOpen =+ suggestions.channelRefPopupRef.current.items.length > 0 &&+ suggestions.channelRefPopupRef.current.command !== null+ if (mentionOpen || channelRefOpen) return false+ if (isForumThreadBody) {+ if (+ event.key === "Enter" &&+ event.shiftKey &&+ !event.isComposing+ ) {+ event.preventDefault()+ sendRef.current()+ return true+ }+ return false+ }+ if (+ event.key === "Enter" &&+ !event.shiftKey &&+ !event.isComposing+ ) {+ event.preventDefault()+ sendRef.current()+ return true+ }+ return false+ },+ handlePaste: (_view, event) => {+ const files = clipboardFiles(event.clipboardData?.items)+ if (files.length === 0) return false+ event.preventDefault()+ addPendingFiles(files)+ return true+ },+ clipboardTextParser: (text, $context) => {+ const dom = buildPasteDom(text, document)+ return PMDOMParser.fromSchema($context.doc.type.schema).parseSlice(dom, {+ preserveWhitespace: true,+ context: $context,+ })+ },+ },+ onUpdate: ({ editor: updatedEditor }) => {+ if (restoringDraftRef.current) return+ fireTyping()+ emitDirtyTransition()+ const key = draftKeyRef.current+ if (key && !isForumThreadBody) {+ writeComposerDraft(+ key,+ updatedEditor.isEmpty ? null : updatedEditor.getJSON(),+ )+ }+ },+ })++ useEffect(() => {+ if (!editor || isForumThreadBody || !draftKey) return+ const doc = readComposerDraft(draftKey)+ if (!doc) return+ restoringDraftRef.current = true+ try {+ editor.commands.setContent(doc as JSONContent, {+ emitUpdate: false,+ errorOnInvalidContent: true,+ })+ } catch {+ clearComposerDraft(draftKey)+ } finally {+ restoringDraftRef.current = false+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [editor, draftKey])++ const previousHasContentRef = useRef(false)+ const onDirtyRef = useRef(onDirty)+ useEffect(() => {+ onDirtyRef.current = onDirty+ }, [onDirty])+ const emitDirtyTransition = () => {+ if (!editor) return+ const next = !editor.isEmpty || pendingFiles.length > 0+ if (next === previousHasContentRef.current) return+ previousHasContentRef.current = next+ onDirtyRef.current?.(next)+ }+ useEffect(() => {+ emitDirtyTransition()+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [pendingFiles, editor])++ const send = () => {+ if (!editor || sendInFlightRef.current) return+ const attemptScopeVersion = sendScopeVersionRef.current+ const attemptLifecycle = lifecycleVersionRef.current+ const attempt = (async () => {+ const preparedFiles = await awaitPendingFiles()+ if (+ lifecycleVersionRef.current !== attemptLifecycle ||+ sendScopeVersionRef.current !== attemptScopeVersion+ ) return+ if (editor.isEmpty && preparedFiles.length === 0) return+ const markdown = editor.isEmpty+ ? ""+ : editor.getText({ blockSeparator: "\n\n" }).trim()+ const mentionType = detectMentionType(markdown)+ const payload = pendingFilesToSendAttachments([...preparedFiles])+ if (sendContract === "accepted") {+ if (!onAcceptSend?.(markdown, payload, mentionType)) return+ } else {+ await onDeferredSubmit?.(markdown, payload, mentionType)+ }+ if (isForumThreadBody) return+ editor.commands.clearContent()+ if (draftKeyRef.current) clearComposerDraft(draftKeyRef.current)+ transferPendingFiles()+ suggestions.resetPopups()+ })()+ sendInFlightRef.current = attempt+ void attempt.then(+ () => {+ if (sendInFlightRef.current === attempt) {+ sendInFlightRef.current = null+ }+ },+ () => {+ if (sendInFlightRef.current === attempt) {+ sendInFlightRef.current = null+ }+ },+ )+ }++ useLayoutEffect(() => {+ sendRef.current = send+ })++ useImperativeHandle(ref, () => ({+ focusEditor: () => {+ editor?.commands.focus("end")+ },+ submitNow: () => {+ send()+ },+ resetAfterSubmit: () => {+ if (!editor) return+ editor.commands.clearContent()+ setPendingFiles([])+ suggestions.resetPopups()+ },+ isEmpty: () => !editor || (editor.isEmpty && pendingFiles.length === 0),+ openFilePicker: () => {+ fileInputRef.current?.click()+ },+ }))++ useEffect(() => {+ if (!autoFocus || !editor || isForumThreadBody) return+ editor.commands.focus("end")+ }, [autoFocus, editor, channel, isForumThreadBody])++ const previousReplyingToRef = useRef(replyingTo)+ useEffect(() => {+ const opened = !previousReplyingToRef.current && !!replyingTo+ previousReplyingToRef.current = replyingTo+ if (opened && editor && !isForumThreadBody) {+ editor.commands.focus("end")+ }+ }, [replyingTo, editor, isForumThreadBody])++ const handleDrop = (event: DragEvent<HTMLDivElement>) => {+ handleDropRaw(event)+ editor?.commands.focus()+ }++ return {+ isForumThreadBody,+ dragging,+ onDragEnter: handleDragEnter,+ onDragLeave: handleDragLeave,+ onDragOver: handleDragOver,+ onDrop: handleDrop,+ mentionPopup: suggestions.mentionPopup,+ channelRefPopup: suggestions.channelRefPopup,+ replyingTo,+ onCancelReply,+ pendingFiles,+ removePendingFile,+ fileInputRef,+ onFileSelect: handleFileSelect,+ editor,+ hideAttach,+ hideEmoji,+ onAttachOpenChange: (open) => {+ if (!open) editor?.commands.focus()+ },+ onUploadFile: () => {+ fileInputRef.current?.click()+ editor?.commands.focus()+ },+ onEmojiPick: (emoji) => {+ editor?.chain().focus().insertContent(emoji).run()+ },+ }+}diff --git a/src/web/src/components/community/messages/use-composer-suggestions.test.ts b/src/web/src/components/community/messages/use-composer-suggestions.test.tsnew file mode 100644index 000000000..3791f7853--- /dev/null+++ b/src/web/src/components/community/messages/use-composer-suggestions.test.ts@@ -0,0 +1,383 @@+import { createElement, useEffect } from "react"+import TestRenderer, { act } from "react-test-renderer"+import { beforeEach, describe, expect, it, vi } from "vitest"++const mocks = vi.hoisted(() => ({+ buildMention: vi.fn(),+ buildChannel: vi.fn(),+ rankMention: vi.fn(),+ rankChannel: vi.fn(),+}))++vi.mock("@/lib/community/mention-extension", () => ({+ EMPTY_MENTION_STATE: {+ items: [],+ selectedIndex: 0,+ command: null,+ rect: null,+ },+ buildCommunityMentionExtension: (...args: unknown[]) =>+ mocks.buildMention(...args),+ rankMentionItems: (...args: unknown[]) => mocks.rankMention(...args),+}))++vi.mock("@/lib/community/channel-ref-extension", () => ({+ EMPTY_CHANNEL_REF_STATE: {+ items: [],+ selectedIndex: 0,+ command: null,+ rect: null,+ },+ buildCommunityChannelRefExtension: (...args: unknown[]) =>+ mocks.buildChannel(...args),+ rankChannelRefItems: (...args: unknown[]) => mocks.rankChannel(...args),+}))++import { useComposerSuggestions } from "./use-composer-suggestions"+import type { ChannelRefCandidate } from "@/lib/community/channel-ref-extension"+import type { Member } from "@/lib/community/models/people"++type Options = Parameters<typeof useComposerSuggestions>[0]+type Result = ReturnType<typeof useComposerSuggestions>++function Harness({+ resultRef,+ ...options+}: Options & { resultRef: { current: Result | null } }) {+ const result = useComposerSuggestions(options)+ useEffect(() => {+ resultRef.current = result+ }, [result, resultRef])+ return createElement("suggestions-probe")+}++const member = (overrides: Partial<Member> = {}): Member =>+ ({+ id: "member-1",+ userId: "user-1",+ name: "Ada",+ discriminator: "0001",+ avatar: "A",+ status: "online",+ ...overrides,+ }) as Member++const channel = (+ overrides: Partial<ChannelRefCandidate> = {},+): ChannelRefCandidate => ({+ id: "channel-1",+ name: "general",+ serverId: "server-1",+ serverName: "One",+ ...overrides,+})++describe("useComposerSuggestions", () => {+ beforeEach(() => {+ mocks.buildMention.mockReset()+ mocks.buildChannel.mockReset()+ mocks.rankMention.mockReset()+ mocks.rankChannel.mockReset()+ mocks.buildMention.mockImplementation((options) => ({+ name: "mention-extension",+ runQuery: (query: string) => {+ options.queryRef.current = query+ options.onSearchMembersRef.current?.(query)+ return mocks.rankMention(+ options.membersRef.current,+ options.contextRef.current,+ query,+ )+ },+ }))+ mocks.buildChannel.mockImplementation((options) => ({+ name: "channel-extension",+ runQuery: (query: string) => {+ options.queryRef.current = query+ options.onIntentRef.current?.()+ return mocks.rankChannel(options.candidatesRef.current, query)+ },+ }))+ mocks.rankMention.mockReturnValue([])+ mocks.rankChannel.mockReturnValue([])+ })++ it("builds only the two custom extensions once and refreshes live refs", async () => {+ const resultRef: { current: Result | null } = { current: null }+ const firstMembers = [member()]+ const firstChannels = [channel()]+ const firstSearch = vi.fn()+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(+ createElement(Harness, {+ members: firstMembers,+ context: "channel",+ onSearchMembers: firstSearch,+ channelRefCandidates: firstChannels,+ onChannelRefIntent: vi.fn(),+ resultRef,+ }),+ )+ })+ const firstMentionExtension = resultRef.current!.mentionExtension+ const firstChannelExtension = resultRef.current!.channelRefExtension+ const mentionOptions = mocks.buildMention.mock.calls[0][0]+ const channelOptions = mocks.buildChannel.mock.calls[0][0]++ const nextMembers = [member({ avatar: "B", status: "offline" })]+ const nextChannels = [channel({ serverName: "Two" })]+ const nextSearch = vi.fn()+ const nextIntent = vi.fn()+ await act(async () => {+ renderer.update(+ createElement(Harness, {+ members: nextMembers,+ context: "thread",+ onSearchMembers: nextSearch,+ channelRefCandidates: nextChannels,+ onChannelRefIntent: nextIntent,+ resultRef,+ }),+ )+ })++ expect(mocks.buildMention).toHaveBeenCalledOnce()+ expect(mocks.buildChannel).toHaveBeenCalledOnce()+ expect(resultRef.current!.mentionExtension).toBe(firstMentionExtension)+ expect(resultRef.current!.channelRefExtension).toBe(firstChannelExtension)+ expect(mentionOptions.membersRef.current).toBe(nextMembers)+ expect(mentionOptions.contextRef.current).toBe("thread")+ expect(mentionOptions.onSearchMembersRef.current).toBe(nextSearch)+ expect(channelOptions.candidatesRef.current).toBe(nextChannels)+ expect(channelOptions.onIntentRef.current).toBe(nextIntent)++ await act(async () => {+ mentionOptions.setPopup({+ items: [],+ selectedIndex: 0,+ command: vi.fn(),+ rect: null,+ })+ channelOptions.setPopup({+ items: [],+ selectedIndex: 0,+ command: vi.fn(),+ rect: null,+ })+ })++ mocks.rankMention.mockReturnValue([{ id: "latest-member" }])+ const mentionResult = (+ resultRef.current!.mentionExtension as unknown as {+ runQuery: (query: string) => unknown+ }+ ).runQuery("ad")+ expect(mentionResult).toEqual([{ id: "latest-member" }])+ expect(nextSearch).toHaveBeenCalledWith("ad")+ expect(mocks.rankMention).toHaveBeenLastCalledWith(+ nextMembers,+ "thread",+ "ad",+ )++ mocks.rankChannel.mockReturnValue([{ id: "latest-channel" }])+ const channelResult = (+ resultRef.current!.channelRefExtension as unknown as {+ runQuery: (query: string) => unknown+ }+ ).runQuery("gen")+ expect(channelResult).toEqual([{ id: "latest-channel" }])+ expect(nextIntent).toHaveBeenCalledOnce()+ expect(mocks.rankChannel).toHaveBeenLastCalledWith(nextChannels, "gen")++ const thirdMembers = [member({ name: "Ada Latest" })]+ const thirdChannels = [channel({ name: "general-latest" })]+ await act(async () => {+ renderer.update(+ createElement(Harness, {+ members: thirdMembers,+ context: "thread",+ onSearchMembers: nextSearch,+ channelRefCandidates: thirdChannels,+ onChannelRefIntent: nextIntent,+ resultRef,+ }),+ )+ })+ expect(mocks.rankMention).toHaveBeenLastCalledWith(+ thirdMembers,+ "thread",+ "ad",+ )+ expect(mocks.rankChannel).toHaveBeenLastCalledWith(thirdChannels, "gen")+ })++ it("reranks open mentions, preserves valid selection, and detects visual changes", async () => {+ const resultRef: { current: Result | null } = { current: null }+ const initialItem = {+ kind: "member" as const,+ id: "member-1",+ userId: "user-1",+ label: "Ada#0001",+ name: "Ada",+ discriminator: "0001",+ avatar: "A",+ status: "online" as const,+ }+ const secondItem = { ...initialItem, id: "member-2", userId: "user-2" }+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(+ createElement(Harness, {+ members: [member()],+ context: "channel",+ channelRefCandidates: [],+ resultRef,+ }),+ )+ })+ const options = mocks.buildMention.mock.calls[0][0]+ await act(async () => {+ options.setPopup({+ items: [initialItem, secondItem],+ selectedIndex: 1,+ command: vi.fn(),+ rect: null,+ })+ })++ const unchangedState = resultRef.current!.mentionPopup+ mocks.rankMention.mockReturnValue([initialItem, secondItem])+ await act(async () => {+ renderer.update(+ createElement(Harness, {+ members: [member({ name: "Ada Lovelace" })],+ context: "channel",+ channelRefCandidates: [],+ resultRef,+ }),+ )+ })+ expect(resultRef.current!.mentionPopup).toBe(unchangedState)++ mocks.rankMention.mockReturnValue([+ { ...initialItem, status: "offline" },+ secondItem,+ ])+ await act(async () => {+ renderer.update(+ createElement(Harness, {+ members: [member({ status: "offline" })],+ context: "channel",+ channelRefCandidates: [],+ resultRef,+ }),+ )+ })+ expect(resultRef.current!.mentionPopup.items[0]).toMatchObject({+ status: "offline",+ })+ expect(resultRef.current!.mentionPopup.selectedIndex).toBe(1)++ mocks.rankMention.mockReturnValue([{ ...initialItem, avatar: "C" }])+ await act(async () => {+ renderer.update(+ createElement(Harness, {+ members: [member({ avatar: "C" })],+ context: "thread",+ channelRefCandidates: [],+ resultRef,+ }),+ )+ })+ expect(resultRef.current!.mentionPopup.selectedIndex).toBe(0)+ })++ it("keeps channel state when only serverName changes and resets both popups", async () => {+ const resultRef: { current: Result | null } = { current: null }+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(+ createElement(Harness, {+ members: [],+ context: "dm",+ channelRefCandidates: [channel()],+ resultRef,+ }),+ )+ })+ const mentionOptions = mocks.buildMention.mock.calls[0][0]+ const channelOptions = mocks.buildChannel.mock.calls[0][0]+ await act(async () => {+ mentionOptions.setPopup({+ items: [{ kind: "everyone", id: "everyone", label: "everyone" }],+ selectedIndex: 0,+ command: vi.fn(),+ rect: null,+ })+ channelOptions.setPopup({+ items: [channel()],+ selectedIndex: 0,+ command: vi.fn(),+ rect: null,+ })+ })+ const previousState = resultRef.current!.channelRefPopup+ mocks.rankChannel.mockReturnValue([channel({ serverName: "Two" })])+ await act(async () => {+ renderer.update(+ createElement(Harness, {+ members: [],+ context: "dm",+ channelRefCandidates: [channel({ serverName: "Two" })],+ resultRef,+ }),+ )+ })+ expect(resultRef.current!.channelRefPopup).toBe(previousState)+ expect(resultRef.current!.channelRefPopup.items[0].serverName).toBe("One")++ const second = channel({ id: "channel-2", name: "random" })+ await act(async () => {+ channelOptions.setPopup({+ items: [channel(), second],+ selectedIndex: 1,+ command: vi.fn(),+ rect: null,+ })+ })+ mocks.rankChannel.mockReturnValue([+ channel({ name: "general-updated" }),+ second,+ ])+ await act(async () => {+ renderer.update(+ createElement(Harness, {+ members: [],+ context: "dm",+ channelRefCandidates: [channel({ name: "general-updated" }), second],+ resultRef,+ }),+ )+ })+ expect(resultRef.current!.channelRefPopup.selectedIndex).toBe(1)++ mocks.rankChannel.mockReturnValue([channel({ name: "final" })])+ await act(async () => {+ renderer.update(+ createElement(Harness, {+ members: [],+ context: "dm",+ channelRefCandidates: [channel({ name: "final" })],+ resultRef,+ }),+ )+ })+ expect(resultRef.current!.channelRefPopup.selectedIndex).toBe(0)++ await act(async () => resultRef.current!.resetPopups())+ expect(resultRef.current!.mentionPopup.command).toBeNull()+ expect(resultRef.current!.channelRefPopup.command).toBeNull()+ })+})diff --git a/src/web/src/components/community/messages/use-composer-suggestions.ts b/src/web/src/components/community/messages/use-composer-suggestions.tsnew file mode 100644index 000000000..c0df5c74c--- /dev/null+++ b/src/web/src/components/community/messages/use-composer-suggestions.ts@@ -0,0 +1,176 @@+import { useEffect, useRef, useState } from "react"+import {+ buildCommunityMentionExtension,+ EMPTY_MENTION_STATE,+ rankMentionItems,+ type MentionContext,+ type MentionItem,+ type MentionPopupState,+} from "@/lib/community/mention-extension"+import {+ buildCommunityChannelRefExtension,+ EMPTY_CHANNEL_REF_STATE,+ rankChannelRefItems,+ type ChannelRefCandidate,+ type ChannelRefPopupState,+} from "@/lib/community/channel-ref-extension"+import type { Member } from "@/lib/community/models/people"++type ComposerSuggestionsOptions = {+ members: Member[]+ context: MentionContext+ onSearchMembers?: (query: string) => void+ channelRefCandidates: ChannelRefCandidate[]+ onChannelRefIntent?: () => void+}++function mentionItemsEqual(a: MentionItem[], b: MentionItem[]): boolean {+ if (a === b) return true+ if (a.length !== b.length) return false+ for (let index = 0; index < a.length; index++) {+ const current = a[index]+ const next = b[index]+ if (+ current.kind !== next.kind ||+ current.id !== next.id ||+ current.label !== next.label+ ) return false+ if (current.kind === "member" && next.kind === "member") {+ if (+ current.avatar !== next.avatar ||+ current.status !== next.status+ ) return false+ }+ }+ return true+}++function channelRefItemsEqual(+ a: ChannelRefCandidate[],+ b: ChannelRefCandidate[],+): boolean {+ if (a === b) return true+ if (a.length !== b.length) return false+ for (let index = 0; index < a.length; index++) {+ if (+ a[index].id !== b[index].id ||+ a[index].name !== b[index].name ||+ a[index].serverId !== b[index].serverId+ ) return false+ }+ return true+}++export function useComposerSuggestions({+ members,+ context,+ onSearchMembers,+ channelRefCandidates,+ onChannelRefIntent,+}: ComposerSuggestionsOptions) {+ const [mentionPopup, setMentionPopup] = useState<MentionPopupState>(+ EMPTY_MENTION_STATE,+ )+ const mentionPopupRef = useRef(mentionPopup)+ useEffect(() => {+ mentionPopupRef.current = mentionPopup+ }, [mentionPopup])++ const [channelRefPopup, setChannelRefPopup] =+ useState<ChannelRefPopupState>(EMPTY_CHANNEL_REF_STATE)+ const channelRefPopupRef = useRef(channelRefPopup)+ useEffect(() => {+ channelRefPopupRef.current = channelRefPopup+ }, [channelRefPopup])++ const membersRef = useRef(members)+ const contextRef = useRef(context)+ const onSearchMembersRef = useRef(onSearchMembers)+ const mentionQueryRef = useRef("")+ useEffect(() => {+ membersRef.current = members+ }, [members])+ useEffect(() => {+ contextRef.current = context+ }, [context])+ useEffect(() => {+ onSearchMembersRef.current = onSearchMembers+ }, [onSearchMembers])++ // eslint-disable-next-line react-hooks/refs -- runtime suggestion callbacks read these refs+ const [mentionExtension] = useState(() =>+ buildCommunityMentionExtension({+ membersRef,+ contextRef,+ popupRef: mentionPopupRef,+ setPopup: setMentionPopup,+ onSearchMembersRef,+ queryRef: mentionQueryRef,+ }),+ )++ const channelRefCandidatesRef = useRef(channelRefCandidates)+ const onChannelRefIntentRef = useRef(onChannelRefIntent)+ const channelRefQueryRef = useRef("")+ useEffect(() => {+ channelRefCandidatesRef.current = channelRefCandidates+ }, [channelRefCandidates])+ useEffect(() => {+ onChannelRefIntentRef.current = onChannelRefIntent+ }, [onChannelRefIntent])++ // eslint-disable-next-line react-hooks/refs -- runtime suggestion callbacks read these refs+ const [channelRefExtension] = useState(() =>+ buildCommunityChannelRefExtension({+ candidatesRef: channelRefCandidatesRef,+ popupRef: channelRefPopupRef,+ onIntentRef: onChannelRefIntentRef,+ setPopup: setChannelRefPopup,+ queryRef: channelRefQueryRef,+ }),+ )++ useEffect(() => {+ const current = mentionPopupRef.current+ if (!current.command) return+ const items = rankMentionItems(members, context, mentionQueryRef.current)+ if (mentionItemsEqual(current.items, items)) return+ setMentionPopup({+ ...current,+ items,+ selectedIndex:+ current.selectedIndex < items.length ? current.selectedIndex : 0,+ })+ }, [members, context])++ useEffect(() => {+ const current = channelRefPopupRef.current+ if (!current.command) return+ const items = rankChannelRefItems(+ channelRefCandidates,+ channelRefQueryRef.current,+ )+ if (channelRefItemsEqual(current.items, items)) return+ setChannelRefPopup({+ ...current,+ items,+ selectedIndex:+ current.selectedIndex < items.length ? current.selectedIndex : 0,+ })+ }, [channelRefCandidates])++ const resetPopups = () => {+ setMentionPopup(EMPTY_MENTION_STATE)+ setChannelRefPopup(EMPTY_CHANNEL_REF_STATE)+ }++ return {+ mentionPopup,+ mentionPopupRef,+ mentionExtension,+ channelRefPopup,+ channelRefPopupRef,+ channelRefExtension,+ resetPopups,+ }+}diff --git a/src/web/src/components/community/virtual-cursor-list.tsx b/src/web/src/components/community/messages/virtual-cursor-list.tsxsimilarity index 100%rename from src/web/src/components/community/virtual-cursor-list.tsxrename to src/web/src/components/community/messages/virtual-cursor-list.tsxdiff --git a/src/web/src/components/community/virtualizer-direct-dom.contract.test.ts b/src/web/src/components/community/messages/virtualizer-direct-dom.contract.test.tssimilarity index 89%rename from src/web/src/components/community/virtualizer-direct-dom.contract.test.tsrename to src/web/src/components/community/messages/virtualizer-direct-dom.contract.test.tsindex 509dfdf09..8b066bb0f 100644--- a/src/web/src/components/community/virtualizer-direct-dom.contract.test.ts+++ b/src/web/src/components/community/messages/virtualizer-direct-dom.contract.test.ts@@ -4,7 +4,7 @@ import path from "node:path"import { fileURLToPath } from "node:url"const componentDirectory = path.dirname(fileURLToPath(import.meta.url))-const hooksDirectory = path.resolve(componentDirectory, "../../hooks/community")+const hooksDirectory = path.resolve(componentDirectory, "../../../hooks/community")const readComponent = (name: string) => fs.readFileSync(path.join(componentDirectory, name), "utf8")describe("community virtualizer direct DOM contract", () => {@@ -23,7 +23,7 @@ describe("community virtualizer direct DOM contract", () => {})it("keeps ForumView on the shared direct DOM row contract", () => {- const forumView = readComponent("forum-view.tsx")+ const forumView = readComponent("../channels/forum-view.tsx")expect(forumView).toContain("...COMMUNITY_VIRTUALIZER_REACT_OPTIONS")expect(forumView).toContain("<VirtualRows")@@ -32,7 +32,7 @@ describe("community virtualizer direct DOM contract", () => {})it("gives MemberList container size and row position ownership to the virtualizer", () => {- const memberList = readComponent("member-list.tsx")+ const memberList = readComponent("../members/member-list.tsx")expect(memberList).toContain("...COMMUNITY_VIRTUALIZER_REACT_OPTIONS")expect(memberList).toContain("ref={rowVirtualizer.containerRef}")@@ -43,7 +43,7 @@ describe("community virtualizer direct DOM contract", () => {})it("gives SettingsMembers container size and row position ownership to the virtualizer", () => {- const serverSettings = readComponent("server-settings.tsx")+ const serverSettings = readComponent("../settings/server-settings.tsx")expect(serverSettings).toContain("...COMMUNITY_VIRTUALIZER_REACT_OPTIONS")expect(serverSettings).toContain("ref={rowVirtualizer.containerRef}")diff --git a/src/web/src/components/community/onboarding/community-onboarding-guide-controller.test.ts b/src/web/src/components/community/onboarding/community-onboarding-guide-controller.test.tsnew file mode 100644index 000000000..90aaf0397--- /dev/null+++ b/src/web/src/components/community/onboarding/community-onboarding-guide-controller.test.ts@@ -0,0 +1,841 @@+import { readFileSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import React from "react";+import TestRenderer, { act } from "react-test-renderer";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { CommunityOnboardingState } from "@/lib/community-onboarding";+import type { CommunityOnboardingGuideController } from "./community-onboarding-guide-types";++const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..");+const readWebSource = (path: string) => readFileSync(resolve(webRoot, path), "utf8");++const mocks = vi.hoisted(() => ({+ hookOrder: [] as string[],+ pathname: "/c/me",+ machines: [] as Array<{ id: string; status: "online" | "offline" }>,+ machinesSuccess: false,+ bots: [] as Array<{ id: string; machineId: string }>,+ botsSuccess: false,+ state: null as CommunityOnboardingState | null,+ router: { replace: vi.fn(), push: vi.fn() },+ advance: vi.fn(),+ recover: vi.fn(),+ skip: vi.fn(),+ driverFactory: vi.fn(),+ waitForTarget: vi.fn(),+ isUsable: vi.fn(),+ inViewport: vi.fn(),+ nextFrame: vi.fn(),+ side: vi.fn(),+ pin: vi.fn(),+ position: vi.fn(),+ shouldRoute: vi.fn(),+ dismiss: vi.fn(),+}));++vi.mock("next/navigation", () => ({+ useRouter: () => {+ mocks.hookOrder.push("router");+ return mocks.router;+ },+ usePathname: () => {+ mocks.hookOrder.push("pathname");+ return mocks.pathname;+ },+}));+vi.mock("@/hooks/community/use-machines", () => ({+ useMachines: () => {+ mocks.hookOrder.push("machines");+ return { machines: mocks.machines, isSuccess: mocks.machinesSuccess };+ },+}));+vi.mock("@/hooks/community/use-bots", () => ({+ useBots: () => {+ mocks.hookOrder.push("bots");+ return { bots: mocks.bots, isSuccess: mocks.botsSuccess };+ },+}));+vi.mock("@/lib/community-onboarding", () => ({+ useCommunityOnboarding: () => {+ mocks.hookOrder.push("onboarding");+ return mocks.state;+ },+ advanceCommunityOnboarding: mocks.advance,+ recoverCommunityOnboardingMachine: mocks.recover,+ skipCommunityOnboarding: mocks.skip,+}));+vi.mock("driver.js", () => ({ driver: mocks.driverFactory }));+vi.mock("./community-onboarding-guide-target", () => ({+ dismissGuideOnTargetClick: mocks.dismiss,+ guidePopoverSide: mocks.side,+ isGuideTargetUsable: mocks.isUsable,+ nextFrame: mocks.nextFrame,+ pinPopoverAwayFromTarget: mocks.pin,+ positionFocusAvatar: mocks.position,+ shouldAutoRouteGuide: mocks.shouldRoute,+ targetIsInViewport: mocks.inViewport,+ waitForTarget: mocks.waitForTarget,+}));++import { useCommunityOnboardingGuideController } from "./community-onboarding-guide-controller";++let latest!: CommunityOnboardingGuideController;+const renderers: TestRenderer.ReactTestRenderer[] = [];+function deferred<T>() {+ let resolve!: (value: T | PromiseLike<T>) => void;+ let reject!: (reason?: unknown) => void;+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });+ return { promise, resolve, reject };+}++function Probe() {+ const controller = useCommunityOnboardingGuideController();+ React.useEffect(() => {+ latest = controller;+ }, [controller]);+ return null;+}++describe("useCommunityOnboardingGuideController", () => {+ const bodyAdd = vi.fn();+ const bodyRemove = vi.fn();+ const appendChild = vi.fn();+ const windowAdd = vi.fn();+ const windowRemove = vi.fn();+ const viewportAdd = vi.fn();+ const viewportRemove = vi.fn();+ const cancelAnimationFrame = vi.fn();+ const avatarRemove = vi.fn();+ const avatar = { className: "", style: {}, remove: avatarRemove } as unknown as HTMLElement;+ const candidate = {+ scrollIntoView: vi.fn(),+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ } as unknown as HTMLElement;+ const instance = {+ destroy: vi.fn(),+ refresh: vi.fn(),+ highlight: vi.fn(),+ getActiveElement: vi.fn(() => candidate),+ };+ let driverOptions: Record<string, unknown> | undefined;+ let rafCallback: FrameRequestCallback | undefined;+ const requestAnimationFrame = vi.fn((callback: FrameRequestCallback) => {+ rafCallback = callback;+ return 41;+ });++ beforeEach(() => {+ vi.clearAllMocks();+ mocks.hookOrder.length = 0;+ mocks.pathname = "/c/me";+ mocks.machines = [];+ mocks.machinesSuccess = false;+ mocks.bots = [];+ mocks.botsSuccess = false;+ mocks.state = null;+ mocks.waitForTarget.mockImplementation(() => new Promise(() => {}));+ mocks.isUsable.mockReturnValue(true);+ mocks.inViewport.mockReturnValue(true);+ mocks.nextFrame.mockResolvedValue(undefined);+ mocks.side.mockImplementation((target: { name: string }) =>+ target.name === "dm-composer" ? "top" : target.name === "add-server" ? "right" : "bottom");+ mocks.shouldRoute.mockImplementation(+ (route: string | undefined, pathname: string, routeKey: string, routedKey: string | null) =>+ Boolean(route && pathname !== route && routedKey !== routeKey),+ );+ mocks.dismiss.mockImplementation((target: { name: string }) => target.name !== "dm-composer");+ instance.getActiveElement.mockReturnValue(candidate);+ mocks.driverFactory.mockImplementation((options: Record<string, unknown>) => {+ driverOptions = options;+ return instance;+ });+ driverOptions = undefined;+ rafCallback = undefined;+ vi.stubGlobal("document", {+ body: {+ appendChild,+ classList: { add: bodyAdd, remove: bodyRemove },+ },+ createElement: () => avatar,+ });+ vi.stubGlobal("window", {+ matchMedia: () => ({ matches: false }),+ requestAnimationFrame,+ cancelAnimationFrame,+ addEventListener: windowAdd,+ removeEventListener: windowRemove,+ visualViewport: {+ addEventListener: viewportAdd,+ removeEventListener: viewportRemove,+ },+ });+ vi.stubGlobal("ResizeObserver", undefined);+ });++ afterEach(() => {+ for (const renderer of renderers.splice(0)) {+ act(() => renderer.unmount());+ }+ vi.unstubAllGlobals();+ });++ const render = () => {+ let renderer!: TestRenderer.ReactTestRenderer;+ act(() => { renderer = TestRenderer.create(React.createElement(Probe)); });+ renderers.push(renderer);+ return renderer;+ };++ it("keeps the complete global hook order, phases, dependencies, and helper boundary", () => {+ render();+ expect(mocks.hookOrder.slice(0, 5)).toEqual([+ "router",+ "pathname",+ "machines",+ "bots",+ "onboarding",+ ]);+ const source = readWebSource(+ "src/components/community/onboarding/community-onboarding-guide-controller.ts",+ );+ const owners = [+ "const router = useRouter();",+ "const pathname = usePathname();",+ "const machinesQuery = useMachines();",+ "const botsQuery = useBots();",+ "const state = useCommunityOnboarding();",+ "const [popoverContainer",+ "const [targetAvatarContainer",+ "const driverRef = useRef",+ "const targetAvatarRef = useRef",+ "const routedGuideRef = useRef",+ "const copy = useMemo",+ "const destroyGuide = useCallback",+ ];+ const ownerPositions = owners.map((needle) => source.indexOf(needle));+ expect(ownerPositions.every((position) => position >= 0)).toBe(true);+ expect(ownerPositions).toEqual([...ownerPositions].sort((a, b) => a - b));+ const effectKinds = [...source.matchAll(/\n (useEffect|useLayoutEffect)\(\(\) =>/g)]+ .map((match) => match[1]);+ expect(effectKinds).toEqual(["useEffect", "useEffect", "useLayoutEffect", "useEffect"]);+ expect(source).toContain("}, [state, machinesQuery.isSuccess, machinesQuery.machines]);");+ expect(source).toContain("}, [copy, state]);");+ expect(source).toContain("}, [popoverContainer, copy]);");+ expect(source).toContain("}, [copy, destroyGuide, pathname, router, state]);");+ expect(source).toContain(+ "[state, machinesQuery.isSuccess, machinesQuery.machines, botsQuery.isSuccess, botsQuery.bots]",+ );+ expect(source).toMatch(/const destroyGuide = useCallback\(\(\) => \{[\s\S]*?\n \}, \[\]\);/);+ expect(source).toContain("if (!popoverContainer) return;");+ expect(source).toContain("if (!instance) return;");+ expect(source).toContain("if (!copy) return;");+ expect(source).toContain("if (targetAvatarRef.current && activeTarget) {");+ for (const path of [+ "src/components/community/onboarding/community-onboarding-guide-copy.ts",+ "src/components/community/onboarding/community-onboarding-guide-target.ts",+ ]) {+ expect(readWebSource(path)).not.toMatch(/\buse[A-Z]\w*\(/);+ }+ const view = readWebSource(+ "src/components/community/onboarding/community-onboarding-guide-view.tsx",+ );+ expect(view.match(/useEffect\(/g)).toHaveLength(1);+ expect(view.indexOf("function GuideCard")).toBeLessThan(view.indexOf("useEffect("));+ expect(view.indexOf("export function renderCommunityOnboardingGuide"))+ .toBeGreaterThan(view.indexOf("useEffect("));+ });++ it("gates copy readiness and preserves every advance/recovery conjunction", () => {+ mocks.state = { status: "active", stage: "machine" };+ mocks.machines = [{ id: "machine-1", status: "online" }];+ const renderer = render();+ expect(latest.copy).toBeNull();+ expect(mocks.advance).not.toHaveBeenCalled();++ mocks.machinesSuccess = true;+ act(() => renderer.update(React.createElement(Probe)));+ expect(latest.copy).toBeNull();+ expect(mocks.advance).toHaveBeenCalledOnce();+ expect(mocks.advance).toHaveBeenCalledWith("machine", "bot");++ mocks.advance.mockClear();+ mocks.machines = [{ id: "machine-1", status: "offline" }];+ act(() => renderer.update(React.createElement(Probe)));+ expect(mocks.advance).not.toHaveBeenCalled();++ mocks.machines = [{ id: "machine-1", status: "online" }];+ mocks.machinesSuccess = false;+ act(() => renderer.update(React.createElement(Probe)));+ expect(mocks.advance).not.toHaveBeenCalled();++ mocks.machinesSuccess = true;+ mocks.state = { status: "active", stage: "bot" };+ mocks.machines = [];+ act(() => renderer.update(React.createElement(Probe)));+ expect(mocks.advance).not.toHaveBeenCalled();+ expect(latest.copy?.target).toEqual({ name: "connect-machine" });+ expect(mocks.recover).toHaveBeenCalledOnce();++ mocks.recover.mockClear();+ mocks.machines = [{ id: "offline", status: "offline" }];+ act(() => renderer.update(React.createElement(Probe)));+ expect(latest.copy?.target).toEqual({ name: "reconnect-machine", resourceId: "offline" });+ expect(mocks.recover).toHaveBeenCalledOnce();++ mocks.recover.mockClear();+ mocks.state = { status: "active", stage: "bot", machineRecovery: true };+ act(() => renderer.update(React.createElement(Probe)));+ expect(mocks.recover).not.toHaveBeenCalled();++ mocks.state = { status: "active", stage: "machine" };+ act(() => renderer.update(React.createElement(Probe)));+ expect(latest.copy?.target.name).toBe("reconnect-machine");+ expect(mocks.recover).not.toHaveBeenCalled();++ mocks.state = { status: "active", stage: "bot" };+ mocks.machines = [{ id: "online", status: "online" }];+ act(() => renderer.update(React.createElement(Probe)));+ expect(latest.copy?.target.name).toBe("create-bot");+ expect(mocks.recover).not.toHaveBeenCalled();++ mocks.state = { status: "active", stage: "bot", botId: "bot-1" };+ mocks.botsSuccess = false;+ act(() => renderer.update(React.createElement(Probe)));+ expect(latest.copy).toBeNull();+ expect(mocks.recover).not.toHaveBeenCalled();++ mocks.state = null;+ act(() => renderer.update(React.createElement(Probe)));+ expect(mocks.advance).not.toHaveBeenCalled();+ expect(mocks.recover).not.toHaveBeenCalled();+ });++ it("routes each key once without clearing the routed ref when copy loses its route", () => {+ mocks.state = { status: "active", stage: "bot" };+ mocks.machines = [{ id: "machine-1", status: "online" }];+ mocks.machinesSuccess = true;+ mocks.pathname = "/c/me";+ const renderer = render();+ expect(mocks.router.replace).toHaveBeenCalledWith("/c/me/bots");++ mocks.pathname = "/c/elsewhere";+ act(() => renderer.update(React.createElement(Probe)));+ expect(mocks.router.replace).toHaveBeenCalledTimes(1);++ mocks.state = { status: "active", stage: "server" };+ act(() => renderer.update(React.createElement(Probe)));+ expect(mocks.router.replace).toHaveBeenCalledTimes(1);++ mocks.state = { status: "active", stage: "bot" };+ act(() => renderer.update(React.createElement(Probe)));+ expect(mocks.router.replace).toHaveBeenCalledTimes(1);++ mocks.state = { status: "active", stage: "dm", dmId: "dm-7" };+ act(() => renderer.update(React.createElement(Probe)));+ expect(mocks.router.replace).toHaveBeenLastCalledWith("/c/me/dm-7");+ expect(mocks.router.replace).toHaveBeenCalledTimes(2);+ expect(mocks.router.push).not.toHaveBeenCalled();+ expect(mocks.shouldRoute).toHaveBeenCalledWith(+ "/c/me/dm-7",+ "/c/elsewhere",+ "active:dm:/c/me/dm-7",+ "active:bot:/c/me/bots",+ );+ });++ it("marks a current route key and early-returns on a later wrong path for that key", () => {+ mocks.state = { status: "active", stage: "bot" };+ mocks.machines = [{ id: "machine-1", status: "online" }];+ mocks.machinesSuccess = true;+ mocks.pathname = "/c/me/bots";+ const renderer = render();+ expect(mocks.shouldRoute).toHaveBeenLastCalledWith(+ "/c/me/bots",+ "/c/me/bots",+ "active:bot:/c/me/bots",+ "active:bot:/c/me/bots",+ );+ expect(mocks.router.replace).not.toHaveBeenCalled();+ expect(mocks.waitForTarget).toHaveBeenCalledOnce();++ mocks.waitForTarget.mockClear();+ mocks.driverFactory.mockClear();+ mocks.pathname = "/c/elsewhere";+ act(() => renderer.update(React.createElement(Probe)));+ expect(mocks.shouldRoute).toHaveBeenLastCalledWith(+ "/c/me/bots",+ "/c/elsewhere",+ "active:bot:/c/me/bots",+ "active:bot:/c/me/bots",+ );+ expect(mocks.router.replace).not.toHaveBeenCalled();+ expect(mocks.router.push).not.toHaveBeenCalled();+ expect(mocks.waitForTarget).not.toHaveBeenCalled();+ expect(mocks.driverFactory).not.toHaveBeenCalled();+ });++ it("retries target waits, then preserves two-frame Driver and DOM/ref ordering", async () => {+ mocks.state = { status: "active", stage: "server" };+ mocks.waitForTarget.mockResolvedValueOnce(null).mockResolvedValueOnce(candidate);+ let renderer!: TestRenderer.ReactTestRenderer;+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(Probe));+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ });+ renderers.push(renderer);+ expect(mocks.waitForTarget).toHaveBeenCalledTimes(2);+ expect(mocks.waitForTarget.mock.calls[0]![1]).toBe(2000);+ expect(candidate.scrollIntoView).toHaveBeenCalledWith({+ behavior: "auto",+ block: "nearest",+ inline: "nearest",+ });+ expect(mocks.nextFrame).toHaveBeenCalledTimes(2);+ expect(candidate.scrollIntoView.mock.invocationCallOrder[0])+ .toBeLessThan(mocks.nextFrame.mock.invocationCallOrder[0]!);+ expect(mocks.nextFrame.mock.invocationCallOrder[1])+ .toBeLessThan(mocks.driverFactory.mock.invocationCallOrder[0]!);+ expect(mocks.isUsable).toHaveBeenCalledWith(candidate);+ expect(mocks.inViewport).toHaveBeenCalledWith(candidate);+ expect(driverOptions).toMatchObject({+ animate: true,+ allowClose: false,+ overlayColor: "var(--community-onboarding-overlay)",+ overlayOpacity: 0.46,+ stagePadding: 8,+ stageRadius: 12,+ disableActiveInteraction: false,+ showButtons: [],+ popoverClass: "community-onboarding-popover community-onboarding-popover-right",+ });+ expect((driverOptions!.overlayClickBehavior as () => unknown)()).toBeUndefined();+ expect(instance.highlight).toHaveBeenCalledWith({+ element: candidate,+ popover: { description: "Loading", side: "right", align: "center" },+ });+ expect(appendChild).toHaveBeenCalledWith(avatar);+ expect(avatar.className).toBe("community-onboarding-focus-avatar");+ expect(mocks.position).toHaveBeenCalledWith(avatar, candidate, "right");+ expect(bodyAdd).toHaveBeenCalledWith("community-onboarding-active");+ expect(candidate.addEventListener).toHaveBeenCalledWith(+ "click",+ expect.any(Function),+ { once: true },+ );+ expect(instance.highlight.mock.invocationCallOrder[0])+ .toBeLessThan(appendChild.mock.invocationCallOrder[0]!);+ expect(appendChild.mock.invocationCallOrder[0])+ .toBeLessThan(mocks.position.mock.invocationCallOrder[0]!);+ expect(mocks.position.mock.invocationCallOrder[0])+ .toBeLessThan(bodyAdd.mock.invocationCallOrder[0]!);+ expect(bodyAdd.mock.invocationCallOrder[0])+ .toBeLessThan(candidate.addEventListener.mock.invocationCallOrder[0]!);++ const description = {+ replaceChildren: vi.fn(() => {+ expect(latest.popoverContainer).toBeNull();+ }),+ parentElement: null,+ } as unknown as HTMLElement;+ act(() => {+ (driverOptions!.onPopoverRender as (popover: { description: HTMLElement }) => void)({+ description,+ });+ });+ expect(description.replaceChildren).toHaveBeenCalledOnce();+ expect(instance.refresh).toHaveBeenCalledOnce();+ expect(rafCallback).toEqual(expect.any(Function));+ act(() => rafCallback?.(41));+ expect(mocks.pin).toHaveBeenCalledWith(description, instance, "right");+ expect(mocks.position).toHaveBeenLastCalledWith(avatar, candidate, "right");+ expect(latest.popoverContainer).toBe(description);+ expect(latest.targetAvatarContainer).toBe(avatar);++ act(() => renderer.update(React.createElement(Probe)));+ expect(latest.popoverContainer).toBe(description);+ expect(latest.targetAvatarContainer).toBe(avatar);+ expect(instance.destroy).not.toHaveBeenCalled();++ const source = readWebSource(+ "src/components/community/onboarding/community-onboarding-guide-controller.ts",+ );+ const lifecycleOrder = [+ "instance = driver({",+ "driverRef.current = instance;",+ "instance.highlight({",+ 'avatarContainer = document.createElement("div");',+ 'avatarContainer.className = "community-onboarding-focus-avatar";',+ "document.body.appendChild(avatarContainer);",+ "targetAvatarRef.current = avatarContainer;",+ "positionFocusAvatar(avatarContainer, target, popoverSide);",+ "setTargetAvatarContainer(avatarContainer);",+ 'document.body.classList.add("community-onboarding-active");',+ "if (dismissGuideOnTargetClick(copy.target)) {",+ 'target.addEventListener("click", handleTargetClick, { once: true });',+ ].map((needle) => source.indexOf(needle));+ expect(lifecycleOrder.every((position) => position >= 0)).toBe(true);+ expect(lifecycleOrder).toEqual([...lifecycleOrder].sort((a, b) => a - b));+ expect(source.indexOf("popover.description.replaceChildren();"))+ .toBeLessThan(source.indexOf("setPopoverContainer(popover.description);"));+ });++ it("uses reduced-motion Driver configuration without changing startup", async () => {+ mocks.state = { status: "active", stage: "server" };+ mocks.waitForTarget.mockResolvedValue(candidate);+ window.matchMedia = vi.fn(() => ({ matches: true })) as never;+ let renderer!: TestRenderer.ReactTestRenderer;+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(Probe));+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ });+ renderers.push(renderer);+ expect(driverOptions).toMatchObject({+ animate: false,+ allowClose: false,+ disableActiveInteraction: false,+ });+ expect(instance.highlight).toHaveBeenCalledOnce();+ });++ it("aborts a pending wait and ignores its stale completion after unmount", async () => {+ const wait = deferred<HTMLElement | null>();+ let signal!: AbortSignal;+ mocks.state = { status: "active", stage: "server" };+ mocks.waitForTarget.mockImplementation(+ (_target, timeout: number, nextSignal: AbortSignal) => {+ expect(timeout).toBe(2000);+ signal = nextSignal;+ return wait.promise;+ },+ );+ let renderer!: TestRenderer.ReactTestRenderer;+ act(() => {+ renderer = TestRenderer.create(React.createElement(Probe));+ });+ expect(signal.aborted).toBe(false);+ act(() => renderer.unmount());+ expect(signal.aborted).toBe(true);++ await act(async () => {+ wait.resolve(candidate);+ await wait.promise;+ await Promise.resolve();+ });+ expect(candidate.scrollIntoView).not.toHaveBeenCalled();+ expect(mocks.nextFrame).not.toHaveBeenCalled();+ expect(mocks.driverFactory).not.toHaveBeenCalled();+ expect(appendChild).not.toHaveBeenCalled();+ expect(bodyAdd).not.toHaveBeenCalled();+ });++ it("finishes both sequential frames but rejects stale post-abort Driver work", async () => {+ const firstFrame = deferred<void>();+ const secondFrame = deferred<void>();+ mocks.state = { status: "active", stage: "server" };+ mocks.waitForTarget.mockResolvedValue(candidate);+ mocks.nextFrame+ .mockReturnValueOnce(firstFrame.promise)+ .mockReturnValueOnce(secondFrame.promise);+ let renderer!: TestRenderer.ReactTestRenderer;+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(Probe));+ await Promise.resolve();+ await Promise.resolve();+ });+ expect(candidate.scrollIntoView).toHaveBeenCalledOnce();+ expect(mocks.nextFrame).toHaveBeenCalledOnce();+ act(() => renderer.unmount());++ await act(async () => {+ firstFrame.resolve();+ await firstFrame.promise;+ await Promise.resolve();+ });+ expect(mocks.nextFrame).toHaveBeenCalledTimes(2);+ await act(async () => {+ secondFrame.resolve();+ await secondFrame.promise;+ await Promise.resolve();+ });+ expect(mocks.isUsable).toHaveBeenCalledWith(candidate);+ expect(mocks.inViewport).toHaveBeenCalledWith(candidate);+ expect(mocks.driverFactory).not.toHaveBeenCalled();+ expect(appendChild).not.toHaveBeenCalled();+ expect(bodyAdd).not.toHaveBeenCalled();+ });++ it("cleans an active run once across replacement and unmount, then leading-destroys popover", async () => {+ mocks.state = { status: "active", stage: "server" };+ mocks.waitForTarget.mockResolvedValueOnce(candidate)+ .mockImplementation(() => new Promise(() => {}));+ let renderer!: TestRenderer.ReactTestRenderer;+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(Probe));+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ });+ const description = {+ replaceChildren: vi.fn(),+ parentElement: null,+ } as unknown as HTMLElement;+ act(() => {+ (driverOptions!.onPopoverRender as (popover: { description: HTMLElement }) => void)({+ description,+ });+ });+ expect(latest.popoverContainer).toBe(description);+ const clickHandler = candidate.addEventListener.mock.calls[0]![1];++ mocks.state = { status: "active", stage: "server", serverId: "server-1" };+ act(() => renderer.update(React.createElement(Probe)));+ expect(candidate.removeEventListener).toHaveBeenCalledWith("click", clickHandler);+ expect(instance.destroy).toHaveBeenCalledOnce();+ expect(avatarRemove).toHaveBeenCalledOnce();+ expect(bodyRemove).toHaveBeenCalledWith("community-onboarding-active");+ expect(latest.popoverContainer).toBeNull();+ expect(latest.targetAvatarContainer).toBeNull();++ act(() => renderer.unmount());+ expect(instance.destroy).toHaveBeenCalledOnce();+ expect(avatarRemove).toHaveBeenCalledOnce();+ expect(candidate.removeEventListener).toHaveBeenCalledOnce();+ });++ it("keeps DM click persistence, narrow cleanup, leading destroy, and destroy-before-skip", async () => {+ mocks.state = { status: "active", stage: "dm" };+ mocks.waitForTarget.mockResolvedValue(candidate);+ let renderer!: TestRenderer.ReactTestRenderer;+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(Probe));+ await Promise.resolve();+ await Promise.resolve();+ });+ renderers.push(renderer);+ expect(candidate.addEventListener).not.toHaveBeenCalled();++ const description = {+ replaceChildren: vi.fn(),+ parentElement: null,+ } as unknown as HTMLElement;+ act(() => {+ (driverOptions!.onPopoverRender as (popover: { description: HTMLElement }) => void)({+ description,+ });+ });+ expect(latest.popoverContainer).toBe(description);+ act(() => latest.onSkip());+ expect(instance.destroy.mock.invocationCallOrder.at(-1))+ .toBeLessThan(mocks.skip.mock.invocationCallOrder[0]!);+ expect(avatarRemove).toHaveBeenCalled();+ expect(bodyRemove).toHaveBeenCalledWith("community-onboarding-active");+ expect(latest.popoverContainer).toBeNull();++ const source = readWebSource(+ "src/components/community/onboarding/community-onboarding-guide-controller.ts",+ );+ const destroyBlock = source.slice(+ source.indexOf("const destroyGuide = useCallback"),+ source.indexOf(" useEffect(() => {"),+ );+ const destroyOrder = [+ "const instance = driverRef.current;",+ "driverRef.current = null;",+ "instance?.destroy();",+ "targetAvatarRef.current?.remove();",+ "targetAvatarRef.current = null;",+ 'document.body.classList.remove("community-onboarding-active");',+ "setPopoverContainer(null);",+ "setTargetAvatarContainer(null);",+ ].map((needle) => destroyBlock.indexOf(needle));+ expect(destroyOrder.every((position) => position >= 0)).toBe(true);+ expect(destroyOrder).toEqual([...destroyOrder].sort((a, b) => a - b));+ const lifecycle = source.slice(source.lastIndexOf("useEffect(() => {"));+ const cleanup = lifecycle.slice(lifecycle.indexOf("return () => {"));+ expect(lifecycle.indexOf("destroyGuide();")).toBeLessThan(lifecycle.indexOf("if (!copy"));+ const cleanupOrder = [+ "abortController.abort();",+ 'target?.removeEventListener("click", handleTargetClick)',+ "if (driverRef.current === instance) driverRef.current = null;",+ "if (targetAvatarRef.current === avatarContainer) targetAvatarRef.current = null;",+ "avatarContainer?.remove();",+ "instance?.destroy();",+ 'document.body.classList.remove("community-onboarding-active");',+ "setTargetAvatarContainer(null);",+ "instance = null;",+ ].map((needle) => cleanup.indexOf(needle));+ expect(cleanupOrder.every((position) => position >= 0)).toBe(true);+ expect(cleanupOrder).toEqual([...cleanupOrder].sort((a, b) => a - b));+ expect(cleanup).toContain("setTargetAvatarContainer(null);");+ expect(cleanup).not.toContain("setPopoverContainer(null);");+ });++ it("uses the ResizeObserver-absent cleanup branch without registering listeners", async () => {+ mocks.state = { status: "active", stage: "server" };+ mocks.waitForTarget.mockResolvedValue(candidate);+ let renderer!: TestRenderer.ReactTestRenderer;+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(Probe));+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ });+ const description = {+ replaceChildren: vi.fn(),+ parentElement: null,+ } as unknown as HTMLElement;+ act(() => {+ (driverOptions!.onPopoverRender as (popover: { description: HTMLElement }) => void)({+ description,+ });+ });+ expect(instance.refresh).toHaveBeenCalledOnce();+ expect(requestAnimationFrame).toHaveBeenCalledOnce();+ expect(windowAdd).not.toHaveBeenCalled();+ expect(viewportAdd).not.toHaveBeenCalled();++ act(() => renderer.unmount());+ expect(cancelAnimationFrame).toHaveBeenCalledWith(41);+ expect(windowRemove).not.toHaveBeenCalled();+ expect(viewportRemove).not.toHaveBeenCalled();+ });++ it("keeps a null popover container as a complete positioning no-op", () => {+ mocks.state = null;+ render();+ expect(instance.refresh).not.toHaveBeenCalled();+ expect(requestAnimationFrame).not.toHaveBeenCalled();+ expect(windowAdd).not.toHaveBeenCalled();+ expect(viewportAdd).not.toHaveBeenCalled();+ });++ it("keeps a stale popover callback harmless after the Driver ref is cleared", async () => {+ mocks.state = { status: "active", stage: "server" };+ mocks.waitForTarget.mockResolvedValue(candidate);+ let renderer!: TestRenderer.ReactTestRenderer;+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(Probe));+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ });+ renderers.push(renderer);+ const onPopoverRender = driverOptions!.onPopoverRender as (+ popover: { description: HTMLElement }+ ) => void;+ act(() => latest.onSkip());+ instance.refresh.mockClear();+ requestAnimationFrame.mockClear();+ const staleDescription = {+ replaceChildren: vi.fn(),+ parentElement: null,+ } as unknown as HTMLElement;+ act(() => onPopoverRender({ description: staleDescription }));+ expect(latest.popoverContainer).toBe(staleDescription);+ expect(instance.refresh).not.toHaveBeenCalled();+ expect(requestAnimationFrame).not.toHaveBeenCalled();+ });++ it("observes only the popover when its optional parent is absent", async () => {+ const observe = vi.fn();+ const disconnect = vi.fn();+ vi.stubGlobal("ResizeObserver", class {+ observe = observe;+ disconnect = disconnect;+ });+ mocks.state = { status: "active", stage: "server" };+ mocks.waitForTarget.mockResolvedValue(candidate);+ let renderer!: TestRenderer.ReactTestRenderer;+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(Probe));+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ });+ const description = {+ replaceChildren: vi.fn(),+ parentElement: null,+ } as unknown as HTMLElement;+ act(() => {+ (driverOptions!.onPopoverRender as (popover: { description: HTMLElement }) => void)({+ description,+ });+ });+ expect(observe).toHaveBeenCalledOnce();+ expect(observe).toHaveBeenCalledWith(description);+ act(() => renderer.unmount());+ expect(disconnect).toHaveBeenCalledOnce();+ });++ it("keeps the observer-present positioning listener and cleanup matrix", async () => {+ const observe = vi.fn();+ const disconnect = vi.fn();+ vi.stubGlobal("ResizeObserver", class {+ observe = observe;+ disconnect = disconnect;+ });+ mocks.state = { status: "active", stage: "server" };+ mocks.waitForTarget.mockResolvedValue(candidate);+ let renderer!: TestRenderer.ReactTestRenderer;+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(Probe));+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ });+ renderers.push(renderer);+ const description = {+ replaceChildren: vi.fn(),+ parentElement: { id: "parent" },+ } as unknown as HTMLElement;+ act(() => {+ (driverOptions!.onPopoverRender as (popover: { description: HTMLElement }) => void)({+ description,+ });+ });+ expect(observe).toHaveBeenNthCalledWith(1, description);+ expect(observe).toHaveBeenNthCalledWith(2, description.parentElement);+ expect(windowAdd).toHaveBeenCalledWith("resize", expect.any(Function));+ expect(windowAdd).toHaveBeenCalledWith("scroll", expect.any(Function), true);+ expect(viewportAdd).toHaveBeenCalledWith("resize", expect.any(Function));+ expect(viewportAdd).toHaveBeenCalledWith("scroll", expect.any(Function));++ const refresh = windowAdd.mock.calls.find(([name]) => name === "resize")![1] as () => void;+ instance.refresh.mockClear();+ cancelAnimationFrame.mockClear();+ requestAnimationFrame.mockClear();+ act(() => refresh());+ expect(instance.refresh).toHaveBeenCalledOnce();+ expect(cancelAnimationFrame).toHaveBeenCalledOnce();+ expect(cancelAnimationFrame).toHaveBeenCalledWith(41);+ expect(requestAnimationFrame).toHaveBeenCalledOnce();+ expect(instance.refresh.mock.invocationCallOrder[0])+ .toBeLessThan(cancelAnimationFrame.mock.invocationCallOrder[0]!);+ expect(cancelAnimationFrame.mock.invocationCallOrder[0])+ .toBeLessThan(requestAnimationFrame.mock.invocationCallOrder[0]!);++ mocks.pin.mockClear();+ mocks.position.mockClear();+ instance.getActiveElement.mockReturnValue(null);+ act(() => rafCallback?.(41));+ expect(mocks.pin).toHaveBeenCalledWith(description, instance, "right");+ expect(mocks.position).not.toHaveBeenCalled();++ act(() => renderer.unmount());+ expect(disconnect).toHaveBeenCalledOnce();+ expect(windowRemove).toHaveBeenCalledWith("resize", expect.any(Function));+ expect(windowRemove).toHaveBeenCalledWith("scroll", expect.any(Function), true);+ expect(viewportRemove).toHaveBeenCalledWith("resize", expect.any(Function));+ expect(viewportRemove).toHaveBeenCalledWith("scroll", expect.any(Function));+ expect(cancelAnimationFrame).toHaveBeenCalledWith(41);+ });+});diff --git a/src/web/src/components/community/onboarding/community-onboarding-guide-controller.ts b/src/web/src/components/community/onboarding/community-onboarding-guide-controller.tsnew file mode 100644index 000000000..dc30fcb29--- /dev/null+++ b/src/web/src/components/community/onboarding/community-onboarding-guide-controller.ts@@ -0,0 +1,230 @@+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";+import { usePathname, useRouter } from "next/navigation";+import { driver, type Driver } from "driver.js";+import { isPresenceOnline } from "@alook/shared";+import { useMachines } from "@/hooks/community/use-machines";+import { useBots } from "@/hooks/community/use-bots";+import {+ advanceCommunityOnboarding,+ recoverCommunityOnboardingMachine,+ skipCommunityOnboarding,+ useCommunityOnboarding,+} from "@/lib/community-onboarding";+import { guideCopy } from "./community-onboarding-guide-copy";+import {+ dismissGuideOnTargetClick,+ guidePopoverSide,+ isGuideTargetUsable,+ nextFrame,+ pinPopoverAwayFromTarget,+ positionFocusAvatar,+ shouldAutoRouteGuide,+ targetIsInViewport,+ waitForTarget,+} from "./community-onboarding-guide-target";+import type { CommunityOnboardingGuideController } from "./community-onboarding-guide-types";++export function useCommunityOnboardingGuideController(): CommunityOnboardingGuideController {+ const router = useRouter();+ const pathname = usePathname();+ const machinesQuery = useMachines();+ const botsQuery = useBots();+ const state = useCommunityOnboarding();+ const [popoverContainer, setPopoverContainer] = useState<HTMLElement | null>(null);+ const [targetAvatarContainer, setTargetAvatarContainer] = useState<HTMLElement | null>(null);+ const driverRef = useRef<Driver | null>(null);+ const targetAvatarRef = useRef<HTMLElement | null>(null);+ const routedGuideRef = useRef<string | null>(null);++ const copy = useMemo(+ () => {+ if (!state) return null;+ if ((state.stage === "machine" || state.stage === "bot") && !machinesQuery.isSuccess) {+ return null;+ }+ if (+ state.stage === "bot" &&+ state.botId &&+ !botsQuery.isSuccess+ ) {+ return null;+ }+ return guideCopy(state, {+ machines: machinesQuery.machines,+ bots: botsQuery.bots,+ });+ },+ [state, machinesQuery.isSuccess, machinesQuery.machines, botsQuery.isSuccess, botsQuery.bots],+ );++ const destroyGuide = useCallback(() => {+ const instance = driverRef.current;+ driverRef.current = null;+ instance?.destroy();+ targetAvatarRef.current?.remove();+ targetAvatarRef.current = null;+ document.body.classList.remove("community-onboarding-active");+ setPopoverContainer(null);+ setTargetAvatarContainer(null);+ }, []);++ useEffect(() => {+ if (+ state?.status !== "active" ||+ state.stage !== "machine" ||+ !machinesQuery.isSuccess ||+ !machinesQuery.machines.some((machine) => isPresenceOnline(machine.status))+ ) {+ return;+ }+ advanceCommunityOnboarding("machine", "bot");+ }, [state, machinesQuery.isSuccess, machinesQuery.machines]);++ useEffect(() => {+ const recoveryTarget =+ copy?.target.name === "connect-machine" || copy?.target.name === "reconnect-machine";+ if (!recoveryTarget || state?.status !== "active" || state.stage !== "bot" || state.machineRecovery) return;+ recoverCommunityOnboardingMachine();+ }, [copy, state]);++ useLayoutEffect(() => {+ if (!popoverContainer) return;+ let positionFrame: number | null = null;+ const refresh = () => {+ const instance = driverRef.current;+ if (!instance) return;+ instance.refresh();+ if (positionFrame !== null) window.cancelAnimationFrame(positionFrame);+ positionFrame = window.requestAnimationFrame(() => {+ positionFrame = null;+ if (!copy) return;+ const popoverSide = guidePopoverSide(copy.target);+ pinPopoverAwayFromTarget(popoverContainer, instance, popoverSide);+ const activeTarget = instance.getActiveElement();+ if (targetAvatarRef.current && activeTarget) {+ positionFocusAvatar(targetAvatarRef.current, activeTarget, popoverSide);+ }+ });+ };+ refresh();+ if (typeof ResizeObserver === "undefined") {+ return () => {+ if (positionFrame !== null) window.cancelAnimationFrame(positionFrame);+ };+ }+ const observer = new ResizeObserver(refresh);+ observer.observe(popoverContainer);+ if (popoverContainer.parentElement) observer.observe(popoverContainer.parentElement);+ window.addEventListener("resize", refresh);+ window.addEventListener("scroll", refresh, true);+ window.visualViewport?.addEventListener("resize", refresh);+ window.visualViewport?.addEventListener("scroll", refresh);+ return () => {+ if (positionFrame !== null) window.cancelAnimationFrame(positionFrame);+ observer.disconnect();+ window.removeEventListener("resize", refresh);+ window.removeEventListener("scroll", refresh, true);+ window.visualViewport?.removeEventListener("resize", refresh);+ window.visualViewport?.removeEventListener("scroll", refresh);+ };+ }, [popoverContainer, copy]);++ useEffect(() => {+ destroyGuide();+ if (!copy || !state) return;+ const stageKey = state.stage;+ const routeKey = `${state.status}:${stageKey}:${copy.route ?? ""}`;+ if (copy.route && pathname === copy.route) routedGuideRef.current = routeKey;+ if (+ copy.route &&+ shouldAutoRouteGuide(copy.route, pathname, routeKey, routedGuideRef.current)+ ) {+ routedGuideRef.current = routeKey;+ router.replace(copy.route);+ return;+ }+ if (copy.route && pathname !== copy.route) {+ return;+ }++ const abortController = new AbortController();+ let target: HTMLElement | null = null;+ let instance: Driver | null = null;+ let avatarContainer: HTMLElement | null = null;+ let handleTargetClick: (() => void) | null = null;++ void (async () => {+ while (!abortController.signal.aborted && !target) {+ const candidate = await waitForTarget(copy.target, 2000, abortController.signal);+ if (!candidate || abortController.signal.aborted) continue;+ candidate.scrollIntoView({ behavior: "auto", block: "nearest", inline: "nearest" });+ await nextFrame();+ await nextFrame();+ if (isGuideTargetUsable(candidate) && targetIsInViewport(candidate)) target = candidate;+ }+ if (abortController.signal.aborted || !target) return;+ const popoverSide = guidePopoverSide(copy.target);+ instance = driver({+ animate: !window.matchMedia("(prefers-reduced-motion: reduce)").matches,+ allowClose: false,+ overlayClickBehavior: () => undefined,+ overlayColor: "var(--community-onboarding-overlay)",+ overlayOpacity: 0.46,+ stagePadding: 8,+ stageRadius: 12,+ disableActiveInteraction: false,+ showButtons: [],+ popoverClass: `community-onboarding-popover community-onboarding-popover-${popoverSide}`,+ onPopoverRender: (popover) => {+ popover.description.replaceChildren();+ setPopoverContainer(popover.description);+ },+ });+ driverRef.current = instance;+ instance.highlight({+ element: target,+ popover: {+ description: "Loading",+ side: popoverSide,+ align: "center",+ },+ });+ avatarContainer = document.createElement("div");+ avatarContainer.className = "community-onboarding-focus-avatar";+ document.body.appendChild(avatarContainer);+ targetAvatarRef.current = avatarContainer;+ positionFocusAvatar(avatarContainer, target, popoverSide);+ setTargetAvatarContainer(avatarContainer);+ document.body.classList.add("community-onboarding-active");+ if (dismissGuideOnTargetClick(copy.target)) {+ handleTargetClick = () => {+ destroyGuide();+ };+ target.addEventListener("click", handleTargetClick, { once: true });+ }+ })();++ return () => {+ abortController.abort();+ if (handleTargetClick) target?.removeEventListener("click", handleTargetClick);+ if (driverRef.current === instance) driverRef.current = null;+ if (targetAvatarRef.current === avatarContainer) targetAvatarRef.current = null;+ avatarContainer?.remove();+ instance?.destroy();+ document.body.classList.remove("community-onboarding-active");+ setTargetAvatarContainer(null);+ instance = null;+ };+ }, [copy, destroyGuide, pathname, router, state]);++ return {+ copy,+ state,+ popoverContainer,+ targetAvatarContainer,+ onSkip: () => {+ destroyGuide();+ skipCommunityOnboarding();+ },+ };+}diff --git a/src/web/src/components/community/onboarding/community-onboarding-guide-copy.test.ts b/src/web/src/components/community/onboarding/community-onboarding-guide-copy.test.tsnew file mode 100644index 000000000..56e4db2c5--- /dev/null+++ b/src/web/src/components/community/onboarding/community-onboarding-guide-copy.test.ts@@ -0,0 +1,114 @@+import { describe, expect, it } from "vitest";+import type { CommunityOnboardingState } from "@/lib/community-onboarding";+import { guideCopy } from "./community-onboarding-guide-copy";++const state = (stage: CommunityOnboardingState["stage"], extra = {}) => ({+ status: "active" as const,+ stage,+ ...extra,+});+const machine = (id: string, status: "online" | "offline") => ({ id, status });++describe("guideCopy", () => {+ it("keeps every machine-stage branch and stable offline selection", () => {+ expect(guideCopy(state("machine"), {+ machines: [machine("online", "online")],+ bots: [],+ })).toBeNull();+ expect(guideCopy(state("machine"), { machines: [], bots: [] })).toEqual({+ target: { name: "connect-machine" },+ eyebrow: "Step 1 of 4",+ title: "Give your bot a place to run",+ route: "/c/me/machines",+ });+ expect(guideCopy(state("machine"), {+ machines: [machine("z", "offline"), machine("a", "offline")],+ bots: [],+ })).toEqual({+ target: { name: "reconnect-machine", resourceId: "a" },+ eyebrow: "Step 1 of 4",+ title: "Bring your machine back online",+ route: "/c/me/machines",+ });+ });++ it("prioritizes a pending bot's bound offline machine", () => {+ expect(guideCopy(state("bot", { botId: "bot-1" }), {+ machines: [machine("online", "online"), machine("bound", "offline")],+ bots: [{ id: "bot-1", machineId: "bound" }],+ })).toEqual({+ target: { name: "reconnect-machine", resourceId: "bound" },+ eyebrow: "Step 2 of 4",+ title: "Bring your machine back online",+ route: "/c/me/machines",+ });+ });++ it("keeps bot recovery, creation, and pending-chat copy exact", () => {+ expect(guideCopy(state("bot"), {+ machines: [machine("z", "offline"), machine("a", "offline")],+ bots: [],+ })).toEqual({+ target: { name: "reconnect-machine", resourceId: "a" },+ eyebrow: "Step 2 of 4",+ title: "Bring your machine back online",+ route: "/c/me/machines",+ });+ expect(guideCopy(state("bot"), { machines: [], bots: [] })).toEqual({+ target: { name: "connect-machine" },+ eyebrow: "Step 2 of 4",+ title: "Give your bot a place to run",+ route: "/c/me/machines",+ });+ expect(guideCopy(state("bot"), {+ machines: [machine("online", "online")],+ bots: [],+ })).toEqual({+ target: { name: "create-bot" },+ eyebrow: "Step 2 of 4",+ title: "Create a bot with a voice of its own",+ route: "/c/me/bots",+ });+ expect(guideCopy(state("bot", { botId: "bot-1" }), {+ machines: [machine("online", "online")],+ bots: [{ id: "bot-1", machineId: "online" }],+ })).toEqual({+ target: { name: "create-bot" },+ eyebrow: "Step 2 of 4",+ title: "Meet your bot in chat",+ route: "/c/me/bots",+ });+ });++ it("keeps DM routing optional and exact", () => {+ expect(guideCopy(state("dm"), { machines: [], bots: [] })).toEqual({+ target: { name: "dm-composer" },+ eyebrow: "Step 3 of 4",+ title: "Start a conversation with your bot",+ route: undefined,+ });+ expect(guideCopy(state("dm", { dmId: "dm-7" }), { machines: [], bots: [] }))+ .toEqual({+ target: { name: "dm-composer" },+ eyebrow: "Step 3 of 4",+ title: "Start a conversation with your bot",+ route: "/c/me/dm-7",+ });+ });++ it("keeps both server-stage titles and no route", () => {+ expect(guideCopy(state("server"), { machines: [], bots: [] })).toEqual({+ target: { name: "add-server" },+ eyebrow: "Step 4 of 4",+ title: "Make a shared home for friends and family",+ });+ expect(guideCopy(state("server", { serverId: "server-1" }), {+ machines: [],+ bots: [],+ })).toEqual({+ target: { name: "add-server" },+ eyebrow: "Step 4 of 4",+ title: "Bring your bot into the server",+ });+ });+});diff --git a/src/web/src/components/community/onboarding/community-onboarding-guide-copy.ts b/src/web/src/components/community/onboarding/community-onboarding-guide-copy.tsnew file mode 100644index 000000000..c7b92227d--- /dev/null+++ b/src/web/src/components/community/onboarding/community-onboarding-guide-copy.ts@@ -0,0 +1,91 @@+import { isPresenceOnline } from "@alook/shared";+import type { CommunityOnboardingState } from "@/lib/community-onboarding";+import type { GuideContext, GuideCopy, GuideTarget } from "./community-onboarding-guide-types";++const target = (name: GuideTarget["name"], resourceId?: string): GuideTarget => ({+ name,+ ...(resourceId ? { resourceId } : {}),+});++function stableOfflineMachine(machines: GuideContext["machines"]) {+ return machines+ .filter((machine) => !isPresenceOnline(machine.status))+ .sort((a, b) => a.id.localeCompare(b.id))[0];+}++function recoveryCopy(machine: GuideContext["machines"][number], eyebrow: string): GuideCopy {+ return {+ target: target("reconnect-machine", machine.id),+ eyebrow,+ title: "Bring your machine back online",+ route: "/c/me/machines",+ };+}++export function guideCopy(+ state: CommunityOnboardingState,+ { machines, bots }: GuideContext,+): GuideCopy | null {+ if (state.stage === "machine") {+ if (machines.some((machine) => isPresenceOnline(machine.status))) return null;+ const offlineMachine = stableOfflineMachine(machines);+ if (offlineMachine) return recoveryCopy(offlineMachine, "Step 1 of 4");+ return {+ target: target("connect-machine"),+ eyebrow: "Step 1 of 4",+ title: "Give your bot a place to run",+ route: "/c/me/machines",+ };+ }+ if (state.stage === "bot") {+ const boundMachineId = state.botId+ ? bots.find((bot) => bot.id === state.botId)?.machineId+ : undefined;+ const boundMachine = boundMachineId+ ? machines.find((machine) => machine.id === boundMachineId)+ : undefined;+ if (boundMachine && !isPresenceOnline(boundMachine.status)) {+ return recoveryCopy(boundMachine, "Step 2 of 4");+ }+ if (!machines.some((machine) => isPresenceOnline(machine.status))) {+ const offlineMachine = stableOfflineMachine(machines);+ if (offlineMachine) return recoveryCopy(offlineMachine, "Step 2 of 4");+ return {+ target: target("connect-machine"),+ eyebrow: "Step 2 of 4",+ title: "Give your bot a place to run",+ route: "/c/me/machines",+ };+ }+ if (state.botId) {+ return {+ target: target("create-bot"),+ eyebrow: "Step 2 of 4",+ title: "Meet your bot in chat",+ route: "/c/me/bots",+ };+ }+ return {+ target: target("create-bot"),+ eyebrow: "Step 2 of 4",+ title: "Create a bot with a voice of its own",+ route: "/c/me/bots",+ };+ }+ if (state.stage === "dm") {+ return {+ target: target("dm-composer"),+ eyebrow: "Step 3 of 4",+ title: "Start a conversation with your bot",+ route: state.dmId ? `/c/me/${state.dmId}` : undefined,+ };+ }+ const recovering = Boolean(state.serverId);+ return {+ target: target("add-server"),+ eyebrow: "Step 4 of 4",+ title: recovering+ ? "Bring your bot into the server"+ : "Make a shared home for friends and family",+ };+}diff --git a/src/web/src/components/community/onboarding/community-onboarding-guide-facade.contract.test.ts b/src/web/src/components/community/onboarding/community-onboarding-guide-facade.contract.test.tsnew file mode 100644index 000000000..d3be046c3--- /dev/null+++ b/src/web/src/components/community/onboarding/community-onboarding-guide-facade.contract.test.ts@@ -0,0 +1,71 @@+import { readFileSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import React from "react";+import TestRenderer, { act } from "react-test-renderer";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ controller: vi.fn(() => ({ marker: "controller" })),+ view: vi.fn(),+}));++vi.mock("./community-onboarding-guide-controller", () => ({+ useCommunityOnboardingGuideController: mocks.controller,+}));+vi.mock("./community-onboarding-guide-view", () => ({+ renderCommunityOnboardingGuide: mocks.view,+}));++import * as facade from "./community-onboarding-guide";++const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..");+const readWebSource = (path: string) => readFileSync(resolve(webRoot, path), "utf8");++describe("CommunityOnboardingGuide facade", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.view.mockReturnValue(React.createElement("guide-view"));+ });++ it("retains exactly ten runtime exports", () => {+ expect(Object.keys(facade).sort()).toEqual([+ "CommunityOnboardingGuide",+ "adjacentAvatarLayout",+ "dismissGuideOnTargetClick",+ "findGuideTarget",+ "guideCopy",+ "guidePopoverSide",+ "nonOverlappingPopoverLayout",+ "rectFitsViewport",+ "shouldAutoRouteGuide",+ "waitForTarget",+ ]);+ });++ it("calls one controller and one ordinary view helper without adding a wrapper", () => {+ let renderer!: TestRenderer.ReactTestRenderer;+ act(() => {+ renderer = TestRenderer.create(React.createElement(facade.CommunityOnboardingGuide));+ });+ expect(mocks.controller).toHaveBeenCalledOnce();+ expect(mocks.view).toHaveBeenCalledOnce();+ expect(mocks.view).toHaveBeenCalledWith({ marker: "controller" });+ expect(renderer.root.findAllByType("guide-view")).toHaveLength(1);+ });++ it("keeps the sole production importer on the original path and the facade boundary plain", () => {+ const importer = readWebSource("src/app/c/community-shell.tsx");+ expect(importer).toContain(+ 'import { CommunityOnboardingGuide } from "@/components/community/onboarding/community-onboarding-guide"',+ );+ expect(importer.match(/<CommunityOnboardingGuide\s*\/>/g)).toHaveLength(1);++ const source = readWebSource(+ "src/components/community/onboarding/community-onboarding-guide.tsx",+ );+ expect(source).toContain("const controller = useCommunityOnboardingGuideController();");+ expect(source).toContain("return renderCommunityOnboardingGuide(controller);");+ expect(source).not.toMatch(/createElement|<CommunityOnboardingGuideView|<Provider|<Fragment/);+ });+});diff --git a/src/web/src/components/community/onboarding/community-onboarding-guide-target.test.ts b/src/web/src/components/community/onboarding/community-onboarding-guide-target.test.tsnew file mode 100644index 000000000..7247c8e46--- /dev/null+++ b/src/web/src/components/community/onboarding/community-onboarding-guide-target.test.ts@@ -0,0 +1,468 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ adjacentAvatarLayout,+ dismissGuideOnTargetClick,+ findGuideTarget,+ guidePopoverSide,+ guideTargetControl,+ isGuideTargetUsable,+ nextFrame,+ nonOverlappingPopoverLayout,+ pinPopoverAwayFromTarget,+ positionFocusAvatar,+ rectFitsViewport,+ targetIsInViewport,+ waitForTarget,+} from "./community-onboarding-guide-target";++type FakeElement = HTMLElement & {+ styleState?: Record<string, string>;+};++const controlSelector = "button:not([disabled]), [role=button], .ProseMirror";++function element({+ id,+ connected = true,+ direct = true,+ control,+ rect = { top: 10, right: 110, bottom: 50, left: 10, width: 100, height: 40 },+}: {+ id?: string;+ connected?: boolean;+ direct?: boolean;+ control?: HTMLElement | null;+ rect?: Record<string, number>;+} = {}) {+ const matches = vi.fn(() => direct);+ const querySelector = vi.fn(() => control ?? null);+ return {+ isConnected: connected,+ dataset: id ? { onboardingId: id } : {},+ matches,+ querySelector,+ getBoundingClientRect: () => rect,+ } as unknown as FakeElement;+}++describe("community onboarding target helpers", () => {+ afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ });++ it("uses the exact selector for direct button, role, ProseMirror, and nested controls", () => {+ for (const direct of [element(), element(), element()]) {+ expect(guideTargetControl(direct)).toBe(direct);+ expect(direct.matches).toHaveBeenCalledWith(controlSelector);+ expect(direct.querySelector).not.toHaveBeenCalled();+ }+ const control = element();+ const wrapper = element({ direct: false, control });+ expect(guideTargetControl(wrapper)).toBe(control);+ expect(wrapper.matches).toHaveBeenCalledWith(controlSelector);+ expect(wrapper.querySelector).toHaveBeenCalledWith(controlSelector);+ });++ it("selects the first usable exact resource and measures the inner control for viewport", () => {+ const hiddenControl = element();+ const hidden = element({ id: "machine-1", direct: false, control: hiddenControl });+ const wrong = element({ id: "machine-2" });+ const control = element({+ rect: { top: 5, right: 119, bottom: 79, left: 5, width: 114, height: 74 },+ });+ const matching = element({+ id: "machine-1",+ direct: false,+ control,+ rect: { top: 500, right: 600, bottom: 540, left: 500, width: 100, height: 40 },+ });+ const querySelectorAll = vi.fn(() => [hidden, wrong, matching]);+ vi.stubGlobal("document", { querySelectorAll });+ vi.stubGlobal("window", {+ getComputedStyle: (node: HTMLElement) => ({+ display: node === hiddenControl ? "none" : "block",+ visibility: "visible",+ pointerEvents: "auto",+ }),+ innerWidth: 120,+ innerHeight: 80,+ });++ expect(guideTargetControl(matching)).toBe(control);+ expect(isGuideTargetUsable(hidden)).toBe(false);+ expect(findGuideTarget({ name: "reconnect-machine", resourceId: "machine-1" }))+ .toBe(control);+ expect(querySelectorAll).toHaveBeenCalledWith(+ '[data-onboarding-target="reconnect-machine"]',+ );+ expect(targetIsInViewport(matching)).toBe(true);+ expect(rectFitsViewport({+ top: -1,+ left: -1,+ right: 121,+ bottom: 81,+ width: 122,+ height: 82,+ }, 120, 80)).toBe(true);+ expect(rectFitsViewport({+ top: -2,+ left: 0,+ right: 100,+ bottom: 40,+ width: 100,+ height: 40,+ }, 120, 80)).toBe(false);+ });++ it("rejects every wrapper/control usability gate independently", () => {+ const disconnected = element({ connected: false });+ const zero = element({ rect: { top: 0, right: 0, bottom: 0, left: 0, width: 0, height: 0 } });+ const wrapperDisplay = element();+ const wrapperVisibility = element();+ const controlDisplay = element();+ const displayWrapper = element({ direct: false, control: controlDisplay });+ const controlVisibility = element();+ const visibilityWrapper = element({ direct: false, control: controlVisibility });+ const controlPointer = element();+ const pointerWrapper = element({ direct: false, control: controlPointer });+ vi.stubGlobal("window", {+ getComputedStyle: (node: HTMLElement) => ({+ display:+ node === wrapperDisplay || node === controlDisplay ? "none" : "block",+ visibility:+ node === wrapperVisibility || node === controlVisibility ? "hidden" : "visible",+ pointerEvents: node === controlPointer ? "none" : "auto",+ }),+ });+ expect(isGuideTargetUsable(disconnected)).toBe(false);+ expect(isGuideTargetUsable(zero)).toBe(false);+ expect(isGuideTargetUsable(wrapperDisplay)).toBe(false);+ expect(isGuideTargetUsable(wrapperVisibility)).toBe(false);+ expect(isGuideTargetUsable(displayWrapper)).toBe(false);+ expect(isGuideTargetUsable(visibilityWrapper)).toBe(false);+ expect(isGuideTargetUsable(pointerWrapper)).toBe(false);+ });++ it("settles an initial candidate after 200ms without an observer notification", async () => {+ vi.useFakeTimers();+ const initial = element();+ const observe = vi.fn();+ const disconnect = vi.fn();+ vi.stubGlobal("document", { body: {}, querySelectorAll: () => [initial] });+ vi.stubGlobal("window", {+ getComputedStyle: () => ({ display: "block", visibility: "visible", pointerEvents: "auto" }),+ setTimeout,+ clearTimeout,+ });+ vi.stubGlobal("MutationObserver", class {+ observe = observe;+ disconnect = disconnect;+ });++ let result: HTMLElement | null | undefined;+ void waitForTarget({ name: "connect-machine" }).then((value) => { result = value; });+ await vi.advanceTimersByTimeAsync(199);+ expect(result).toBeUndefined();+ await vi.advanceTimersByTimeAsync(1);+ expect(result).toBe(initial);+ expect(observe).toHaveBeenCalledOnce();+ expect(disconnect).toHaveBeenCalledOnce();+ expect(vi.getTimerCount()).toBe(0);+ });++ it("restarts the full 200ms settle window on direct candidate identity replacement", async () => {+ vi.useFakeTimers();+ const first = element();+ const second = element();+ let current = first;+ let notify!: () => void;+ vi.stubGlobal("document", { body: {}, querySelectorAll: () => [current] });+ vi.stubGlobal("window", {+ getComputedStyle: () => ({ display: "block", visibility: "visible", pointerEvents: "auto" }),+ setTimeout,+ clearTimeout,+ });+ vi.stubGlobal("MutationObserver", class {+ constructor(callback: () => void) { notify = callback; }+ observe() {}+ disconnect() {}+ });++ let result: HTMLElement | null | undefined;+ void waitForTarget({ name: "connect-machine" }).then((value) => { result = value; });+ await vi.advanceTimersByTimeAsync(100);+ current = second;+ notify();+ await vi.advanceTimersByTimeAsync(199);+ expect(result).toBeUndefined();+ await vi.advanceTimersByTimeAsync(1);+ expect(result).toBe(second);+ expect(vi.getTimerCount()).toBe(0);+ });++ it("cancels settle on candidate loss, rearms identity changes, and finishes once", async () => {+ vi.useFakeTimers();+ const first = element();+ const second = element();+ let current: FakeElement | null = first;+ let notify!: () => void;+ const observe = vi.fn();+ const disconnect = vi.fn();+ const removeAbort = vi.fn();+ vi.stubGlobal("document", {+ body: {},+ querySelectorAll: () => current ? [current] : [],+ });+ vi.stubGlobal("window", {+ getComputedStyle: () => ({ display: "block", visibility: "visible", pointerEvents: "auto" }),+ setTimeout,+ clearTimeout,+ });+ vi.stubGlobal("MutationObserver", class {+ constructor(callback: () => void) { notify = callback; }+ observe = observe;+ disconnect = disconnect;+ });+ const signal = {+ aborted: false,+ addEventListener: vi.fn(),+ removeEventListener: removeAbort,+ } as unknown as AbortSignal;++ const pending = waitForTarget({ name: "connect-machine" }, 2000, signal);+ await vi.advanceTimersByTimeAsync(100);+ current = null;+ notify();+ await vi.advanceTimersByTimeAsync(500);+ let settled = false;+ void pending.then(() => { settled = true; });+ await Promise.resolve();+ expect(settled).toBe(false);+ current = second;+ notify();+ await vi.advanceTimersByTimeAsync(199);+ await Promise.resolve();+ expect(settled).toBe(false);+ await vi.advanceTimersByTimeAsync(1);+ await expect(pending).resolves.toBe(second);+ expect(observe).toHaveBeenCalledWith(document.body, {+ attributes: true,+ childList: true,+ subtree: true,+ });+ expect(disconnect).toHaveBeenCalledOnce();+ expect(removeAbort).toHaveBeenCalledWith("abort", expect.any(Function));+ expect(vi.getTimerCount()).toBe(0);+ notify();+ expect(disconnect).toHaveBeenCalledOnce();+ });++ it("uses the default 2000ms timeout and cleans a one-shot timeout finish", async () => {+ vi.useFakeTimers();+ let notify!: () => void;+ const disconnect = vi.fn();+ const removeEventListener = vi.fn();+ vi.stubGlobal("document", { body: {}, querySelectorAll: () => [] });+ vi.stubGlobal("window", { setTimeout, clearTimeout });+ vi.stubGlobal("MutationObserver", class {+ constructor(callback: () => void) { notify = callback; }+ observe() {}+ disconnect() { disconnect(); }+ });+ const signal = {+ aborted: false,+ addEventListener: vi.fn(),+ removeEventListener,+ } as unknown as AbortSignal;+ const pending = waitForTarget({ name: "connect-machine" }, undefined, signal);+ await vi.advanceTimersByTimeAsync(1999);+ let settled = false;+ void pending.then(() => { settled = true; });+ await Promise.resolve();+ expect(settled).toBe(false);+ await vi.advanceTimersByTimeAsync(1);+ await expect(pending).resolves.toBeNull();+ notify();+ expect(disconnect).toHaveBeenCalledOnce();+ expect(removeEventListener).toHaveBeenCalledWith("abort", expect.any(Function));+ expect(vi.getTimerCount()).toBe(0);+ });++ it("does no observer/timer work when already aborted and cleans mid-wait abort", async () => {+ vi.useFakeTimers();+ const disconnect = vi.fn();+ const constructObserver = vi.fn();+ let abort!: () => void;+ vi.stubGlobal("document", { body: {}, querySelectorAll: () => [] });+ vi.stubGlobal("window", { setTimeout, clearTimeout });+ vi.stubGlobal("MutationObserver", class {+ constructor() { constructObserver(); }+ observe() {}+ disconnect() { disconnect(); }+ });+ await expect(waitForTarget(+ { name: "connect-machine" },+ 2000,+ { aborted: true } as AbortSignal,+ )).resolves.toBeNull();+ expect(constructObserver).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);++ const signal = {+ aborted: false,+ addEventListener: vi.fn((_name: string, handler: () => void) => { abort = handler; }),+ removeEventListener: vi.fn(),+ } as unknown as AbortSignal;+ const pending = waitForTarget({ name: "connect-machine" }, 2000, signal);+ abort();+ await expect(pending).resolves.toBeNull();+ expect(disconnect).toHaveBeenCalledOnce();+ expect(vi.getTimerCount()).toBe(0);+ });++ it("keeps side preferences and exhaustive four-way avatar/popover geometry", () => {+ expect(guidePopoverSide({ name: "dm-composer" })).toBe("top");+ expect(guidePopoverSide({ name: "channel-composer" })).toBe("top");+ expect(guidePopoverSide({ name: "add-server" })).toBe("right");+ expect(guidePopoverSide({ name: "create-bot" })).toBe("bottom");+ expect(dismissGuideOnTargetClick({ name: "dm-composer" })).toBe(false);+ expect(dismissGuideOnTargetClick({ name: "channel-composer" })).toBe(true);++ const viewport = { top: 0, left: 0, width: 400, height: 300 };+ const centered = { top: 100, right: 220, bottom: 140, left: 100 };+ expect(adjacentAvatarLayout(+ centered, 28, viewport, "right",+ )).toEqual({ top: 150, left: 108 });+ expect(adjacentAvatarLayout(+ { top: 250, right: 220, bottom: 280, left: 100 }, 28, viewport, "right",+ )).toEqual({ top: 212, left: 108 });+ expect(adjacentAvatarLayout(+ centered, 28, viewport, "bottom",+ )).toEqual({ top: 108, left: 230 });+ expect(adjacentAvatarLayout(+ { top: 100, right: 390, bottom: 140, left: 350 }, 28, viewport, "top",+ )).toEqual({ top: 108, left: 312 });+ expect(adjacentAvatarLayout(+ { top: 15, right: 25, bottom: 25, left: 15 },+ 28,+ { top: 0, left: 0, width: 40, height: 40 },+ "top",+ )).toEqual({ top: 4, left: 4 });++ const targetRect = {+ top: 200, right: 260, bottom: 240, left: 140, width: 120, height: 40,+ };+ const popoverRect = { width: 80, height: 60 };+ const popoverViewport = { top: 0, left: 0, width: 600, height: 600 };+ expect(nonOverlappingPopoverLayout(+ targetRect, popoverRect, popoverViewport, "top",+ )).toEqual({ top: 128, left: 160 });+ expect(nonOverlappingPopoverLayout(+ targetRect, popoverRect, popoverViewport, "bottom",+ )).toEqual({ top: 252, left: 160 });+ expect(nonOverlappingPopoverLayout(+ targetRect, popoverRect, popoverViewport, "right",+ )).toEqual({ top: 190, left: 272 });+ expect(nonOverlappingPopoverLayout(+ { top: 200, right: 580, bottom: 240, left: 460, width: 120, height: 40 },+ popoverRect,+ popoverViewport,+ "right",+ )).toEqual({ top: 190, left: 368 });+ expect(nonOverlappingPopoverLayout(+ { top: 200, right: 20, bottom: 240, left: 0, width: 20, height: 40 },+ popoverRect,+ popoverViewport,+ "top",+ )).toEqual({ top: 128, left: 12 });+ expect(nonOverlappingPopoverLayout(+ { top: 100, right: 120, bottom: 140, left: 0, width: 120, height: 40 },+ { width: 700, height: 700 },+ popoverViewport,+ "top",+ )).toEqual({ top: -112, left: -112 });+ });++ it("positions with visualViewport, falls back to window, no-ops safely, and uses one RAF", async () => {++ const writes: unknown[][] = [];+ const wrapper = {+ getBoundingClientRect: () => ({ width: 100, height: 40 }),+ style: { setProperty: (...args: unknown[]) => writes.push(args) },+ };+ const target = element({ rect: { top: 50, right: 120, bottom: 90, left: 20, width: 100, height: 40 } });+ const popover = { closest: () => wrapper } as unknown as HTMLElement;+ const driver = { getActiveElement: () => target };+ const avatar = { style: {} } as HTMLElement;+ const requestAnimationFrame = vi.fn((callback: FrameRequestCallback) => {+ callback(7);+ return 7;+ });+ vi.stubGlobal("window", {+ innerWidth: 500,+ innerHeight: 400,+ visualViewport: { offsetTop: 10, offsetLeft: 5, width: 480, height: 360 },+ requestAnimationFrame,+ });+ pinPopoverAwayFromTarget(popover, driver as never, "top");+ positionFocusAvatar(avatar, target, "top");+ await nextFrame();+ expect(writes).toEqual([+ ["top", "102px", "important"],+ ["left", "20px", "important"],+ ["right", "auto", "important"],+ ["bottom", "auto", "important"],+ ]);+ expect(avatar.style.top).toBe("58px");+ expect(avatar.style.left).toBe("130px");++ const fallbackWrites: unknown[][] = [];+ const fallbackWrapper = {+ getBoundingClientRect: () => ({ width: 100, height: 40 }),+ style: { setProperty: (...args: unknown[]) => fallbackWrites.push(args) },+ };+ const fallbackTarget = element({+ rect: { top: 100, right: 200, bottom: 140, left: 100, width: 100, height: 40 },+ });+ vi.stubGlobal("window", {+ innerWidth: 500,+ innerHeight: 400,+ requestAnimationFrame,+ });+ pinPopoverAwayFromTarget(+ { closest: () => fallbackWrapper } as unknown as HTMLElement,+ { getActiveElement: () => fallbackTarget } as never,+ "top",+ );+ const fallbackAvatar = { style: {} } as HTMLElement;+ positionFocusAvatar(fallbackAvatar, fallbackTarget, "top");+ expect(fallbackWrites).toEqual([+ ["top", "48px", "important"],+ ["left", "100px", "important"],+ ["right", "auto", "important"],+ ["bottom", "auto", "important"],+ ]);+ expect(fallbackAvatar.style.top).toBe("108px");+ expect(fallbackAvatar.style.left).toBe("210px");++ const noOpWrites = vi.fn();+ pinPopoverAwayFromTarget(+ { closest: () => null } as unknown as HTMLElement,+ { getActiveElement: () => fallbackTarget } as never,+ "top",+ );+ pinPopoverAwayFromTarget(+ {+ closest: () => ({+ style: { setProperty: noOpWrites },+ getBoundingClientRect: () => ({ width: 1, height: 1 }),+ }),+ } as unknown as HTMLElement,+ { getActiveElement: () => null } as never,+ "top",+ );+ expect(noOpWrites).not.toHaveBeenCalled();+ expect(requestAnimationFrame).toHaveBeenCalledOnce();+ });+});diff --git a/src/web/src/components/community/onboarding/community-onboarding-guide-target.ts b/src/web/src/components/community/onboarding/community-onboarding-guide-target.tsnew file mode 100644index 000000000..971c976cc--- /dev/null+++ b/src/web/src/components/community/onboarding/community-onboarding-guide-target.ts@@ -0,0 +1,274 @@+import type { Driver } from "driver.js";+import type {+ GuidePopoverSide,+ GuideTarget,+ ViewportRect,+} from "./community-onboarding-guide-types";++export function guideTargetControl(element: HTMLElement) {+ if (element.matches("button:not([disabled]), [role=button], .ProseMirror")) return element;+ return element.querySelector<HTMLElement>("button:not([disabled]), [role=button], .ProseMirror");+}++export function isGuideTargetUsable(element: HTMLElement) {+ if (!element.isConnected) return false;+ const control = guideTargetControl(element);+ if (!control) return false;+ const elementStyle = window.getComputedStyle(element);+ const controlStyle = window.getComputedStyle(control);+ const rect = element.getBoundingClientRect();+ return (+ rect.width > 0 &&+ rect.height > 0 &&+ elementStyle.display !== "none" &&+ elementStyle.visibility !== "hidden" &&+ controlStyle.display !== "none" &&+ controlStyle.visibility !== "hidden" &&+ controlStyle.pointerEvents !== "none"+ );+}++export function findGuideTarget(guideTarget: GuideTarget) {+ const candidates = document.querySelectorAll<HTMLElement>(+ `[data-onboarding-target="${guideTarget.name}"]`,+ );+ for (const candidate of candidates) {+ if (guideTarget.resourceId && candidate.dataset.onboardingId !== guideTarget.resourceId) {+ continue;+ }+ if (!isGuideTargetUsable(candidate)) continue;+ const control = guideTargetControl(candidate);+ if (control) return control;+ }+ return null;+}++export function waitForTarget(+ guideTarget: GuideTarget,+ timeoutMs = 2000,+ signal?: AbortSignal,+) {+ return new Promise<HTMLElement | null>((resolve) => {+ if (signal?.aborted) {+ resolve(null);+ return;+ }+ let candidate: HTMLElement | null = null;+ let settleTimer: number | null = null;+ let observer: MutationObserver | null = null;+ let timeout: number | null = null;+ let finished = false;+ const finish = (target: HTMLElement | null) => {+ if (finished) return;+ finished = true;+ observer?.disconnect();+ if (settleTimer !== null) window.clearTimeout(settleTimer);+ if (timeout !== null) window.clearTimeout(timeout);+ signal?.removeEventListener("abort", handleAbort);+ resolve(target);+ };+ const handleAbort = () => finish(null);+ const check = () => {+ const next = findGuideTarget(guideTarget);+ if (next === candidate) return;+ if (settleTimer !== null) window.clearTimeout(settleTimer);+ candidate = next;+ if (!candidate) return;+ settleTimer = window.setTimeout(() => {+ const current = findGuideTarget(guideTarget);+ if (current && current === candidate) finish(current);+ else check();+ }, 200);+ };+ observer = new MutationObserver(check);+ timeout = window.setTimeout(() => finish(null), timeoutMs);+ signal?.addEventListener("abort", handleAbort, { once: true });+ observer.observe(document.body, { attributes: true, childList: true, subtree: true });+ check();+ });+}++export function rectFitsViewport(+ rect: Pick<DOMRect, "top" | "right" | "bottom" | "left" | "width" | "height">,+ viewportWidth: number,+ viewportHeight: number,+) {+ const tolerance = 1;+ return (+ rect.width > 0 &&+ rect.height > 0 &&+ rect.top >= -tolerance &&+ rect.left >= -tolerance &&+ rect.bottom <= viewportHeight + tolerance &&+ rect.right <= viewportWidth + tolerance+ );+}++export function targetIsInViewport(element: HTMLElement) {+ const control = guideTargetControl(element) ?? element;+ return rectFitsViewport(control.getBoundingClientRect(), window.innerWidth, window.innerHeight);+}++export function shouldAutoRouteGuide(+ route: string | undefined,+ pathname: string,+ routeKey: string,+ routedKey: string | null,+) {+ return Boolean(route && pathname !== route && routedKey !== routeKey);+}++export function guidePopoverSide(guideTarget: GuideTarget): GuidePopoverSide {+ if (guideTarget.name === "dm-composer" || guideTarget.name === "channel-composer") {+ return "top";+ }+ if (guideTarget.name === "add-server") return "right";+ return "bottom";+}++export function dismissGuideOnTargetClick(guideTarget: GuideTarget) {+ return guideTarget.name !== "dm-composer";+}++export function adjacentAvatarLayout(+ targetRect: Pick<DOMRect, "top" | "right" | "bottom" | "left">,+ avatarSize: number,+ viewport: ViewportRect,+ popoverSide: GuidePopoverSide,+) {+ const margin = 8;+ const gap = 10;+ const viewportRight = viewport.left + viewport.width;+ const viewportBottom = viewport.top + viewport.height;+ const clampLeft = (left: number) =>+ Math.min(Math.max(left, viewport.left + margin), viewportRight - avatarSize - margin);+ const clampTop = (top: number) =>+ Math.min(Math.max(top, viewport.top + margin), viewportBottom - avatarSize - margin);+ const positions = {+ right: { top: clampTop(targetRect.top + 8), left: targetRect.right + gap },+ left: { top: clampTop(targetRect.top + 8), left: targetRect.left - gap - avatarSize },+ top: { top: targetRect.top - gap - avatarSize, left: clampLeft(targetRect.left + 8) },+ bottom: { top: targetRect.bottom + gap, left: clampLeft(targetRect.left + 8) },+ };+ const candidates =+ popoverSide === "right"+ ? [positions.bottom, positions.top, positions.left, positions.right]+ : popoverSide === "bottom"+ ? [positions.right, positions.left, positions.top, positions.bottom]+ : [positions.right, positions.left, positions.bottom, positions.top];+ const fits = ({ top, left }: { top: number; left: number }) =>+ top >= viewport.top + margin &&+ left >= viewport.left + margin &&+ top + avatarSize <= viewportBottom - margin &&+ left + avatarSize <= viewportRight - margin;++ return candidates.find(fits) ?? {+ top: clampTop(targetRect.top - avatarSize - gap),+ left: clampLeft(targetRect.left + 8),+ };+}++export function nonOverlappingPopoverLayout(+ targetRect: Pick<DOMRect, "top" | "right" | "bottom" | "left" | "width" | "height">,+ popoverRect: Pick<DOMRect, "width" | "height">,+ viewport: ViewportRect,+ preferredSide: GuidePopoverSide = "top",+) {+ const margin = 12;+ const gap = 12;+ const viewportRight = viewport.left + viewport.width;+ const viewportBottom = viewport.top + viewport.height;+ const centeredLeft = Math.min(+ Math.max(+ targetRect.left + targetRect.width / 2 - popoverRect.width / 2,+ viewport.left + margin,+ ),+ viewportRight - popoverRect.width - margin,+ );+ const centeredTop = Math.min(+ Math.max(+ targetRect.top + targetRect.height / 2 - popoverRect.height / 2,+ viewport.top + margin,+ ),+ viewportBottom - popoverRect.height - margin,+ );+ const above = { top: targetRect.top - gap - popoverRect.height, left: centeredLeft };+ const below = { top: targetRect.bottom + gap, left: centeredLeft };+ const right = { top: centeredTop, left: targetRect.right + gap };+ const left = { top: centeredTop, left: targetRect.left - gap - popoverRect.width };+ const candidates =+ preferredSide === "bottom"+ ? [below, above, right, left]+ : preferredSide === "right"+ ? [right, left, below, above]+ : [above, below, right, left];+ const fits = ({ top, left }: { top: number; left: number }) =>+ top >= viewport.top + margin &&+ left >= viewport.left + margin &&+ top + popoverRect.height <= viewportBottom - margin &&+ left + popoverRect.width <= viewportRight - margin;+ const fittingCandidate = candidates.find(fits);+ if (fittingCandidate) return fittingCandidate;++ const targetCenterY = targetRect.top + targetRect.height / 2;+ return {+ top:+ targetCenterY >= viewport.top + viewport.height / 2+ ? viewport.top + margin+ : viewportBottom - popoverRect.height - margin,+ left: centeredLeft,+ };+}++export function pinPopoverAwayFromTarget(+ popoverContainer: HTMLElement,+ instance: Driver,+ preferredSide: GuidePopoverSide,+) {+ const wrapper = popoverContainer.closest<HTMLElement>(".driver-popover");+ const activeTarget = instance.getActiveElement();+ if (!wrapper || !activeTarget) return;+ const visualViewport = window.visualViewport;+ const viewport = {+ top: visualViewport?.offsetTop ?? 0,+ left: visualViewport?.offsetLeft ?? 0,+ width: visualViewport?.width ?? window.innerWidth,+ height: visualViewport?.height ?? window.innerHeight,+ };+ const layout = nonOverlappingPopoverLayout(+ activeTarget.getBoundingClientRect(),+ wrapper.getBoundingClientRect(),+ viewport,+ preferredSide,+ );+ wrapper.style.setProperty("top", `${layout.top}px`, "important");+ wrapper.style.setProperty("left", `${layout.left}px`, "important");+ wrapper.style.setProperty("right", "auto", "important");+ wrapper.style.setProperty("bottom", "auto", "important");+}++export function positionFocusAvatar(+ avatarContainer: HTMLElement,+ activeTarget: Element,+ popoverSide: GuidePopoverSide,+) {+ const visualViewport = window.visualViewport;+ const viewport = {+ top: visualViewport?.offsetTop ?? 0,+ left: visualViewport?.offsetLeft ?? 0,+ width: visualViewport?.width ?? window.innerWidth,+ height: visualViewport?.height ?? window.innerHeight,+ };+ const layout = adjacentAvatarLayout(+ activeTarget.getBoundingClientRect(),+ 28,+ viewport,+ popoverSide,+ );+ avatarContainer.style.top = `${layout.top}px`;+ avatarContainer.style.left = `${layout.left}px`;+}++export function nextFrame() {+ return new Promise<void>((resolve) => window.requestAnimationFrame(() => resolve()));+}diff --git a/src/web/src/components/community/onboarding/community-onboarding-guide-types.ts b/src/web/src/components/community/onboarding/community-onboarding-guide-types.tsnew file mode 100644index 000000000..46aa92c3a--- /dev/null+++ b/src/web/src/components/community/onboarding/community-onboarding-guide-types.ts@@ -0,0 +1,38 @@+import type { CommunityMachineSummary } from "@alook/shared";+import type { BotSummary } from "@/hooks/community/use-bots";+import type { CommunityOnboardingState } from "@/lib/community-onboarding";++export type GuideTarget = {+ name:+ | "channel-composer"+ | "connect-machine"+ | "reconnect-machine"+ | "create-bot"+ | "dm-composer"+ | "add-server";+ resourceId?: string;+};++export type GuideCopy = {+ target: GuideTarget;+ eyebrow: string;+ title: string;+ route?: string;+};++export type GuidePopoverSide = "top" | "right" | "bottom";++export type GuideContext = {+ machines: Pick<CommunityMachineSummary, "id" | "status">[];+ bots: Pick<BotSummary, "id" | "machineId">[];+};++export type ViewportRect = { top: number; left: number; width: number; height: number };++export type CommunityOnboardingGuideController = {+ copy: GuideCopy | null;+ state: CommunityOnboardingState | null;+ popoverContainer: HTMLElement | null;+ targetAvatarContainer: HTMLElement | null;+ onSkip: () => void;+};diff --git a/src/web/src/components/community/onboarding/community-onboarding-guide-view.test.ts b/src/web/src/components/community/onboarding/community-onboarding-guide-view.test.tsnew file mode 100644index 000000000..76793359f--- /dev/null+++ b/src/web/src/components/community/onboarding/community-onboarding-guide-view.test.ts@@ -0,0 +1,182 @@+import { readFileSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import React from "react";+import TestRenderer, { act } from "react-test-renderer";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { CommunityOnboardingGuideController } from "./community-onboarding-guide-types";++const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..");+const readWebSource = (path: string) =>+ readFileSync(resolve(webRoot, path), "utf8").replaceAll("\r\n", "\n");++vi.mock("react-dom", async () => {+ const ReactModule = await import("react");+ return {+ createPortal: (child: React.ReactNode, container: Element) =>+ ReactModule.createElement("portal", { container }, child),+ };+});+vi.mock("@/components/avatar", () => ({+ GeneratedAvatar: (props: Record<string, unknown>) => React.createElement("avatar", props),+}));+vi.mock("@/components/ui/button", () => ({+ Button: ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) =>+ React.createElement("button", props, children),+}));++import { renderCommunityOnboardingGuide } from "./community-onboarding-guide-view";++function controller(+ overrides: Partial<CommunityOnboardingGuideController> = {},+): CommunityOnboardingGuideController {+ return {+ copy: {+ target: { name: "create-bot" },+ eyebrow: "Step 2 of 4",+ title: "Create a bot with a voice of its own",+ route: "/c/me/bots",+ },+ state: { status: "active", stage: "bot", guideAvatarSeed: "guide-7" },+ popoverContainer: null,+ targetAvatarContainer: null,+ onSkip: vi.fn(),+ ...overrides,+ };+}++describe("renderCommunityOnboardingGuide", () => {+ afterEach(() => vi.unstubAllGlobals());++ it("returns null unless both copy and state exist", () => {+ expect(renderCommunityOnboardingGuide(controller({ copy: null }))).toBeNull();+ expect(renderCommunityOnboardingGuide(controller({ state: null }))).toBeNull();+ });++ it("keeps one Fragment with popover then avatar portals and exact destinations", () => {+ vi.stubGlobal("window", {+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ });+ const popoverContainer = { id: "popover" } as unknown as HTMLElement;+ const targetAvatarContainer = { id: "avatar" } as unknown as HTMLElement;+ let renderer!: TestRenderer.ReactTestRenderer;+ act(() => {+ renderer = TestRenderer.create(renderCommunityOnboardingGuide(controller({+ popoverContainer,+ targetAvatarContainer,+ })));+ });+ const portals = renderer.root.findAllByType("portal");+ expect(portals).toHaveLength(2);+ expect(portals.map((portal) => portal.props.container)).toEqual([+ popoverContainer,+ targetAvatarContainer,+ ]);+ expect(renderer.root.findByType("avatar").props).toEqual({+ seed: "guide-7",+ size: 28,+ className: "rounded-full ring-2 ring-background shadow-md",+ });++ const source = readWebSource(+ "src/components/community/onboarding/community-onboarding-guide-view.tsx",+ );+ expect(source.indexOf("? createPortal(")).toBeLessThan(+ source.lastIndexOf("? createPortal("),+ );+ expect(source).toContain("<>\n {popoverContainer");+ });++ it("uses the exact fallback avatar seed", () => {+ let renderer!: TestRenderer.ReactTestRenderer;+ act(() => {+ renderer = TestRenderer.create(renderCommunityOnboardingGuide(controller({+ state: { status: "active", stage: "server" },+ targetAvatarContainer: {} as HTMLElement,+ })));+ });+ expect(renderer.root.findByType("avatar").props.seed).toBe("alook-guide");+ });++ it("keeps GuideCard DOM and the capture Escape listener lifecycle", () => {+ const calls: string[] = [];+ const onSkip = vi.fn();+ const replacementSkip = vi.fn(() => calls.push("skip"));+ let keydown!: (event: KeyboardEvent) => void;+ const handlers: Array<(event: KeyboardEvent) => void> = [];+ const addEventListener = vi.fn((name: string, handler: (event: KeyboardEvent) => void) => {+ if (name === "keydown") {+ keydown = handler;+ handlers.push(handler);+ }+ });+ const removeEventListener = vi.fn();+ vi.stubGlobal("window", { addEventListener, removeEventListener });+ let renderer!: TestRenderer.ReactTestRenderer;+ act(() => {+ renderer = TestRenderer.create(renderCommunityOnboardingGuide(controller({+ popoverContainer: {} as HTMLElement,+ onSkip,+ })));+ });+ expect(addEventListener).toHaveBeenCalledWith("keydown", expect.any(Function), true);+ expect(renderer.root.findAllByProps({ className: "community-onboarding-card" }))+ .toHaveLength(1);+ expect(renderer.root.findAllByProps({ className: "community-onboarding-content" }))+ .toHaveLength(1);+ expect(renderer.root.findAllByProps({ className: "community-onboarding-meta" }))+ .toHaveLength(1);+ expect(renderer.root.findByProps({ className: "community-onboarding-eyebrow" }).children)+ .toEqual(["Step 2 of 4"]);+ expect(renderer.root.findByType("h2").children)+ .toEqual(["Create a bot with a voice of its own"]);+ const skip = renderer.root.findByType("button");+ expect(skip.props).toMatchObject({+ variant: "ghost",+ className: "community-onboarding-skip",+ });+ expect(skip.children).toEqual(["Skip guide"]);++ const ordinary = { key: "Enter", preventDefault: vi.fn(), stopPropagation: vi.fn() };+ act(() => keydown(ordinary as unknown as KeyboardEvent));+ expect(onSkip).not.toHaveBeenCalled();+ const escape = {+ key: "Escape",+ preventDefault: vi.fn(() => calls.push("prevent")),+ stopPropagation: vi.fn(() => calls.push("stop")),+ };+ act(() => keydown(escape as unknown as KeyboardEvent));+ expect(escape.preventDefault).toHaveBeenCalledOnce();+ expect(escape.stopPropagation).toHaveBeenCalledOnce();+ expect(onSkip).toHaveBeenCalledOnce();+ calls.length = 0;++ const firstHandler = handlers[0]!;+ act(() => {+ renderer.update(renderCommunityOnboardingGuide(controller({+ popoverContainer: {} as HTMLElement,+ onSkip: replacementSkip,+ })));+ });+ expect(removeEventListener).toHaveBeenCalledWith("keydown", firstHandler, true);+ expect(addEventListener).toHaveBeenCalledTimes(2);+ expect(handlers[1]).not.toBe(firstHandler);+ expect(removeEventListener.mock.invocationCallOrder[0])+ .toBeLessThan(addEventListener.mock.invocationCallOrder[1]!);++ const replacementEscape = {+ key: "Escape",+ preventDefault: vi.fn(() => calls.push("prevent")),+ stopPropagation: vi.fn(() => calls.push("stop")),+ };+ act(() => keydown(replacementEscape as unknown as KeyboardEvent));+ expect(calls).toEqual(["prevent", "stop", "skip"]);+ expect(replacementSkip).toHaveBeenCalledOnce();+ expect(onSkip).toHaveBeenCalledOnce();++ const replacementHandler = keydown;+ act(() => renderer.unmount());+ expect(removeEventListener).toHaveBeenLastCalledWith("keydown", replacementHandler, true);+ });+});diff --git a/src/web/src/components/community/onboarding/community-onboarding-guide-view.tsx b/src/web/src/components/community/onboarding/community-onboarding-guide-view.tsxnew file mode 100644index 000000000..2b58749c1--- /dev/null+++ b/src/web/src/components/community/onboarding/community-onboarding-guide-view.tsx@@ -0,0 +1,70 @@+import { useEffect } from "react";+import { createPortal } from "react-dom";+import { GeneratedAvatar } from "@/components/avatar";+import { Button } from "@/components/ui/button";+import type {+ CommunityOnboardingGuideController,+ GuideCopy,+} from "./community-onboarding-guide-types";++function GuideCard({+ copy,+ onSkip,+}: {+ copy: GuideCopy;+ onSkip: () => void;+}) {+ useEffect(() => {+ const handleKeyDown = (event: KeyboardEvent) => {+ if (event.key !== "Escape") return;+ event.preventDefault();+ event.stopPropagation();+ onSkip();+ };+ window.addEventListener("keydown", handleKeyDown, true);+ return () => window.removeEventListener("keydown", handleKeyDown, true);+ }, [onSkip]);+ return (+ <div className="community-onboarding-card">+ <div className="community-onboarding-content">+ <div className="community-onboarding-meta">+ <p className="community-onboarding-eyebrow">{copy.eyebrow}</p>+ <Button variant="ghost" className="community-onboarding-skip" onClick={onSkip}>+ Skip guide+ </Button>+ </div>+ <h2>{copy.title}</h2>+ </div>+ </div>+ );+}++export function renderCommunityOnboardingGuide({+ copy,+ state,+ popoverContainer,+ targetAvatarContainer,+ onSkip,+}: CommunityOnboardingGuideController) {+ if (!copy || !state) return null;+ return (+ <>+ {popoverContainer+ ? createPortal(+ <GuideCard copy={copy} onSkip={onSkip} />,+ popoverContainer,+ )+ : null}+ {targetAvatarContainer+ ? createPortal(+ <GeneratedAvatar+ seed={state.guideAvatarSeed ?? "alook-guide"}+ size={28}+ className="rounded-full ring-2 ring-background shadow-md"+ />,+ targetAvatarContainer,+ )+ : null}+ </>+ );+}diff --git a/src/web/src/components/community/onboarding/community-onboarding-guide.tsx b/src/web/src/components/community/onboarding/community-onboarding-guide.tsxindex 33b674d17..084ca73dc 100644--- a/src/web/src/components/community/onboarding/community-onboarding-guide.tsx+++ b/src/web/src/components/community/onboarding/community-onboarding-guide.tsx@@ -1,648 +1,21 @@"use client";-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";-import { createPortal } from "react-dom";-import { usePathname, useRouter } from "next/navigation";-import { GeneratedAvatar } from "@/components/avatar";-import { Button } from "@/components/ui/button";-import { driver, type Driver } from "driver.js";-import { isPresenceOnline, type CommunityMachineSummary } from "@alook/shared";-import { useMachines } from "@/hooks/community/use-machines";-import { useBots, type BotSummary } from "@/hooks/community/use-bots";-import {- advanceCommunityOnboarding,- recoverCommunityOnboardingMachine,- skipCommunityOnboarding,- type CommunityOnboardingState,- useCommunityOnboarding,-} from "@/lib/community-onboarding";--type GuideCopy = {- target: GuideTarget;- eyebrow: string;- title: string;- route?: string;-};--type GuideTarget = {- name: "channel-composer" | "connect-machine" | "reconnect-machine" | "create-bot" | "dm-composer" | "add-server";- resourceId?: string;-};--type GuidePopoverSide = "top" | "right" | "bottom";--type GuideContext = {- machines: Pick<CommunityMachineSummary, "id" | "status">[];- bots: Pick<BotSummary, "id" | "machineId">[];-};--const target = (name: GuideTarget["name"], resourceId?: string): GuideTarget => ({- name,- ...(resourceId ? { resourceId } : {}),-});--function stableOfflineMachine(machines: GuideContext["machines"]) {- return machines- .filter((machine) => !isPresenceOnline(machine.status))- .sort((a, b) => a.id.localeCompare(b.id))[0];-}--function recoveryCopy(machine: GuideContext["machines"][number], eyebrow: string): GuideCopy {- return {- target: target("reconnect-machine", machine.id),- eyebrow,- title: "Bring your machine back online",- route: "/c/me/machines",- };-}--export function guideCopy(- state: CommunityOnboardingState,- { machines, bots }: GuideContext,-): GuideCopy | null {- if (state.stage === "machine") {- if (machines.some((machine) => isPresenceOnline(machine.status))) return null;- const offlineMachine = stableOfflineMachine(machines);- if (offlineMachine) return recoveryCopy(offlineMachine, "Step 1 of 4");- return {- target: target("connect-machine"),- eyebrow: "Step 1 of 4",- title: "Give your bot a place to run",- route: "/c/me/machines",- };- }- if (state.stage === "bot") {- const boundMachineId = state.botId- ? bots.find((bot) => bot.id === state.botId)?.machineId- : undefined;- const boundMachine = boundMachineId- ? machines.find((machine) => machine.id === boundMachineId)- : undefined;- if (boundMachine && !isPresenceOnline(boundMachine.status)) {- return recoveryCopy(boundMachine, "Step 2 of 4");- }- if (!machines.some((machine) => isPresenceOnline(machine.status))) {- const offlineMachine = stableOfflineMachine(machines);- if (offlineMachine) return recoveryCopy(offlineMachine, "Step 2 of 4");- return {- target: target("connect-machine"),- eyebrow: "Step 2 of 4",- title: "Give your bot a place to run",- route: "/c/me/machines",- };- }- if (state.botId) {- return {- target: target("create-bot"),- eyebrow: "Step 2 of 4",- title: "Meet your bot in chat",- route: "/c/me/bots",- };- }- return {- target: target("create-bot"),- eyebrow: "Step 2 of 4",- title: "Create a bot with a voice of its own",- route: "/c/me/bots",- };- }- if (state.stage === "dm") {- return {- target: target("dm-composer"),- eyebrow: "Step 3 of 4",- title: "Start a conversation with your bot",- route: state.dmId ? `/c/me/${state.dmId}` : undefined,- };- }- const recovering = Boolean(state.serverId);- return {- target: target("add-server"),- eyebrow: "Step 4 of 4",- title: recovering- ? "Bring your bot into the server"- : "Make a shared home for friends and family",- };-}--function guideTargetControl(element: HTMLElement) {- if (element.matches("button:not([disabled]), [role=button], .ProseMirror")) return element;- return element.querySelector<HTMLElement>("button:not([disabled]), [role=button], .ProseMirror");-}--function isGuideTargetUsable(element: HTMLElement) {- if (!element.isConnected) return false;- const control = guideTargetControl(element);- if (!control) return false;- const elementStyle = window.getComputedStyle(element);- const controlStyle = window.getComputedStyle(control);- const rect = element.getBoundingClientRect();- return (- rect.width > 0 &&- rect.height > 0 &&- elementStyle.display !== "none" &&- elementStyle.visibility !== "hidden" &&- controlStyle.display !== "none" &&- controlStyle.visibility !== "hidden" &&- controlStyle.pointerEvents !== "none"- );-}--export function findGuideTarget(guideTarget: GuideTarget) {- const candidates = document.querySelectorAll<HTMLElement>(- `[data-onboarding-target="${guideTarget.name}"]`,- );- for (const candidate of candidates) {- if (guideTarget.resourceId && candidate.dataset.onboardingId !== guideTarget.resourceId) {- continue;- }- if (!isGuideTargetUsable(candidate)) continue;- const control = guideTargetControl(candidate);- if (control) return control;- }- return null;-}--export function waitForTarget(- guideTarget: GuideTarget,- timeoutMs = 2000,- signal?: AbortSignal,-) {- return new Promise<HTMLElement | null>((resolve) => {- if (signal?.aborted) {- resolve(null);- return;- }- let candidate: HTMLElement | null = null;- let settleTimer: number | null = null;- let observer: MutationObserver | null = null;- let timeout: number | null = null;- let finished = false;- const finish = (target: HTMLElement | null) => {- if (finished) return;- finished = true;- observer?.disconnect();- if (settleTimer !== null) window.clearTimeout(settleTimer);- if (timeout !== null) window.clearTimeout(timeout);- signal?.removeEventListener("abort", handleAbort);- resolve(target);- };- const handleAbort = () => finish(null);- const check = () => {- const next = findGuideTarget(guideTarget);- if (next === candidate) return;- if (settleTimer !== null) window.clearTimeout(settleTimer);- candidate = next;- if (!candidate) return;- settleTimer = window.setTimeout(() => {- const current = findGuideTarget(guideTarget);- if (current && current === candidate) finish(current);- else check();- }, 200);- };- observer = new MutationObserver(check);- timeout = window.setTimeout(() => finish(null), timeoutMs);- signal?.addEventListener("abort", handleAbort, { once: true });- observer.observe(document.body, { attributes: true, childList: true, subtree: true });- check();- });-}--export function rectFitsViewport(- rect: Pick<DOMRect, "top" | "right" | "bottom" | "left" | "width" | "height">,- viewportWidth: number,- viewportHeight: number,-) {- const tolerance = 1;- return (- rect.width > 0 &&- rect.height > 0 &&- rect.top >= -tolerance &&- rect.left >= -tolerance &&- rect.bottom <= viewportHeight + tolerance &&- rect.right <= viewportWidth + tolerance- );-}--function targetIsInViewport(element: HTMLElement) {- const control = guideTargetControl(element) ?? element;- return rectFitsViewport(control.getBoundingClientRect(), window.innerWidth, window.innerHeight);-}--export function shouldAutoRouteGuide(- route: string | undefined,- pathname: string,- routeKey: string,- routedKey: string | null,-) {- return Boolean(route && pathname !== route && routedKey !== routeKey);-}--export function guidePopoverSide(guideTarget: GuideTarget): GuidePopoverSide {- if (guideTarget.name === "dm-composer" || guideTarget.name === "channel-composer") {- return "top";- }- if (guideTarget.name === "add-server") return "right";- return "bottom";-}--export function dismissGuideOnTargetClick(guideTarget: GuideTarget) {- return guideTarget.name !== "dm-composer";-}--type ViewportRect = { top: number; left: number; width: number; height: number };--export function adjacentAvatarLayout(- targetRect: Pick<DOMRect, "top" | "right" | "bottom" | "left">,- avatarSize: number,- viewport: ViewportRect,- popoverSide: GuidePopoverSide,-) {- const margin = 8;- const gap = 10;- const viewportRight = viewport.left + viewport.width;- const viewportBottom = viewport.top + viewport.height;- const clampLeft = (left: number) =>- Math.min(Math.max(left, viewport.left + margin), viewportRight - avatarSize - margin);- const clampTop = (top: number) =>- Math.min(Math.max(top, viewport.top + margin), viewportBottom - avatarSize - margin);- const positions = {- right: { top: clampTop(targetRect.top + 8), left: targetRect.right + gap },- left: { top: clampTop(targetRect.top + 8), left: targetRect.left - gap - avatarSize },- top: { top: targetRect.top - gap - avatarSize, left: clampLeft(targetRect.left + 8) },- bottom: { top: targetRect.bottom + gap, left: clampLeft(targetRect.left + 8) },- };- const candidates =- popoverSide === "right"- ? [positions.bottom, positions.top, positions.left, positions.right]- : popoverSide === "bottom"- ? [positions.right, positions.left, positions.top, positions.bottom]- : [positions.right, positions.left, positions.bottom, positions.top];- const fits = ({ top, left }: { top: number; left: number }) =>- top >= viewport.top + margin &&- left >= viewport.left + margin &&- top + avatarSize <= viewportBottom - margin &&- left + avatarSize <= viewportRight - margin;-- return candidates.find(fits) ?? {- top: clampTop(targetRect.top - avatarSize - gap),- left: clampLeft(targetRect.left + 8),- };-}--export function nonOverlappingPopoverLayout(- targetRect: Pick<DOMRect, "top" | "right" | "bottom" | "left" | "width" | "height">,- popoverRect: Pick<DOMRect, "width" | "height">,- viewport: ViewportRect,- preferredSide: GuidePopoverSide = "top",-) {- const margin = 12;- const gap = 12;- const viewportRight = viewport.left + viewport.width;- const viewportBottom = viewport.top + viewport.height;- const centeredLeft = Math.min(- Math.max(- targetRect.left + targetRect.width / 2 - popoverRect.width / 2,- viewport.left + margin,- ),- viewportRight - popoverRect.width - margin,- );- const centeredTop = Math.min(- Math.max(- targetRect.top + targetRect.height / 2 - popoverRect.height / 2,- viewport.top + margin,- ),- viewportBottom - popoverRect.height - margin,- );- const above = { top: targetRect.top - gap - popoverRect.height, left: centeredLeft };- const below = { top: targetRect.bottom + gap, left: centeredLeft };- const right = { top: centeredTop, left: targetRect.right + gap };- const left = { top: centeredTop, left: targetRect.left - gap - popoverRect.width };- const candidates =- preferredSide === "bottom"- ? [below, above, right, left]- : preferredSide === "right"- ? [right, left, below, above]- : [above, below, right, left];- const fits = ({ top, left }: { top: number; left: number }) =>- top >= viewport.top + margin &&- left >= viewport.left + margin &&- top + popoverRect.height <= viewportBottom - margin &&- left + popoverRect.width <= viewportRight - margin;- const fittingCandidate = candidates.find(fits);- if (fittingCandidate) return fittingCandidate;-- const targetCenterY = targetRect.top + targetRect.height / 2;- return {- top:- targetCenterY >= viewport.top + viewport.height / 2- ? viewport.top + margin- : viewportBottom - popoverRect.height - margin,- left: centeredLeft,- };-}--function pinPopoverAwayFromTarget(- popoverContainer: HTMLElement,- instance: Driver,- preferredSide: GuidePopoverSide,-) {- const wrapper = popoverContainer.closest<HTMLElement>(".driver-popover");- const activeTarget = instance.getActiveElement();- if (!wrapper || !activeTarget) return;- const visualViewport = window.visualViewport;- const viewport = {- top: visualViewport?.offsetTop ?? 0,- left: visualViewport?.offsetLeft ?? 0,- width: visualViewport?.width ?? window.innerWidth,- height: visualViewport?.height ?? window.innerHeight,- };- const layout = nonOverlappingPopoverLayout(- activeTarget.getBoundingClientRect(),- wrapper.getBoundingClientRect(),- viewport,- preferredSide,- );- wrapper.style.setProperty("top", `${layout.top}px`, "important");- wrapper.style.setProperty("left", `${layout.left}px`, "important");- wrapper.style.setProperty("right", "auto", "important");- wrapper.style.setProperty("bottom", "auto", "important");-}--function positionFocusAvatar(- avatarContainer: HTMLElement,- activeTarget: Element,- popoverSide: GuidePopoverSide,-) {- const visualViewport = window.visualViewport;- const viewport = {- top: visualViewport?.offsetTop ?? 0,- left: visualViewport?.offsetLeft ?? 0,- width: visualViewport?.width ?? window.innerWidth,- height: visualViewport?.height ?? window.innerHeight,- };- const layout = adjacentAvatarLayout(- activeTarget.getBoundingClientRect(),- 28,- viewport,- popoverSide,- );- avatarContainer.style.top = `${layout.top}px`;- avatarContainer.style.left = `${layout.left}px`;-}--function nextFrame() {- return new Promise<void>((resolve) => window.requestAnimationFrame(() => resolve()));-}--function GuideCard({- copy,- onSkip,-}: {- copy: GuideCopy;- onSkip: () => void;-}) {- useEffect(() => {- const handleKeyDown = (event: KeyboardEvent) => {- if (event.key !== "Escape") return;- event.preventDefault();- event.stopPropagation();- onSkip();- };- window.addEventListener("keydown", handleKeyDown, true);- return () => window.removeEventListener("keydown", handleKeyDown, true);- }, [onSkip]);- return (- <div className="community-onboarding-card">- <div className="community-onboarding-content">- <div className="community-onboarding-meta">- <p className="community-onboarding-eyebrow">{copy.eyebrow}</p>- <Button variant="ghost" className="community-onboarding-skip" onClick={onSkip}>- Skip guide- </Button>- </div>- <h2>{copy.title}</h2>- </div>- </div>- );-}+import { useCommunityOnboardingGuideController } from "./community-onboarding-guide-controller";+import { renderCommunityOnboardingGuide } from "./community-onboarding-guide-view";++export { guideCopy } from "./community-onboarding-guide-copy";+export {+ adjacentAvatarLayout,+ dismissGuideOnTargetClick,+ findGuideTarget,+ guidePopoverSide,+ nonOverlappingPopoverLayout,+ rectFitsViewport,+ shouldAutoRouteGuide,+ waitForTarget,+} from "./community-onboarding-guide-target";export function CommunityOnboardingGuide() {- const router = useRouter();- const pathname = usePathname();- const machinesQuery = useMachines();- const botsQuery = useBots();- const state = useCommunityOnboarding();- const [popoverContainer, setPopoverContainer] = useState<HTMLElement | null>(null);- const [targetAvatarContainer, setTargetAvatarContainer] = useState<HTMLElement | null>(null);- const driverRef = useRef<Driver | null>(null);- const targetAvatarRef = useRef<HTMLElement | null>(null);- const routedGuideRef = useRef<string | null>(null);-- const copy = useMemo(- () => {- if (!state) return null;- if ((state.stage === "machine" || state.stage === "bot") && !machinesQuery.isSuccess) {- return null;- }- if (- state.stage === "bot" &&- state.botId &&- !botsQuery.isSuccess- ) {- return null;- }- return guideCopy(state, {- machines: machinesQuery.machines,- bots: botsQuery.bots,- });- },- [state, machinesQuery.isSuccess, machinesQuery.machines, botsQuery.isSuccess, botsQuery.bots],- );- const destroyGuide = useCallback(() => {- const instance = driverRef.current;- driverRef.current = null;- instance?.destroy();- targetAvatarRef.current?.remove();- targetAvatarRef.current = null;- document.body.classList.remove("community-onboarding-active");- setPopoverContainer(null);- setTargetAvatarContainer(null);- }, []);-- useEffect(() => {- if (- state?.status !== "active" ||- state.stage !== "machine" ||- !machinesQuery.isSuccess ||- !machinesQuery.machines.some((machine) => isPresenceOnline(machine.status))- ) {- return;- }- advanceCommunityOnboarding("machine", "bot");- }, [state, machinesQuery.isSuccess, machinesQuery.machines]);-- useEffect(() => {- const recoveryTarget =- copy?.target.name === "connect-machine" || copy?.target.name === "reconnect-machine";- if (!recoveryTarget || state?.status !== "active" || state.stage !== "bot" || state.machineRecovery) return;- recoverCommunityOnboardingMachine();- }, [copy, state]);-- useLayoutEffect(() => {- if (!popoverContainer) return;- let positionFrame: number | null = null;- const refresh = () => {- const instance = driverRef.current;- if (!instance) return;- instance.refresh();- if (positionFrame !== null) window.cancelAnimationFrame(positionFrame);- positionFrame = window.requestAnimationFrame(() => {- positionFrame = null;- if (!copy) return;- const popoverSide = guidePopoverSide(copy.target);- pinPopoverAwayFromTarget(popoverContainer, instance, popoverSide);- const activeTarget = instance.getActiveElement();- if (targetAvatarRef.current && activeTarget) {- positionFocusAvatar(targetAvatarRef.current, activeTarget, popoverSide);- }- });- };- refresh();- if (typeof ResizeObserver === "undefined") {- return () => {- if (positionFrame !== null) window.cancelAnimationFrame(positionFrame);- };- }- const observer = new ResizeObserver(refresh);- observer.observe(popoverContainer);- if (popoverContainer.parentElement) observer.observe(popoverContainer.parentElement);- window.addEventListener("resize", refresh);- window.addEventListener("scroll", refresh, true);- window.visualViewport?.addEventListener("resize", refresh);- window.visualViewport?.addEventListener("scroll", refresh);- return () => {- if (positionFrame !== null) window.cancelAnimationFrame(positionFrame);- observer.disconnect();- window.removeEventListener("resize", refresh);- window.removeEventListener("scroll", refresh, true);- window.visualViewport?.removeEventListener("resize", refresh);- window.visualViewport?.removeEventListener("scroll", refresh);- };- }, [popoverContainer, copy]);-- useEffect(() => {- destroyGuide();- if (!copy || !state) return;- const stageKey = state.stage;- const routeKey = `${state.status}:${stageKey}:${copy.route ?? ""}`;- if (copy.route && pathname === copy.route) routedGuideRef.current = routeKey;- if (- copy.route &&- shouldAutoRouteGuide(copy.route, pathname, routeKey, routedGuideRef.current)- ) {- routedGuideRef.current = routeKey;- router.replace(copy.route);- return;- }- if (copy.route && pathname !== copy.route) {- return;- }-- const abortController = new AbortController();- let target: HTMLElement | null = null;- let instance: Driver | null = null;- let avatarContainer: HTMLElement | null = null;- let handleTargetClick: (() => void) | null = null;-- void (async () => {- while (!abortController.signal.aborted && !target) {- const candidate = await waitForTarget(copy.target, 2000, abortController.signal);- if (!candidate || abortController.signal.aborted) continue;- candidate.scrollIntoView({ behavior: "auto", block: "nearest", inline: "nearest" });- await nextFrame();- await nextFrame();- if (isGuideTargetUsable(candidate) && targetIsInViewport(candidate)) target = candidate;- }- if (abortController.signal.aborted || !target) return;- const popoverSide = guidePopoverSide(copy.target);- instance = driver({- animate: !window.matchMedia("(prefers-reduced-motion: reduce)").matches,- allowClose: false,- overlayClickBehavior: () => undefined,- overlayColor: "var(--community-onboarding-overlay)",- overlayOpacity: 0.46,- stagePadding: 8,- stageRadius: 12,- disableActiveInteraction: false,- showButtons: [],- popoverClass: `community-onboarding-popover community-onboarding-popover-${popoverSide}`,- onPopoverRender: (popover) => {- popover.description.replaceChildren();- setPopoverContainer(popover.description);- },- });- driverRef.current = instance;- instance.highlight({- element: target,- popover: {- description: "Loading",- side: popoverSide,- align: "center",- },- });- avatarContainer = document.createElement("div");- avatarContainer.className = "community-onboarding-focus-avatar";- document.body.appendChild(avatarContainer);- targetAvatarRef.current = avatarContainer;- positionFocusAvatar(avatarContainer, target, popoverSide);- setTargetAvatarContainer(avatarContainer);- document.body.classList.add("community-onboarding-active");- if (dismissGuideOnTargetClick(copy.target)) {- handleTargetClick = () => {- destroyGuide();- };- target.addEventListener("click", handleTargetClick, { once: true });- }- })();-- return () => {- abortController.abort();- if (handleTargetClick) target?.removeEventListener("click", handleTargetClick);- if (driverRef.current === instance) driverRef.current = null;- if (targetAvatarRef.current === avatarContainer) targetAvatarRef.current = null;- avatarContainer?.remove();- instance?.destroy();- document.body.classList.remove("community-onboarding-active");- setTargetAvatarContainer(null);- instance = null;- };- }, [copy, destroyGuide, pathname, router, state]);-- if (!copy || !state) return null;- return (- <>- {popoverContainer- ? createPortal(- <GuideCard- copy={copy}- onSkip={() => {- destroyGuide();- skipCommunityOnboarding();- }}- />,- popoverContainer,- )- : null}- {targetAvatarContainer- ? createPortal(- <GeneratedAvatar- seed={state.guideAvatarSeed ?? "alook-guide"}- size={28}- className="rounded-full ring-2 ring-background shadow-md"- />,- targetAvatarContainer,- )- : null}- </>- );+ const controller = useCommunityOnboardingGuideController();+ return renderCommunityOnboardingGuide(controller);}diff --git a/src/web/src/components/community/category-settings-dialog.tsx b/src/web/src/components/community/settings/category-settings-dialog.tsxsimilarity index 96%rename from src/web/src/components/community/category-settings-dialog.tsxrename to src/web/src/components/community/settings/category-settings-dialog.tsxindex 30b9a92f4..fe4c82177 100644--- a/src/web/src/components/community/category-settings-dialog.tsx+++ b/src/web/src/components/community/settings/category-settings-dialog.tsx@@ -4,7 +4,7 @@ import { useState } from "react"import { Button } from "@/components/ui/button"import { onEnterSubmit } from "@/lib/ime"import { CreateDialogShell } from "./create-dialog-shell"-import { PrivateCategoryRow } from "./private-category-row"+import { PrivateCategoryRow } from "../members/private-category-row"// Category settings dialog — rename only. Privacy (public/private) is fixed at// creation and can't be changed here: flipping it would silently widen/tightendiff --git a/src/web/src/components/community/create-category-dialog.tsx b/src/web/src/components/community/settings/create-category-dialog.tsxsimilarity index 96%rename from src/web/src/components/community/create-category-dialog.tsxrename to src/web/src/components/community/settings/create-category-dialog.tsxindex 2f6e8fe9e..3d6e41a60 100644--- a/src/web/src/components/community/create-category-dialog.tsx+++ b/src/web/src/components/community/settings/create-category-dialog.tsx@@ -4,7 +4,7 @@ import { useState } from "react"import { Button } from "@/components/ui/button"import { onEnterSubmit } from "@/lib/ime"import { CreateDialogShell } from "./create-dialog-shell"-import { PrivateCategoryRow } from "./private-category-row"+import { PrivateCategoryRow } from "../members/private-category-row"// Create Category dialog — name + private toggle (defaults to public). In a// private category any member can create a channel, but each channel is visiblediff --git a/src/web/src/components/community/create-channel-dialog.tsx b/src/web/src/components/community/settings/create-channel-dialog.tsxsimilarity index 98%rename from src/web/src/components/community/create-channel-dialog.tsxrename to src/web/src/components/community/settings/create-channel-dialog.tsxindex 4b2323592..2a1984107 100644--- a/src/web/src/components/community/create-channel-dialog.tsx+++ b/src/web/src/components/community/settings/create-channel-dialog.tsx@@ -2,7 +2,7 @@import { useState } from "react"import { Check } from "lucide-react"-import { EntityIcon } from "./entity-icon"+import { EntityIcon } from "../entity-icon"import { CreateDialogShell } from "./create-dialog-shell"import { Button } from "@/components/ui/button"import { tid } from "@/lib/community/testids"diff --git a/src/web/src/components/community/create-dialog-shell.tsx b/src/web/src/components/community/settings/create-dialog-shell.tsxsimilarity index 100%rename from src/web/src/components/community/create-dialog-shell.tsxrename to src/web/src/components/community/settings/create-dialog-shell.tsxdiff --git a/src/web/src/components/community/create-server-dialog.tsx b/src/web/src/components/community/settings/create-server-dialog.tsxsimilarity index 99%rename from src/web/src/components/community/create-server-dialog.tsxrename to src/web/src/components/community/settings/create-server-dialog.tsxindex 67b97ae0b..676627041 100644--- a/src/web/src/components/community/create-server-dialog.tsx+++ b/src/web/src/components/community/settings/create-server-dialog.tsx@@ -10,7 +10,7 @@ import { validateIconSourceFile } from "@/lib/community/image-crop"import { previewSlug } from "@/lib/community/slug-preview"import { tid } from "@/lib/community/testids"import { CreateDialogShell } from "./create-dialog-shell"-import { ImageCropDialog } from "./image-crop-dialog"+import { ImageCropDialog } from "../image-crop-dialog"import { SlugHint } from "./slug-hint"const REDUCED_MOTION_QUERY = "(prefers-reduced-motion: reduce)"diff --git a/src/web/src/components/community/field.tsx b/src/web/src/components/community/settings/field.tsxsimilarity index 100%rename from src/web/src/components/community/field.tsxrename to src/web/src/components/community/settings/field.tsxdiff --git a/src/web/src/components/community/server-audit-removal.contract.test.ts b/src/web/src/components/community/settings/server-audit-removal.contract.test.tssimilarity index 82%rename from src/web/src/components/community/server-audit-removal.contract.test.tsrename to src/web/src/components/community/settings/server-audit-removal.contract.test.tsindex 017f755b8..10592746e 100644--- a/src/web/src/components/community/server-audit-removal.contract.test.ts+++ b/src/web/src/components/community/settings/server-audit-removal.contract.test.ts@@ -4,7 +4,7 @@ import { fileURLToPath } from "node:url"import { describe, expect, it } from "vitest"const componentDirectory = dirname(fileURLToPath(import.meta.url))-const webRoot = resolve(componentDirectory, "../../..")+const webRoot = resolve(componentDirectory, "../../../..")const repositoryRoot = resolve(webRoot, "../..")const readWeb = (path: string) => readFileSync(resolve(webRoot, path), "utf8")@@ -12,9 +12,9 @@ const readRepository = (path: string) => readFileSync(resolve(repositoryRoot, padescribe("server audit removal contract", () => {it("removes the server settings surface and client query", () => {- expect(readWeb("src/components/community/server-settings.tsx")).not.toContain("Audit Log")- expect(readWeb("src/components/community/channel-sidebar.tsx")).not.toContain("Audit Log")- expect(readWeb("src/components/community/_types.ts")).not.toContain('| "audit"')+ expect(readWeb("src/components/community/settings/server-settings.tsx")).not.toContain("Audit Log")+ expect(readWeb("src/components/community/channels/channel-sidebar.tsx")).not.toContain("Audit Log")+ expect(readWeb("src/components/community/settings/settings-types.ts")).not.toContain('| "audit"')expect(readWeb("src/hooks/community/use-server-panels.ts")).not.toContain("useAuditLog")expect(readWeb("src/lib/query-keys.ts")).not.toContain("auditLog:")})diff --git a/src/web/src/components/community/server-settings.tsx b/src/web/src/components/community/settings/server-settings.tsxsimilarity index 97%rename from src/web/src/components/community/server-settings.tsxrename to src/web/src/components/community/settings/server-settings.tsxindex e1412ea67..9caa8b883 100644--- a/src/web/src/components/community/server-settings.tsx+++ b/src/web/src/components/community/settings/server-settings.tsx@@ -4,26 +4,32 @@ import { useEffect, useRef, useState } from "react"import type { LucideIcon } from "lucide-react"import { useVirtualizer } from "@tanstack/react-virtual"import { Settings, Users, Link2, Bell, Trash2, X, Shield, Search, Camera } from "lucide-react"-import { NOTIF_LEVELS, notifLevelDisplay } from "@alook/shared"+import {+ isServerOwner,+ NOTIF_LEVELS,+ notifLevelDisplay,+ type CommunityRole as Role,+} from "@alook/shared"import { ConfirmDialog } from "@/components/ui/confirm-dialog"import { Button } from "@/components/ui/button"-import { formatRelativeTime } from "./format-time"+import { formatRelativeTime } from "@/lib/community/format-time"import { Input } from "@/components/ui/input"import { AutoResizeTextarea } from "@/components/ui/auto-resize-textarea"import { Badge, badgeVariants } from "@/components/ui/badge"import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"import { Skeleton } from "@/components/ui/skeleton"-import { Avatar } from "./avatar"-import { ServerIcon } from "./server-icon"+import { Avatar } from "../avatar"+import { ServerIcon } from "../server-icon"import { avatarInitial } from "@/lib/community/avatar"import { SlugHint } from "./slug-hint"import { previewSlug } from "@/lib/community/slug-preview"import { tid } from "@/lib/community/testids"import { useInvites } from "@/hooks/community/use-server-panels"import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS } from "@/hooks/community/virtualizer-react-options"-import type { SettingsSection, Member, Role, InviteRow, OpenProfile } from "./_types"-import { isServerOwner } from "./_types"+import type { SettingsSection } from "@/components/community/settings/settings-types"+import type { Member, InviteRow } from "@/lib/community/models/people"+import type { OpenProfile } from "@/components/community/social/profile-types"import {SETTINGS_NAV_CLASS,SETTINGS_NAV_LABEL_CLASS,diff --git a/src/web/src/components/community/settings-navigation.test.ts b/src/web/src/components/community/settings/settings-navigation.test.tssimilarity index 100%rename from src/web/src/components/community/settings-navigation.test.tsrename to src/web/src/components/community/settings/settings-navigation.test.tsdiff --git a/src/web/src/components/community/settings-navigation.ts b/src/web/src/components/community/settings/settings-navigation.tssimilarity index 100%rename from src/web/src/components/community/settings-navigation.tsrename to src/web/src/components/community/settings/settings-navigation.tsdiff --git a/src/web/src/components/community/settings/settings-types.ts b/src/web/src/components/community/settings/settings-types.tsnew file mode 100644index 000000000..7ff0876a8--- /dev/null+++ b/src/web/src/components/community/settings/settings-types.ts@@ -0,0 +1,5 @@+export type SettingsSection =+ | "overview"+ | "members"+ | "invites"+ | "notifications"diff --git a/src/web/src/components/community/slug-hint.test.ts b/src/web/src/components/community/settings/slug-hint.test.tssimilarity index 100%rename from src/web/src/components/community/slug-hint.test.tsrename to src/web/src/components/community/settings/slug-hint.test.tsdiff --git a/src/web/src/components/community/slug-hint.tsx b/src/web/src/components/community/settings/slug-hint.tsxsimilarity index 100%rename from src/web/src/components/community/slug-hint.tsxrename to src/web/src/components/community/settings/slug-hint.tsxdiff --git a/src/web/src/components/community/edit-profile-dialog.tsx b/src/web/src/components/community/settings/user-settings.tsxsimilarity index 99%rename from src/web/src/components/community/edit-profile-dialog.tsxrename to src/web/src/components/community/settings/user-settings.tsxindex 12d77eb1d..5379e4a73 100644--- a/src/web/src/components/community/edit-profile-dialog.tsx+++ b/src/web/src/components/community/settings/user-settings.tsx@@ -11,9 +11,9 @@ import { Separator } from "@/components/ui/separator"import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"import { ConfirmDialog } from "@/components/ui/confirm-dialog"import { clearPersistedCache } from "@/lib/query-persister"-import { Avatar } from "./avatar"+import { Avatar } from "../avatar"import { Field } from "./field"-import { StatusEditor, hasStatus } from "./status-editor"+import { StatusEditor, hasStatus } from "../social/status-editor"import {SETTINGS_LOGOUT_CLASS,SETTINGS_NAV_CLASS,diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsxdeleted file mode 100644index c6c1e4247..000000000--- a/src/web/src/components/community/shell-frame.tsx+++ /dev/null@@ -1,870 +0,0 @@-"use client"--import {- useCallback,- useEffect,- useMemo,- useRef,- useState,- type ReactNode,-} from "react"-import { usePathname, useRouter } from "next/navigation"-import { useQueryClient } from "@tanstack/react-query"-import { toast } from "sonner"-import { toastApiError } from "@/lib/api/client"-import { communityKeys } from "@/lib/query-keys"-import { markSwitch } from "@/lib/perf/switch-mark"-import { userProfileQueryFn, PROFILE_STALE_TIME_MS } from "@/hooks/community/use-user-profile"-import { useDefaultLayout } from "react-resizable-panels"-import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@/components/ui/resizable"-import { AppSurface } from "@/components/ui/app-surface"-import { Dialog, DialogContent } from "@/components/ui/dialog"-import { useBreakpoint } from "@/hooks/use-mobile"-import { Shell } from "./shell"-import {- COMMUNITY_RAIL_WIDTH,- 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"-import { UserSettings } from "./edit-profile-dialog"-import { ProfileCard } from "./profile-card"-import { ImageLightbox } from "./image-lightbox"-import { AttachmentPreviewSheet } from "./attachment-preview-sheet"-import { ImageCropDialog } from "./image-crop-dialog"-import { validateIconSourceFile } from "@/lib/community/image-crop"-import type { FileAttachment, ImagePreview, Marked, MobileZone, Profile, View } from "./_types"-import {- resolveProfileContextLabel,- resolveProfileServerId,- resolveProfileTarget,- resolveProfileUserId,- buildSelfProfile,-} from "./profile-lookup"-import { resolveProfilePresence } from "@/lib/community/presence"-import { avatarInitial } from "@/lib/community/avatar"-import { signOut } from "@/lib/auth-client"-import { clearPersistedCache } from "@/lib/query-persister"-import { useCommunityStore } from "@/stores/community"-import { useCommunityWsStore, useOnlineUserIds } from "@/stores/community/ws"-import { useMessageStreamStore } from "@/stores/community/message-stream"-import { useCurrentUser, useSetCurrentUser } from "@/contexts/community/current-user"-import { serverQueryFn, useServers, type ServerDetail } from "@/hooks/community/use-servers"-import { useFolders } from "@/hooks/community/use-folders"-import { useFriends } from "@/hooks/community/use-friends"-import { useServerMembers } from "@/hooks/community/use-server-members"-import { useInboxUnreads, useInboxMentions, useInboxMarked } from "@/hooks/community/use-inbox"-import { useInboxAutoCollapse } from "@/hooks/community/use-inbox-auto-collapse"-import { useCommunityOnboarding } from "@/lib/community-onboarding"-import {- useCreateServer,- useLeaveServer,- useUploadServerIcon,- useDeleteServerFolder,- useReorderServers,- useReorderFolders,- useUpdateFolderItems,- useCreateServerFolderWith,- useCreateOrGetDm,- useMarkAllInboxRead,- useDeleteMention,- useUnmarkMessage,- useUpdateProfile,- useReadForumThreadFromInbox,- useUploadUserAvatar,-} from "@/hooks/community/mutations"-import { useDmMessageSender } from "@/hooks/community/use-dm-message-sender"-import { getLastChannel, pickServerLandingHref } from "@/lib/community/last-channel"-import { getLastMeLeaf, pickMeLandingLocation } from "@/lib/community/last-me-location"-import {- commitLatestNavigationIntent,- createNavigationIntentGate,- supersedeNavigationIntent,-} from "@/lib/community/navigation-intent"--/**- * Shared community shell — ServerRail on the left, sidebar column with the- * caller's own nav, main content on the right, floating UserBar, plus the- * mobile zone switch, ProfileCard, ImageLightbox, and the user-settings- * dialog. Layouts wire their own sidebar and per-view state on top of this;- * server-scoped dialogs (server settings) are slotted through `extraDialogs`.- *- * Mobile zone is owned by the caller so sidebar pick callbacks can flip to- * "messages" without threading a ref through props. Layouts wire it to- * `useCommunityStore.uiHandlers.goBackMobile` (registered on mount here) so- * pages can swing back to nav without prop drilling.- */-export function ShellFrame({- view,- activeServerId,- mobileZone,- setMobileZone,- sidebar,- children,- extraDialogs,- onOpenActiveServerSettings,- onOpenActiveServerInvite,- goHome,- goServer,-}: {- view: View- activeServerId: string | undefined- mobileZone: MobileZone- setMobileZone: (z: MobileZone) => void- sidebar: (opts?: { noHeader?: boolean }) => ReactNode- children: ReactNode- extraDialogs?: ReactNode- onOpenActiveServerSettings?: () => void- onOpenActiveServerInvite?: () => void- goHome: () => void- goServer: () => void-}) {- const router = useRouter()- const pathname = usePathname()- const bp = useBreakpoint()- const queryClient = useQueryClient()- const currentUser = useCurrentUser()- const setCurrentUser = useSetCurrentUser()- const onlineUserIds = useOnlineUserIds()- const onboardingState = useCommunityOnboarding()-- useEffect(() => {- if (onboardingState?.status === "active") {- setMobileZone(onboardingState.stage === "server" ? "nav" : "messages")- }- }, [onboardingState, setMobileZone])-- // Server list + folders drive the rail. Members + friends feed the profile- // popover's mutual-server count when the user opens a member card.- const serversQuery = useServers()- const { servers } = serversQuery- const { folders } = useFolders()- const { friends } = useFriends()- const currentServerId = useCommunityStore((s) => s.currentServerId)- const profileServerId = resolveProfileServerId(view, activeServerId)- const membersHook = useServerMembers(profileServerId)- const members = membersHook.members-- // Inbox pair — the shell reads both to drive the bell badge.- const inboxUnreads = useInboxUnreads()- const inboxMentions = useInboxMentions()- const unreadFeed = inboxUnreads.servers- const unreadDms = inboxUnreads.dms- const mentions = inboxMentions.mentions- const inboxLoading = inboxUnreads.isLoading || inboxMentions.isLoading- // Marked feed is lazy: it has no bell badge, so it only fetches once the- // viewer opens the Marked tab. `markedTabOpened` latches true on first open- // (the query then lives normally under communityKeys.inboxMarked()).- const [markedTabOpened, setMarkedTabOpened] = useState(false)- const inboxMarked = useInboxMarked(markedTabOpened)- const marked = inboxMarked.marked- const { mutate: unmarkMessageMutate } = useUnmarkMessage()- // Popover open-state + auto-collapse: the inbox closes itself once the row- // the viewer clicked leaves the list. See use-inbox-auto-collapse.- const inbox = useInboxAutoCollapse({ unreads: unreadFeed, unreadDms, mentions })- const watchInboxItem = inbox.watchItem-- // Mutations wired through the shell.- // Destructure the STABLE mutation methods, not the whole mutation object.- // TanStack's `useMutation` returns a fresh wrapper object every render but- // binds `.mutate`/`.mutateAsync` stably; depending on the wrapper made every- // rail callback below rebuild each render, busting ServerRail's memo and- // re-rendering the whole shell (children included) on any shell re-render.- // Mirrors the message-side fix (see page.tsx messageActions deps note).- const { mutateAsync: createServerAsync } = useCreateServer()- const { mutate: leaveServerMutate } = useLeaveServer()- const { mutate: uploadServerIconMutate } = useUploadServerIcon()- const { mutate: deleteFolderMutate } = useDeleteServerFolder()- const { mutate: reorderServersMutate } = useReorderServers()- const { mutate: reorderFoldersMutate } = useReorderFolders()- const { mutate: updateFolderItemsMutate } = useUpdateFolderItems()- const { mutate: createFolderWithMutate } = useCreateServerFolderWith()- const createOrGetDm = useCreateOrGetDm()- const { accept: acceptDmMessage } = useDmMessageSender()- const markAllInboxRead = useMarkAllInboxRead()- const deleteMention = useDeleteMention()- const { mutate: readForumThreadFromInbox } = useReadForumThreadFromInbox()- const updateProfile = useUpdateProfile()- const uploadUserAvatar = useUploadUserAvatar()-- const [editingProfile, setEditingProfile] = useState(false)- const [profile, setProfile] = useState<{- data: Profile- x: number- y: number- // First-paint seed for the status pill — used only until `userStatuses`- // has an overlay entry for this user. See profile-card.tsx for the merge- // rule (overlay wins, seed is fallback).- initialStatusEmoji: string | null- initialStatusText: string | null- } | null>(null)- const [preview, setPreview] = useState<ImagePreview | null>(null)- const [attachmentPreview, setAttachmentPreview] = useState<FileAttachment | null>(null)- const [pendingAvatarCrop, setPendingAvatarCrop] = useState<{ src: string; fileName: string } | null>(null)-- // Rail wiring — universal, since navigation is URL-driven and doesn't- // depend on the current view.- const folderServerIds = useMemo(() => {- const s = new Set<string>()- for (const f of folders) for (const srv of f.servers) s.add(srv.id)- return s- }, [folders])- const railServers = useMemo(- () =>- servers- .filter((s) => !folderServerIds.has(s.id))- .map((s) => ({ ...s, active: s.id === activeServerId })),- [servers, activeServerId, folderServerIds],- )-- const serverNavigationGateRef = useRef(createNavigationIntentGate())- const cancelPendingServerNavigation = useCallback(() => {- supersedeNavigationIntent(serverNavigationGateRef.current)- }, [])- useEffect(() => {- cancelPendingServerNavigation()- }, [cancelPendingServerNavigation, pathname])-- const serverDestination = useCallback((id: string) => {- const detail = queryClient.getQueryData<ServerDetail>(communityKeys.server(id))- const channelIds = detail?.categories.flatMap((category) =>- category.channels.filter((channel) => !channel.pending).map((channel) => channel.id)- ) ?? []- return pickServerLandingHref(id, channelIds, getLastChannel(id))- }, [queryClient])- const resolveServerDestination = useCallback(async (id: string) => {- const root = `/c/channels/${id}`- const immediate = serverDestination(id)- if (immediate !== root) return immediate- try {- await queryClient.fetchQuery({- queryKey: communityKeys.server(id),- queryFn: serverQueryFn(id),- staleTime: Infinity,- })- } catch {- return root- }- return serverDestination(id)- }, [queryClient, serverDestination])- const onRailServerNavigate = useCallback(- (id: string) => {- markSwitch("server", id)- void commitLatestNavigationIntent(- serverNavigationGateRef.current,- () => resolveServerDestination(id),- (destination) => router.push(destination),- )- },- [resolveServerDestination, router],- )- const onRailHomeNavigate = useCallback(() => {- cancelPendingServerNavigation()- goHome()- }, [cancelPendingServerNavigation, goHome])- const onRailServerPrefetch = useCallback((id: string) => {- void resolveServerDestination(id).then((destination) => router.prefetch(destination))- }, [resolveServerDestination, router])- const onRailHomePrefetch = useCallback(- () => router.prefetch(pickMeLandingLocation(getLastMeLeaf())),- [router],- )- const onRailCreateServer = useCallback(- async (name: string, icon?: File) => {- try {- const data = await createServerAsync({ name })- const newId = data.server.id- toast(`Server "${name}" created`)- if (icon) {- uploadServerIconMutate(- { serverId: newId, file: icon },- { onError: (e) => toastApiError(e, "Server created, but the icon failed to upload") },- )- }- cancelPendingServerNavigation()- router.push(`/c/channels/${newId}`)- } catch (e) {- toastApiError(e, "Failed to create server")- }- },- [cancelPendingServerNavigation, createServerAsync, uploadServerIconMutate, router],- )- const onRailLeaveServer = useCallback(- (id: string) => {- // Mark BEFORE mutate — the WS `member.leave` fanout / servers-list- // refetch can race the mutation callback and reach the layout's- // eject effect first. Marker present → layout stays silent and- // this button owns the "Left server" toast.- markVoluntaryLeave(id)- leaveServerMutate(- { serverId: id },- {- onSuccess: () => {- toast("Left server")- if (currentServerId === id) {- cancelPendingServerNavigation()- router.replace(pickPostEjectDestination(servers, id))- }- },- onError: (e) => toastApiError(e, "Failed to leave server"),- },- )- },- [cancelPendingServerNavigation, leaveServerMutate, currentServerId, router, servers],- )- const onRailOpenSettings = useCallback(- (id?: string) => {- if (!id) return- cancelPendingServerNavigation()- const action = resolveServerRailOverlayAction({- targetServerId: id,- activeServerId,- overlay: "settings",- hasActiveOpener: !!onOpenActiveServerSettings,- })- if (action.kind === "open-active") onOpenActiveServerSettings?.()- else router.push(action.href)- },- [activeServerId, cancelPendingServerNavigation, onOpenActiveServerSettings, router],- )- const onRailOpenInvitePopover = useCallback(- (id?: string) => {- if (!id) return- cancelPendingServerNavigation()- const action = resolveServerRailOverlayAction({- targetServerId: id,- activeServerId,- overlay: "invite",- hasActiveOpener: !!onOpenActiveServerInvite,- })- if (action.kind === "open-active") onOpenActiveServerInvite?.()- else router.push(action.href)- },- [activeServerId, cancelPendingServerNavigation, onOpenActiveServerInvite, router],- )- const onRailUngroupFolder = useCallback(- (fId: string) => {- deleteFolderMutate(- { folderId: fId },- {- onSuccess: () => toast("Group removed"),- onError: (e) => toastApiError(e, "Failed to remove group"),- },- )- },- [deleteFolderMutate],- )- const onRailReorderRail = useCallback(- (ids: string[]) => {- reorderServersMutate(- { serverIds: ids },- { onError: (e) => toastApiError(e, "Failed to save server order") },- )- },- [reorderServersMutate],- )- const onRailReorderFolders = useCallback(- (ids: string[]) => {- reorderFoldersMutate(- { folderIds: ids },- { onError: (e) => toastApiError(e, "Failed to reorder groups") },- )- },- [reorderFoldersMutate],- )- const onRailFolderItemsChange = useCallback(- (fId: string, ids: string[]) => {- updateFolderItemsMutate(- { folderId: fId, serverIds: ids },- { onError: (e) => toastApiError(e, "Failed to update group") },- )- },- [updateFolderItemsMutate],- )- const onRailDragCreateFolder = useCallback(- (a: string, b: string) => {- createFolderWithMutate(- { serverIdA: a, serverIdB: b },- { onError: (e) => toastApiError(e, "Failed to create group") },- )- },- [createFolderWithMutate],- )-- const railProps = {- servers: railServers,- folders,- activeServerId,- serversLoading: serversQuery.isLoading,- setMobileZone,- view,- onHome: onRailHomeNavigate,- onHomePrefetch: onRailHomePrefetch,- onServer: goServer,- onServerNavigate: onRailServerNavigate,- onServerPrefetch: onRailServerPrefetch,- onCreateServer: onRailCreateServer,- onLeaveServer: onRailLeaveServer,- onOpenSettings: onRailOpenSettings,- onOpenInvitePopover: onRailOpenInvitePopover,- onUngroupFolder: onRailUngroupFolder,- onReorderRail: onRailReorderRail,- onReorderFolders: onRailReorderFolders,- onFolderItemsChange: onRailFolderItemsChange,- onDragCreateFolder: onRailDragCreateFolder,- }-- // ProfileCard — resolves the target user from members / friends and- // enriches with the profile API. Registered with the community store so- // pages can trigger this from anywhere via `useCommunityStore.uiHandlers`.- const openProfile = useCallback(- (name: string, e: React.MouseEvent, discriminator?: string, targetUserId?: string) => {- const isSelf = !!targetUserId && targetUserId === currentUser.id- if (isSelf) {- const selfMember = profileServerId- ? members.find((member) => member.userId === currentUser.id)- : undefined- setProfile({- data: buildSelfProfile(- currentUser,- onlineUserIds,- resolveProfileContextLabel(profileServerId, selfMember),- ),- x: e.clientX,- y: e.clientY,- initialStatusEmoji: currentUser.statusEmoji ?? null,- initialStatusText: currentUser.statusText ?? null,- })- return- }- const member = resolveProfileTarget(members, friends, { name, discriminator, userId: targetUserId })- const about = member?.sub ?? ""- // Hoisted above `data` (was previously computed after `setProfile`,- // only for the async fetch below) so the same value can also feed- // `resolveProfilePresence`.- const userId = resolveProfileUserId(member, targetUserId)- const data: Profile = {- name,- userId,- // discriminator is undefined until the /profile fetch below hydrates it.- avatar: member?.avatar ?? avatarInitial(name),- contextLabel: resolveProfileContextLabel(profileServerId, member),- about,- mutual: 0,- presence: resolveProfilePresence(false, userId, onlineUserIds),- }- setProfile({- data,- x: e.clientX,- y: e.clientY,- initialStatusEmoji: member?.statusEmoji ?? null,- initialStatusText: member?.statusText ?? null,- })- if (userId) {- // Cached under `communityKeys.profile(userId)` — a re-click on the- // same person within `PROFILE_STALE_TIME_MS` resolves from memory- // instead of re-hitting the network (see plans/profile-card-memory-cache.md).- queryClient- .fetchQuery({- queryKey: communityKeys.profile(userId),- queryFn: userProfileQueryFn(userId),- staleTime: PROFILE_STALE_TIME_MS,- })- .then((p) => {- // Refresh THIS card's seed only — never write to the WS overlay- // from a REST snapshot. `communityKeys.profile(userId)` is cached- // for 5 min, so a re-open can resolve from stale cache; the WS- // overlay is meant to be the freshest source (community:status.update- // events keep it live). Writing REST → overlay would let a stale- // cache clobber a live WS value, and every other consumer- // (member list, friends list, UserBar) that subscribes to the- // overlay would visibly regress. Overlay stays write-only from- // the WS handler + self-mutation paths.- // Status fields are assigned directly (no `??` fallback) — the- // REST route always populates both, and a freshly-cleared status- // must overwrite a stale member-row seed instead of getting- // masked by it.- setProfile((prev) =>- prev- ? {- ...prev,- data: {- ...prev.data,- about: p.aboutMe ?? prev.data.about,- mutual: p.mutualServers ?? 0,- discriminator: p.discriminator ?? prev.data.discriminator,- },- initialStatusEmoji: p.statusEmoji,- initialStatusText: p.statusText,- }- : prev,- )- })- .catch((e) => toastApiError(e, "Failed to load profile"))- }- },- [currentUser, profileServerId, members, friends, queryClient, onlineUserIds],- )-- const previewImage = useCallback((image: ImagePreview) => setPreview(image), [])- const previewAttachment = useCallback((attachment: FileAttachment) => setAttachmentPreview(attachment), [])- const goBackMobile = useCallback(() => setMobileZone("nav"), [setMobileZone])- // Navigate for channel/server-ref pills. They live deep in the memoized- // Streamdown message tree where a subtree `useRouter().push` is a no-op; the- // shell's router is the live one (rail clicks above navigate through it), so- // the pills route through this bridge instead.- const navigate = useCallback(- (serverId: string, channelId?: string) => {- markSwitch(channelId ? "channel" : "server", channelId ?? serverId)- if (channelId) {- cancelPendingServerNavigation()- router.push(`/c/channels/${serverId}/${channelId}`)- return- }- void commitLatestNavigationIntent(- serverNavigationGateRef.current,- () => resolveServerDestination(serverId),- (destination) => router.push(destination),- )- },- [cancelPendingServerNavigation, resolveServerDestination, router],- )- useEffect(() => {- useCommunityStore.getState().registerUiHandlers({- previewImage,- previewAttachment,- openProfile,- goBackMobile,- navigate,- cancelPendingNavigation: cancelPendingServerNavigation,- })- }, [previewImage, previewAttachment, openProfile, goBackMobile, navigate, cancelPendingServerNavigation])-- // Inline self-status save from the `ProfileCard` header (see status-editor.tsx).- // Mirrors `userSettingsDialog`'s onSave status branch exactly — both save- // paths must independently apply the same local WS-store write, since self- // isn't in their own fan-out audience (see plans/profile-card-status-overlay.md).- // The card and every other consumer subscribe to `userStatuses`, so writing- // to the store is enough — no need to mirror the value onto `Profile`.- const updateOwnStatus = async (statusEmoji: string | null, statusText: string | null) => {- try {- await updateProfile.mutateAsync({ statusEmoji, statusText })- setCurrentUser((u) => ({ ...u, statusEmoji, statusText }))- useCommunityWsStore.getState().setUserStatus(currentUser.id, statusEmoji, statusText)- } catch (e) {- toastApiError(e, "Failed to update status")- }- }-- const profileMessage = async (userId: string, text: string) => {- if (!userId) {- toast("Could not find user")- return- }- let dmId: string- try {- const data = await createOrGetDm.mutateAsync({ userId })- dmId = data.conversation.id- } catch (e) {- toastApiError(e, "Failed to open DM")- return- }- const trimmed = text.trim()- if (trimmed) {- const receipt = acceptDmMessage({- dmId,- content: trimmed,- author: {- id: currentUser.id,- name: currentUser.name,- avatar: currentUser.avatar,- },- })- if (!receipt.accepted) {- toast("Failed to send message")- return- }- void receipt.committed- }- cancelPendingServerNavigation()- router.push(`/c/me/${dmId}`)- }-- const openServerChannel = useCallback(- (sid: string, cid: string, watchKey: string = `channel:${cid}`) => {- // No PUT here — the channel/thread page's `useEagerChannelRead` fires the- // mark-read on mount, AFTER its read-state snapshot latches, so the NEW- // divider still anchors to the pre-open pointer. Navigating is enough.- // `watchKey` lets the caller own what row the inbox watches for removal —- // a mention click passes `mention:<id>` so the mention row (not the- // channel, which may persist to host unread children) drives the collapse.- watchInboxItem(watchKey)- cancelPendingServerNavigation()- router.push(`/c/channels/${sid}/${cid}`)- },- [cancelPendingServerNavigation, router, watchInboxItem],- )-- const openForumThreadFromInbox = useCallback(- (sid: string, parentChannelId: string, childChannelId: string, openerMessageId: string) => {- // Start the parent progressive read first, but never gate opening the- // child on network success. The mutation has no optimistic trim: success- // refreshes Inbox/server aggregates, while failure toasts and leaves the- // opener unread for a later retry.- watchInboxItem(`channel:${childChannelId}`)- readForumThreadFromInbox({ parentChannelId, openerMessageId })- cancelPendingServerNavigation()- router.push(`/c/channels/${sid}/${childChannelId}`)- },- [cancelPendingServerNavigation, readForumThreadFromInbox, router, watchInboxItem],- )-- // A Marked row is cross-channel — clicking one navigates to the message's- // channel AND opens the context sheet on it (Gus: always land on the channel- // so you see WHERE the message lives, then the sheet shows it + its context;- // same feel as a DM row). Both surfaces use the same `?seq=<n>` deep-link the- // destination page reads to open its sheet — server rows go to- // `/c/channels/<s>/<c>`, DM rows to `/c/me/<channelId>` (a DM channel's id IS- // its `/c/me/<id>` route param). serverId (null ⇒ DM) picks the route only.- // `watchInboxItem` collapses the popover once the destination opens.- const openMarked = useCallback(- (mk: Marked) => {- watchInboxItem(`marked:${mk.id}`)- cancelPendingServerNavigation()- const seqQuery = mk.m.seq != null ? `?seq=${mk.m.seq}` : ""- if (mk.serverId) {- router.push(`/c/channels/${mk.serverId}/${mk.channelId}${seqQuery}`)- } else {- router.push(`/c/me/${mk.channelId}${seqQuery}`)- }- },- [cancelPendingServerNavigation, router, watchInboxItem],- )-- const openInboxDm = useCallback(- (dmId: string) => {- // Optimistic clear on `communityKeys.dms()` so the sidebar updates- // instantly. The real mark-read is owned by the DM page's- // `useEagerDmRead` on mount (snapshot latches first → NEW divider stays- // anchored), and `useDmWatermark` continues to advance the pointer as- // the viewer scrolls.- queryClient.setQueryData(- communityKeys.dms(),- (prev: { conversations: { id: string; unread?: boolean }[] } | undefined) =>- prev- ? { ...prev, conversations: prev.conversations.map((d) => (d.id === dmId ? { ...d, unread: false } : d)) }- : prev,- )- watchInboxItem(`dm:${dmId}`)- cancelPendingServerNavigation()- router.push(`/c/me/${dmId}`)- },- [cancelPendingServerNavigation, router, queryClient, watchInboxItem],- )-- const inboxElement = (- <InboxPopover- unreads={unreadFeed}- unreadDms={unreadDms}- mentions={mentions}- marked={marked}- markedLoading={inboxMarked.isLoading}- loading={inboxLoading}- onOpenChannel={openServerChannel}- onOpenForumThread={openForumThreadFromInbox}- onOpenDm={openInboxDm}- onOpenMention={(mention) => {- if (mention.serverId && mention.channelId) openServerChannel(mention.serverId, mention.channelId, `mention:${mention.id}`)- }}- onOpenMarked={openMarked}- onMarkedTabSelected={() => setMarkedTabOpened(true)}- onMarkAllRead={() => { markAllInboxRead.mutate() }}- onDeleteMention={(id) => deleteMention.mutate({ mentionId: id })}- onUnmark={(messageId) => unmarkMessageMutate({ messageId })}- />- )- const inboxHasUnread =- (unreadFeed?.length ?? 0) > 0 || (unreadDms?.length ?? 0) > 0 || (mentions?.length ?? 0) > 0-- const userSettingsDialog = (- <Dialog open={editingProfile} onOpenChange={(o) => { if (!o) setEditingProfile(false) }}>- <DialogContent className="flex h-[calc(100vh-4rem)] max-h-180 w-[calc(100vw-4rem)] sm:max-w-4xl flex-col gap-0 overflow-hidden rounded-xl p-0" showCloseButton={false}>- <UserSettings- onClose={() => setEditingProfile(false)}- userId={currentUser.id}- userName={currentUser.name}- aboutMe={currentUser.aboutMe ?? ""}- avatar={currentUser.avatar}- statusEmoji={currentUser.statusEmoji}- statusText={currentUser.statusText}- onUploadAvatar={() => {- const input = document.createElement("input")- input.type = "file"- input.accept = "image/png,image/jpeg,image/webp"- input.onchange = () => {- const f = input.files?.[0]- if (!f) return- const check = validateIconSourceFile(f)- if (!check.ok) {- toast(check.error)- return- }- setPendingAvatarCrop({ src: URL.createObjectURL(f), fileName: f.name })- }- input.click()- }}- onSave={async (data) => {- try {- await updateProfile.mutateAsync(data)- setCurrentUser((u) => ({- ...u,- ...(data.name ? { name: data.name } : {}),- ...(data.aboutMe !== undefined ? { aboutMe: data.aboutMe } : {}),- ...(data.statusEmoji !== undefined ? { statusEmoji: data.statusEmoji } : {}),- ...(data.statusText !== undefined ? { statusText: data.statusText } : {}),- }))- // Self is not in their own WS fan-out audience (co-members/friends- // means *other* people) — apply the same store write locally so- // the viewer's own rows (member list, UserBar) update immediately.- if (data.statusEmoji !== undefined || data.statusText !== undefined) {- useCommunityWsStore.getState().setUserStatus(- currentUser.id,- data.statusEmoji ?? null,- data.statusText ?? null,- )- }- } catch (e) { toastApiError(e, "Failed to save profile") }- }}- onLogout={async () => {- cancelPendingServerNavigation()- // Clear community-local state (timers, subscription, presence)- // before the auth cookie clears so no orphan timers fire after- // the user is gone. `useCommunityStore.reset()` also flushes any- // pending mark-reads so the last-read pointer isn't stranded in- // the debounce window — covers every sign-out path uniformly.- useCommunityStore.getState().reset()- useCommunityWsStore.getState().reset()- useMessageStreamStore.getState().resetAll()- // Drop the persisted IDB blob so the next user on this machine- // doesn't see the previous session's cached message rows.- await clearPersistedCache(currentUser.id).catch(() => { })- await signOut()- router.push("/sign-in")- }}- />- </DialogContent>- </Dialog>- )-- const avatarCropDialog = pendingAvatarCrop && (- <ImageCropDialog- imageSrc={pendingAvatarCrop.src}- originalFileName={pendingAvatarCrop.fileName}- maskShape="circle"- onCropped={(file) => {- uploadUserAvatar.mutate({ file }, {- onSuccess: (data) => {- setCurrentUser((u) => ({ ...u, avatar: `${data.url}?t=${Date.now()}` }))- toast("Avatar updated")- },- onError: (e) => toastApiError(e, "Failed to upload avatar"),- })- URL.revokeObjectURL(pendingAvatarCrop.src)- setPendingAvatarCrop(null)- }}- onCancel={() => {- URL.revokeObjectURL(pendingAvatarCrop.src)- setPendingAvatarCrop(null)- }}- />- )-- // `ShellFrame` mounts separately in `channels/layout.tsx` and `me/layout.tsx`- // — navigating server ↔ DMs unmounts one and mounts the other, which would- // otherwise reset the panel to `defaultSize` every time. A single shared- // `id` (not scoped to `view`/`activeServerId`) persists one width across- // both instances, in localStorage, so it also survives full page reloads.- const { defaultLayout, onLayoutChanged } = useDefaultLayout({ id: "community-shell" })- const sidebarPanelRef = useRef<HTMLDivElement>(null)- const [sidebarW, setSidebarW] = useState(240)- useEffect(() => {- const el = sidebarPanelRef.current- if (!el) return- setSidebarW(el.offsetWidth)- const ro = new ResizeObserver(([e]) => setSidebarW(e!.contentRect.width))- ro.observe(el)- return () => ro.disconnect()- }, [bp])-- if (bp === "desktop") {- return (- <Shell onNavigationIntent={cancelPendingServerNavigation}>- <ServerRail {...railProps} bottomInset={60} />- <div className="relative flex-1 flex flex-col min-w-0 pt-2">- <AppSurface className="rounded-tl-xl rounded-tr-none rounded-br-none rounded-bl-none ring-0 border-l border-t border-border/40 shadow-none">- <ResizablePanelGroup- id="community-shell"- orientation="horizontal"- className="min-h-0 flex-1"- defaultLayout={defaultLayout}- onLayoutChanged={onLayoutChanged}- >- <ResizablePanel id="sidebar" defaultSize="24%" minSize={160} maxSize={360} className="flex flex-col pb-14 bg-sidebar">- <div ref={sidebarPanelRef} className="flex min-h-0 flex-1 flex-col">- {sidebar()}- </div>- </ResizablePanel>- <ResizableHandle className="bg-transparent" />- <ResizablePanel id="main" defaultSize="76%" className="flex min-w-0 flex-col bg-background">- {children}- </ResizablePanel>- </ResizablePanelGroup>- </AppSurface>- <div- className="absolute bottom-0 left-0 z-10"- style={{- width: desktopUserBarOverlayWidth(sidebarW),- marginLeft: -COMMUNITY_RAIL_WIDTH,- }}- >- <UserBar user={{ id: currentUser.id, name: currentUser.name, avatar: currentUser.avatar }} onOpenProfile={openProfile} onEditProfile={() => setEditingProfile(true)} inbox={inboxElement} hasUnread={inboxHasUnread} inboxOpen={inbox.open} onInboxOpenChange={inbox.onOpenChange} />- </div>- </div>- {profile && <ProfileCard key={`${profile.data.userId ?? profile.data.name}:${profile.x}:${profile.y}`} data={profile.data} x={profile.x} y={profile.y} bp={bp} onClose={() => setProfile(null)} onMessage={profileMessage} isSelf={!!profile.data.userId && profile.data.userId === currentUser.id} onUpdateStatus={updateOwnStatus} initialStatusEmoji={profile.initialStatusEmoji} initialStatusText={profile.initialStatusText} />}- {preview && <ImageLightbox image={preview} onClose={() => setPreview(null)} />}- <AttachmentPreviewSheet attachment={attachmentPreview} open={!!attachmentPreview} onOpenChange={(open) => { if (!open) setAttachmentPreview(null) }} />- {userSettingsDialog}- {avatarCropDialog}- {extraDialogs}- </Shell>- )- }-- return (- <Shell onNavigationIntent={cancelPendingServerNavigation}>- {mobileZone === "nav" && (- <>- <ServerRail {...railProps} bottomInset={60} />- <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-sidebar">- <div className="flex min-h-0 min-w-0 flex-1">{sidebar({ noHeader: false })}</div>- <UserBar user={{ id: currentUser.id, name: currentUser.name, avatar: currentUser.avatar }} onOpenProfile={openProfile} onEditProfile={() => setEditingProfile(true)} inbox={inboxElement} hasUnread={inboxHasUnread} inboxOpen={inbox.open} onInboxOpenChange={inbox.onOpenChange} />- </div>- </>- )}- {mobileZone === "messages" && (- <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background">- {children}- </div>- )}- {profile && <ProfileCard key={`${profile.data.userId ?? profile.data.name}:${profile.x}:${profile.y}`} data={profile.data} x={profile.x} y={profile.y} bp={bp} onClose={() => setProfile(null)} onMessage={profileMessage} isSelf={!!profile.data.userId && profile.data.userId === currentUser.id} onUpdateStatus={updateOwnStatus} />}- {preview && <ImageLightbox image={preview} onClose={() => setPreview(null)} />}- <AttachmentPreviewSheet attachment={attachmentPreview} open={!!attachmentPreview} onOpenChange={(open) => { if (!open) setAttachmentPreview(null) }} />- {userSettingsDialog}- {avatarCropDialog}- {extraDialogs}- </Shell>- )-}diff --git a/src/web/src/components/community/animated-alook-logo.test.ts b/src/web/src/components/community/shell/animated-alook-logo.test.tssimilarity index 100%rename from src/web/src/components/community/animated-alook-logo.test.tsrename to src/web/src/components/community/shell/animated-alook-logo.test.tsdiff --git a/src/web/src/components/community/animated-alook-logo.tsx b/src/web/src/components/community/shell/animated-alook-logo.tsxsimilarity index 100%rename from src/web/src/components/community/animated-alook-logo.tsxrename to src/web/src/components/community/shell/animated-alook-logo.tsxdiff --git a/src/web/src/components/community/community-inbox-popover.test.ts b/src/web/src/components/community/shell/community-inbox-popover.test.tssimilarity index 98%rename from src/web/src/components/community/community-inbox-popover.test.tsrename to src/web/src/components/community/shell/community-inbox-popover.test.tsindex 58b6542cf..52e2ab6ca 100644--- a/src/web/src/components/community/community-inbox-popover.test.ts+++ b/src/web/src/components/community/shell/community-inbox-popover.test.ts@@ -2,7 +2,7 @@ import React from "react"import TestRenderer, { act } from "react-test-renderer"import { describe, expect, expectTypeOf, it, vi } from "vitest"import { InboxPopover } from "./community-inbox-popover"-import type { UnreadServer } from "./_types"+import type { UnreadServer } from "@/lib/community/models/inbox"vi.mock("@/components/ui/tabs", () => ({Tabs: ({ children }: { children: React.ReactNode }) => React.createElement("div", null, children),diff --git a/src/web/src/components/community/community-inbox-popover.tsx b/src/web/src/components/community/shell/community-inbox-popover.tsxsimilarity index 97%rename from src/web/src/components/community/community-inbox-popover.tsxrename to src/web/src/components/community/shell/community-inbox-popover.tsxindex 544399d19..d5dd05f30 100644--- a/src/web/src/components/community/community-inbox-popover.tsx+++ b/src/web/src/components/community/shell/community-inbox-popover.tsx@@ -1,14 +1,14 @@import { Bookmark, ChevronRight, Inbox, MoreHorizontal, Trash2 } from "lucide-react"import { stripInlineMarkup } from "@alook/shared"-import { EntityIcon } from "./entity-icon"+import { EntityIcon } from "../entity-icon"import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"import { Skeleton } from "@/components/ui/skeleton"-import { Avatar } from "./avatar"-import { ChannelIcon } from "./channel-icon"-import { EmptyState } from "./empty-state"-import { formatRelativeTime } from "./format-time"-import type { Marked, Mention, UnreadDm, UnreadServer } from "./_types"+import { Avatar } from "../avatar"+import { ChannelIcon } from "../channels/channel-icon"+import { EmptyState } from "../empty-state"+import { formatRelativeTime } from "@/lib/community/format-time"+import type { Marked, Mention, UnreadDm, UnreadServer } from "@/lib/community/models/inbox"import { tid } from "@/lib/community/testids"function MentionBadge({ count }: { count: number }) {diff --git a/src/web/src/components/community/community-panel-sheet.tsx b/src/web/src/components/community/shell/community-panel-sheet.tsxsimilarity index 89%rename from src/web/src/components/community/community-panel-sheet.tsxrename to src/web/src/components/community/shell/community-panel-sheet.tsxindex ab05d2e92..71e5e77bf 100644--- a/src/web/src/components/community/community-panel-sheet.tsx+++ b/src/web/src/components/community/shell/community-panel-sheet.tsx@@ -3,7 +3,12 @@import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet"import { useSheetResize, SheetResizeHandle } from "@/components/ui/sheet-resize-handle"import { RightPanelContent } from "./right-panel"-import type { RightPanel, Member, Role, Msg, Thread, OpenProfile, MemberManageContext } from "./_types"+import type { RightPanel } from "@/components/community/shell/panel-types"+import type { Member } from "@/lib/community/models/people"+import type { CommunityRole as Role } from "@alook/shared"+import type { Msg, Thread } from "@/lib/community/models/message"+import type { OpenProfile } from "@/components/community/social/profile-types"+import type { MemberManageContext } from "@/components/community/members/member-management-types"// Sheet-based right panel for the community channel UI.// Renders the channel's threads / pinned / members / search panel as a non-modal Sheet:diff --git a/src/web/src/components/community/mobile-zone.test.ts b/src/web/src/components/community/shell/mobile-zone.test.tssimilarity index 95%rename from src/web/src/components/community/mobile-zone.test.tsrename to src/web/src/components/community/shell/mobile-zone.test.tsindex 6ebefe392..cb5a27f30 100644--- a/src/web/src/components/community/mobile-zone.test.ts+++ b/src/web/src/components/community/shell/mobile-zone.test.ts@@ -1,6 +1,6 @@import { describe, it, expect } from "vitest"import { initialMobileZone, nextMobileZone } from "./mobile-zone"-import type { MobileZone } from "./_types"+import type { MobileZone } from "@/components/community/shell/mobile-zone"describe("initialMobileZone", () => {it("returns 'nav' when no channel is in the URL", () => {diff --git a/src/web/src/components/community/mobile-zone.ts b/src/web/src/components/community/shell/mobile-zone.tssimilarity index 93%rename from src/web/src/components/community/mobile-zone.tsrename to src/web/src/components/community/shell/mobile-zone.tsindex 1ed0c9b78..69a24a619 100644--- a/src/web/src/components/community/mobile-zone.ts+++ b/src/web/src/components/community/shell/mobile-zone.ts@@ -1,4 +1,4 @@-import type { MobileZone } from "./_types"+export type MobileZone = "nav" | "messages"export type MobileZoneAction =| { type: "setActiveChannel" }diff --git a/src/web/src/components/community/panel-shell.tsx b/src/web/src/components/community/shell/panel-shell.tsxsimilarity index 100%rename from src/web/src/components/community/panel-shell.tsxrename to src/web/src/components/community/shell/panel-shell.tsxdiff --git a/src/web/src/components/community/shell/panel-types.ts b/src/web/src/components/community/shell/panel-types.tsnew file mode 100644index 000000000..0a5e1c030--- /dev/null+++ b/src/web/src/components/community/shell/panel-types.ts@@ -0,0 +1 @@+export type RightPanel = "members" | "pinned" | "search" | "threads" | nulldiff --git a/src/web/src/components/community/rail-folder.tsx b/src/web/src/components/community/shell/rail-folder.tsxsimilarity index 97%rename from src/web/src/components/community/rail-folder.tsxrename to src/web/src/components/community/shell/rail-folder.tsxindex 1c2eac623..c339e8071 100644--- a/src/web/src/components/community/rail-folder.tsx+++ b/src/web/src/components/community/shell/rail-folder.tsx@@ -6,7 +6,7 @@ import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem }import { RailIndicator } from "./rail-indicator"import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip"import { SeededBackdrop } from "@/components/avatar"-import type { FolderServer } from "./_types"+import type { FolderServer } from "@/lib/community/models/navigation"export function RailFolder({sortableId, open, onToggle, activeId, folderServers, onUngroup, dragging: isDragActive,diff --git a/src/web/src/components/community/rail-icon.tsx b/src/web/src/components/community/shell/rail-icon.tsxsimilarity index 100%rename from src/web/src/components/community/rail-icon.tsxrename to src/web/src/components/community/shell/rail-icon.tsxdiff --git a/src/web/src/components/community/rail-indicator.tsx b/src/web/src/components/community/shell/rail-indicator.tsxsimilarity index 100%rename from src/web/src/components/community/rail-indicator.tsxrename to src/web/src/components/community/shell/rail-indicator.tsxdiff --git a/src/web/src/components/community/right-panel.tsx b/src/web/src/components/community/shell/right-panel.tsxsimilarity index 92%rename from src/web/src/components/community/right-panel.tsxrename to src/web/src/components/community/shell/right-panel.tsxindex fc67b5f40..102b69eba 100644--- a/src/web/src/components/community/right-panel.tsx+++ b/src/web/src/components/community/shell/right-panel.tsx@@ -5,13 +5,17 @@ import { Users, Pin, Search, MessagesSquare } from "lucide-react"import { Input } from "@/components/ui/input"import { onEnterSubmit } from "@/lib/ime"import { Skeleton } from "@/components/ui/skeleton"-import { Avatar } from "./avatar"+import { Avatar } from "../avatar"import { PanelShell } from "./panel-shell"-import { MemberList } from "./member-list"-import { Message } from "./message"-import { formatRelativeTime } from "./format-time"-import { stripInlineMarkup } from "@alook/shared"-import type { RightPanel, Member, Role, Msg, RenderMsg, Thread, OpenProfile, MemberManageContext } from "./_types"+import { MemberList } from "../members/member-list"+import { Message } from "../messages/message"+import { formatRelativeTime } from "@/lib/community/format-time"+import { stripInlineMarkup, type CommunityRole as Role } from "@alook/shared"+import type { RightPanel } from "@/components/community/shell/panel-types"+import type { Member } from "@/lib/community/models/people"+import type { Msg, RenderMsg, Thread } from "@/lib/community/models/message"+import type { OpenProfile } from "@/components/community/social/profile-types"+import type { MemberManageContext } from "@/components/community/members/member-management-types"// Right-panel content router — members / pinned / search / threads. Data via props.// Always wraps the active section in PanelShell — the surrounding Sheet provides thediff --git a/src/web/src/components/community/server-rail-actions.test.ts b/src/web/src/components/community/shell/server-rail-actions.test.tssimilarity index 100%rename from src/web/src/components/community/server-rail-actions.test.tsrename to src/web/src/components/community/shell/server-rail-actions.test.tsdiff --git a/src/web/src/components/community/server-rail-actions.ts b/src/web/src/components/community/shell/server-rail-actions.tssimilarity index 100%rename from src/web/src/components/community/server-rail-actions.tsrename to src/web/src/components/community/shell/server-rail-actions.tsdiff --git a/src/web/src/components/community/server-rail-brand.test.ts b/src/web/src/components/community/shell/server-rail-brand.test.tssimilarity index 100%rename from src/web/src/components/community/server-rail-brand.test.tsrename to src/web/src/components/community/shell/server-rail-brand.test.tsdiff --git a/src/web/src/components/community/server-rail.tsx b/src/web/src/components/community/shell/server-rail.tsxsimilarity index 97%rename from src/web/src/components/community/server-rail.tsxrename to src/web/src/components/community/shell/server-rail.tsxindex 6ea43144a..5e767ad58 100644--- a/src/web/src/components/community/server-rail.tsx+++ b/src/web/src/components/community/shell/server-rail.tsx@@ -14,10 +14,12 @@ import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltipimport { Skeleton } from "@/components/ui/skeleton"import { SortableServer } from "./sortable-server"import { RailFolder } from "./rail-folder"-import { CreateServerDialog } from "./create-server-dialog"+import { CreateServerDialog } from "../settings/create-server-dialog"import { useRailOrder, isFolderKey, extractFolderId } from "./use-rail-order"import { SeededBackdrop } from "@/components/avatar"-import type { Server, CommunityFolder, MobileZone, View } from "./_types"+import type { Server, CommunityFolder } from "@/lib/community/models/navigation"+import type { MobileZone } from "@/components/community/shell/mobile-zone"+import type { View } from "@/components/community/shell/shell-types"import {completeCommunityOnboarding,isCommunityOnboardingStage,diff --git a/src/web/src/components/community/shell/shell-frame-contract.test.ts b/src/web/src/components/community/shell/shell-frame-contract.test.tsnew file mode 100644index 000000000..fe9d2bc2a--- /dev/null+++ b/src/web/src/components/community/shell/shell-frame-contract.test.ts@@ -0,0 +1,51 @@+import { readFileSync } from "node:fs"+import { dirname, resolve } from "node:path"+import { fileURLToPath } from "node:url"+import type { ComponentProps } from "react"+import { describe, expect, expectTypeOf, it } from "vitest"+import { ShellFrame } from "./shell-frame"+import type { ShellFrameProps } from "./shell-frame-types"++const shellDirectory = dirname(fileURLToPath(import.meta.url))+const webRoot = resolve(shellDirectory, "../../../..")+const readWeb = (path: string) => readFileSync(resolve(webRoot, path), "utf8")++describe("ShellFrame public contract", () => {+ it("keeps the exact public prop shape", () => {+ expectTypeOf<ComponentProps<typeof ShellFrame>>().toEqualTypeOf<ShellFrameProps>()+ })++ it("keeps both layout importers on the one public ShellFrame API", () => {+ const channels = readWeb("src/app/c/channels/layout.tsx")+ const dm = readWeb("src/app/c/me/layout.tsx")++ for (const source of [channels, dm]) {+ expect(source).toContain(+ 'import { ShellFrame } from "@/components/community/shell/shell-frame"',+ )+ expect(source).toContain("<ShellFrame")+ expect(source).toContain("mobileZone={mobileZone}")+ expect(source).toContain("setMobileZone={setMobileZone}")+ expect(source).toContain("sidebar={sidebar}")+ expect(source).toContain("goHome={goHome}")+ expect(source).toContain("goServer={goServer}")+ }+ expect(channels).toContain('view="server"')+ expect(channels).toContain("activeServerId={serverId}")+ expect(dm).toContain('view="dm"')+ expect(dm).toContain("activeServerId={undefined}")+ })++ it("keeps shell-frame as orchestration with one public component", () => {+ const source = readWeb("src/components/community/shell/shell-frame.tsx")+ expect(source.match(/export function /g)).toHaveLength(1)+ expect(source).toContain("export function ShellFrame")+ expect(source).toContain("useShellRailController")+ expect(source).toContain("useShellProfileController")+ expect(source).toContain("useShellInboxController")+ expect(source).toContain("<ShellFrameView")+ expect(source).not.toContain("<ServerRail")+ expect(source).not.toContain("<ProfileCard")+ expect(source).not.toContain("<InboxPopover")+ })+})diff --git a/src/web/src/components/community/shell-frame-geometry.test.ts b/src/web/src/components/community/shell/shell-frame-geometry.test.tssimilarity index 100%rename from src/web/src/components/community/shell-frame-geometry.test.tsrename to src/web/src/components/community/shell/shell-frame-geometry.test.tsdiff --git a/src/web/src/components/community/shell-frame-geometry.ts b/src/web/src/components/community/shell/shell-frame-geometry.tssimilarity index 100%rename from src/web/src/components/community/shell-frame-geometry.tsrename to src/web/src/components/community/shell/shell-frame-geometry.tsdiff --git a/src/web/src/components/community/shell/shell-frame-overlays.test.ts b/src/web/src/components/community/shell/shell-frame-overlays.test.tsnew file mode 100644index 000000000..e36505f9c--- /dev/null+++ b/src/web/src/components/community/shell/shell-frame-overlays.test.ts@@ -0,0 +1,161 @@+import { createElement } from "react"+import { readFileSync } from "node:fs"+import { beforeEach, describe, expect, it, vi } from "vitest"+import TestRenderer, { act } from "react-test-renderer"+import { ShellFrameOverlays } from "./shell-frame-overlays"++vi.mock("@/components/ui/dialog", () => ({+ Dialog: (props: Record<string, unknown>) => createElement("dialog-root", props),+ DialogContent: (props: Record<string, unknown>) => createElement("dialog-content", props),+}))+vi.mock("../settings/user-settings", () => ({+ UserSettings: (props: Record<string, unknown>) => createElement("user-settings", props),+}))+vi.mock("../social/profile-card", () => ({+ ProfileCard: (props: Record<string, unknown>) => createElement("profile-card", props),+}))+vi.mock("../messages/image-lightbox", () => ({+ ImageLightbox: (props: Record<string, unknown>) => createElement("image-lightbox", props),+}))+vi.mock("../messages/attachment-preview-sheet", () => ({+ AttachmentPreviewSheet: (props: Record<string, unknown>) => createElement("attachment-sheet", props),+}))+vi.mock("../image-crop-dialog", () => ({+ ImageCropDialog: (props: Record<string, unknown>) => createElement("crop-dialog", props),+}))++const controller = {+ currentUser: { id: "self" },+ profile: {+ data: { userId: "remote", name: "Remote" },+ x: 12,+ y: 34,+ initialStatusEmoji: "🌱",+ initialStatusText: "Growing",+ },+ closeProfile: vi.fn(),+ profileMessage: vi.fn(),+ updateOwnStatus: vi.fn(),+ preview: { url: "/image.png", alt: "image" },+ closePreview: vi.fn(),+ attachmentPreview: { id: "a1", filename: "notes.txt" },+ onAttachmentPreviewOpenChange: vi.fn(),+ editingProfile: true,+ onUserSettingsOpenChange: vi.fn(),+ userSettingsProps: { onClose: vi.fn(), userId: "self", userName: "Self" },+ pendingAvatarCrop: {+ imageSrc: "blob:avatar",+ originalFileName: "avatar.png",+ onCropped: vi.fn(),+ onCancel: vi.fn(),+ },+} as never++describe("ShellFrameOverlays", () => {+ beforeEach(() => {+ for (const value of Object.values(controller as unknown as Record<string, unknown>)) {+ if (typeof value === "function" && "mockClear" in value) {+ (value as ReturnType<typeof vi.fn>).mockClear()+ }+ }+ })++ it("renders each overlay once in the preserved order", async () => {+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(createElement(ShellFrameOverlays, {+ controller,+ breakpoint: "desktop",+ profileStatusSeeds: {+ initialStatusEmoji: "🌱",+ initialStatusText: "Growing",+ },+ extraDialogs: createElement("extra-dialog"),+ }))+ })++ const types = renderer.root.findAll(+ (node) => typeof node.type === "string",+ ).map((node) => node.type)+ expect(types.filter((type) => type === "profile-card")).toHaveLength(1)+ expect(types.filter((type) => type === "image-lightbox")).toHaveLength(1)+ expect(types.filter((type) => type === "attachment-sheet")).toHaveLength(1)+ expect(types.filter((type) => type === "user-settings")).toHaveLength(1)+ expect(types.filter((type) => type === "crop-dialog")).toHaveLength(1)+ expect(types.filter((type) => type === "extra-dialog")).toHaveLength(1)+ expect(types.indexOf("profile-card")).toBeLessThan(types.indexOf("image-lightbox"))+ expect(types.indexOf("image-lightbox")).toBeLessThan(types.indexOf("attachment-sheet"))+ expect(types.indexOf("attachment-sheet")).toBeLessThan(types.indexOf("dialog-root"))+ expect(types.indexOf("dialog-root")).toBeLessThan(types.indexOf("crop-dialog"))+ expect(types.indexOf("crop-dialog")).toBeLessThan(types.indexOf("extra-dialog"))++ const profileCard = renderer.root.findByType("profile-card")+ expect(profileCard.props.initialStatusEmoji).toBe("🌱")+ expect(profileCard.props.initialStatusText).toBe("Growing")+ expect(renderer.root.findByType("crop-dialog").props.maskShape).toBe("circle")++ renderer.root.findByType("attachment-sheet").props.onOpenChange(false)+ expect(controller.onAttachmentPreviewOpenChange).toHaveBeenCalledWith(false)+ renderer.root.findByType("dialog-root").props.onOpenChange(false)+ expect(controller.onUserSettingsOpenChange).toHaveBeenCalledWith(false)+ renderer.root.findByType("user-settings").props.onClose()+ expect(controller.userSettingsProps.onClose).toHaveBeenCalledTimes(1)+ })++ it("omits status seed props when the mobile caller omits them", async () => {+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(createElement(ShellFrameOverlays, {+ controller,+ breakpoint: "mobile",+ }))+ })+ const profileCard = renderer.root.findByType("profile-card")+ expect("initialStatusEmoji" in profileCard.props).toBe(false)+ expect("initialStatusText" in profileCard.props).toBe(false)+ })++ it("omits nullable overlays while keeping closed sheet and settings wiring", async () => {+ const emptyController = {+ ...controller,+ profile: null,+ preview: null,+ attachmentPreview: null,+ editingProfile: false,+ pendingAvatarCrop: null,+ } as never+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(createElement(ShellFrameOverlays, {+ controller: emptyController,+ breakpoint: "desktop",+ }))+ })++ expect(renderer.root.findAllByType("profile-card")).toHaveLength(0)+ expect(renderer.root.findAllByType("image-lightbox")).toHaveLength(0)+ expect(renderer.root.findAllByType("crop-dialog")).toHaveLength(0)+ expect(renderer.root.findByType("attachment-sheet").props).toMatchObject({+ attachment: null,+ open: false,+ })+ expect(renderer.root.findByType("dialog-root").props.open).toBe(false)+ })++ it("stays a render-only boundary", () => {+ const source = readFileSync(new URL("./shell-frame-overlays.tsx", import.meta.url), "utf8")+ expect(source).toContain(+ 'key={`${profile.data.userId ?? profile.data.name}:${profile.x}:${profile.y}`}',+ )+ for (const forbidden of [+ "/api/",+ "@/lib/query-keys",+ "@/stores/",+ "@/hooks/community/mutations",+ "@/lib/auth-client",+ "@/lib/query-persister",+ ]) {+ expect(source).not.toContain(forbidden)+ }+ })+})diff --git a/src/web/src/components/community/shell/shell-frame-overlays.tsx b/src/web/src/components/community/shell/shell-frame-overlays.tsxnew file mode 100644index 000000000..910b53a01--- /dev/null+++ b/src/web/src/components/community/shell/shell-frame-overlays.tsx@@ -0,0 +1,75 @@+"use client"++import type { ReactNode } from "react"+import type { Breakpoint } from "@/hooks/use-mobile"+import { Dialog, DialogContent } from "@/components/ui/dialog"+import { UserSettings } from "../settings/user-settings"+import { ProfileCard } from "../social/profile-card"+import { ImageLightbox } from "../messages/image-lightbox"+import { AttachmentPreviewSheet } from "../messages/attachment-preview-sheet"+import { ImageCropDialog } from "../image-crop-dialog"+import type { useShellProfileController } from "./use-shell-profile-controller"++type ProfileController = ReturnType<typeof useShellProfileController>++export function ShellFrameOverlays({+ controller,+ breakpoint,+ profileStatusSeeds,+ extraDialogs,+}: {+ controller: ProfileController+ breakpoint: Breakpoint+ profileStatusSeeds?: {+ initialStatusEmoji: string | null+ initialStatusText: string | null+ }+ extraDialogs?: ReactNode+}) {+ const { profile, currentUser } = controller+ const pendingAvatarCrop = controller.pendingAvatarCrop+ return (+ <>+ {profile && (+ <ProfileCard+ key={`${profile.data.userId ?? profile.data.name}:${profile.x}:${profile.y}`}+ data={profile.data}+ x={profile.x}+ y={profile.y}+ bp={breakpoint}+ onClose={controller.closeProfile}+ onMessage={controller.profileMessage}+ isSelf={!!profile.data.userId && profile.data.userId === currentUser.id}+ onUpdateStatus={controller.updateOwnStatus}+ {...profileStatusSeeds}+ />+ )}+ {controller.preview && (+ <ImageLightbox image={controller.preview} onClose={controller.closePreview} />+ )}+ <AttachmentPreviewSheet+ attachment={controller.attachmentPreview}+ open={!!controller.attachmentPreview}+ onOpenChange={controller.onAttachmentPreviewOpenChange}+ />+ <Dialog+ open={controller.editingProfile}+ onOpenChange={controller.onUserSettingsOpenChange}+ >+ <DialogContent+ className="flex h-[calc(100vh-4rem)] max-h-180 w-[calc(100vw-4rem)] sm:max-w-4xl flex-col gap-0 overflow-hidden rounded-xl p-0"+ showCloseButton={false}+ >+ <UserSettings {...controller.userSettingsProps} />+ </DialogContent>+ </Dialog>+ {pendingAvatarCrop && (+ <ImageCropDialog+ {...pendingAvatarCrop}+ maskShape="circle"+ />+ )}+ {extraDialogs}+ </>+ )+}diff --git a/src/web/src/components/community/shell/shell-frame-types.ts b/src/web/src/components/community/shell/shell-frame-types.tsnew file mode 100644index 000000000..521fc7c07--- /dev/null+++ b/src/web/src/components/community/shell/shell-frame-types.ts@@ -0,0 +1,23 @@+import type { ReactNode } from "react"+import type { MobileZone } from "./mobile-zone"+import type { View } from "./shell-types"++export type ShellFrameProps = {+ view: View+ activeServerId: string | undefined+ mobileZone: MobileZone+ setMobileZone: (zone: MobileZone) => void+ sidebar: (opts?: { noHeader?: boolean }) => ReactNode+ children: ReactNode+ extraDialogs?: ReactNode+ onOpenActiveServerSettings?: () => void+ onOpenActiveServerInvite?: () => void+ goHome: () => void+ goServer: () => void+}++export type ShellRouter = {+ push: (href: string) => void+ replace: (href: string) => void+ prefetch: (href: string) => void+}diff --git a/src/web/src/components/community/shell/shell-frame-view.test.ts b/src/web/src/components/community/shell/shell-frame-view.test.tsnew file mode 100644index 000000000..b5ee8dd7a--- /dev/null+++ b/src/web/src/components/community/shell/shell-frame-view.test.ts@@ -0,0 +1,199 @@+import { createElement } from "react"+import TestRenderer, { act } from "react-test-renderer"+import { beforeEach, describe, expect, it, vi } from "vitest"+import { ShellFrameView } from "./shell-frame-view"++const mocks = vi.hoisted(() => ({+ observe: vi.fn(),+ disconnect: vi.fn(),+ onLayoutChanged: vi.fn(),+ resizeCallback: { current: undefined as undefined | ((entries: Array<{ contentRect: { width: number } }>) => void) },+}))++vi.mock("react-resizable-panels", () => ({+ useDefaultLayout: () => ({ defaultLayout: { sidebar: 24, main: 76 }, onLayoutChanged: mocks.onLayoutChanged }),+}))+vi.mock("@/components/ui/resizable", () => ({+ ResizablePanelGroup: (props: Record<string, unknown>) => createElement("panel-group", props),+ ResizablePanel: (props: Record<string, unknown>) => createElement("panel", props),+ ResizableHandle: (props: Record<string, unknown>) => createElement("panel-handle", props),+}))+vi.mock("@/components/ui/app-surface", () => ({+ AppSurface: (props: Record<string, unknown>) => createElement("app-surface", props),+}))+vi.mock("./shell", () => ({+ Shell: (props: Record<string, unknown>) => createElement("shell-root", props),+}))+vi.mock("./server-rail", () => ({+ ServerRail: (props: Record<string, unknown>) => createElement("server-rail", props),+}))+vi.mock("./user-bar", () => ({+ UserBar: (props: Record<string, unknown>) => createElement("user-bar", props),+}))+vi.mock("./community-inbox-popover", () => ({+ InboxPopover: (props: Record<string, unknown>) => createElement("inbox-popover", props),+}))+vi.mock("./shell-frame-overlays", () => ({+ ShellFrameOverlays: (props: Record<string, unknown>) => createElement("shell-overlays", props),+}))++const rail = { railProps: { activeServerId: "s1" } } as never+const profile = {+ currentUser: { id: "u1", name: "User", avatar: "U" },+ openProfile: vi.fn(),+ openUserSettings: vi.fn(),+ profile: {+ initialStatusEmoji: "🌱",+ initialStatusText: "Growing",+ },+} as never+const inbox = {+ popoverProps: { unreads: [], unreadDms: [], mentions: [], marked: [], onOpenForumThread: vi.fn() },+ hasUnread: false,+ open: false,+ onOpenChange: vi.fn(),+} as never++describe("ShellFrameView", () => {+ beforeEach(() => {+ mocks.observe.mockClear()+ mocks.disconnect.mockClear()+ mocks.resizeCallback.current = undefined+ class ResizeObserverMock {+ constructor(callback: (entries: Array<{ contentRect: { width: number } }>) => void) {+ mocks.resizeCallback.current = callback+ }+ observe = mocks.observe+ disconnect = mocks.disconnect+ }+ vi.stubGlobal("ResizeObserver", ResizeObserverMock)+ })++ it("keeps the desktop panel geometry, order, and seeded overlay call", async () => {+ const sidebar = vi.fn(() => createElement("sidebar-content"))+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(createElement(ShellFrameView, {+ breakpoint: "desktop",+ mobileZone: "messages",+ sidebar,+ cancelPendingNavigation: vi.fn(),+ rail,+ profile,+ inbox,+ extraDialogs: createElement("extra-dialog"),+ }, createElement("main-content")), { createNodeMock: () => ({ offsetWidth: 240 }) })+ })++ const shell = renderer.root.findByType("shell-root")+ const hostTypes = shell.findAll((node) => typeof node.type === "string").map((node) => node.type)+ expect(hostTypes.indexOf("server-rail")).toBeLessThan(hostTypes.indexOf("app-surface"))+ expect(hostTypes.indexOf("app-surface")).toBeLessThan(hostTypes.indexOf("user-bar"))+ expect(hostTypes.indexOf("user-bar")).toBeLessThan(hostTypes.indexOf("shell-overlays"))+ expect(renderer.root.findAllByType("shell-overlays")).toHaveLength(1)+ expect(renderer.root.findByType("server-rail").props.bottomInset).toBe(60)+ const group = renderer.root.findByType("panel-group")+ expect(group.props.id).toBe("community-shell")+ expect(group.props.orientation).toBe("horizontal")+ const [sidebarPanel, mainPanel] = renderer.root.findAllByType("panel")+ expect(sidebarPanel.props).toMatchObject({ id: "sidebar", defaultSize: "24%", minSize: 160, maxSize: 360 })+ expect(mainPanel.props).toMatchObject({ id: "main", defaultSize: "76%" })+ expect(renderer.root.findByType("shell-overlays").props.profileStatusSeeds).toEqual({+ initialStatusEmoji: "🌱",+ initialStatusText: "Growing",+ })+ expect(sidebar).toHaveBeenCalledWith()+ expect(mocks.observe).toHaveBeenCalledTimes(1)+ const userBarOverlay = renderer.root.find(+ (node) => node.props.style?.marginLeft === -56,+ )+ expect(userBarOverlay.props.style.width).toBe(297)+ await act(async () => {+ mocks.resizeCallback.current?.([{ contentRect: { width: 300 } }])+ })+ expect(userBarOverlay.props.style.width).toBe(357)++ await act(async () => renderer.unmount())+ expect(mocks.disconnect).toHaveBeenCalledTimes(1)+ })++ it("keeps mobile nav and messages branches distinct and omits status seeds", async () => {+ const sidebar = vi.fn(() => createElement("sidebar-content"))+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(createElement(ShellFrameView, {+ breakpoint: "mobile",+ mobileZone: "nav",+ sidebar,+ cancelPendingNavigation: vi.fn(),+ rail,+ profile,+ inbox,+ }, createElement("main-content")))+ })+ expect(renderer.root.findAllByType("server-rail")).toHaveLength(1)+ expect(renderer.root.findAllByType("user-bar")).toHaveLength(1)+ expect(renderer.root.findAllByType("main-content")).toHaveLength(0)+ expect(renderer.root.findAllByType("shell-overlays")).toHaveLength(1)+ expect("profileStatusSeeds" in renderer.root.findByType("shell-overlays").props).toBe(false)+ expect(sidebar).toHaveBeenCalledWith({ noHeader: false })++ await act(async () => {+ renderer.update(createElement(ShellFrameView, {+ breakpoint: "mobile",+ mobileZone: "messages",+ sidebar,+ cancelPendingNavigation: vi.fn(),+ rail,+ profile,+ inbox,+ }, createElement("main-content")))+ })+ expect(renderer.root.findAllByType("server-rail")).toHaveLength(0)+ expect(renderer.root.findAllByType("user-bar")).toHaveLength(0)+ expect(renderer.root.findAllByType("main-content")).toHaveLength(1)+ expect(renderer.root.findAllByType("shell-overlays")).toHaveLength(1)+ })++ it("disconnects and re-subscribes sidebar observation across breakpoint changes", async () => {+ const sidebar = vi.fn(() => createElement("sidebar-content"))+ const common = {+ mobileZone: "nav" as const,+ sidebar,+ cancelPendingNavigation: vi.fn(),+ rail,+ profile,+ inbox,+ }+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(+ createElement(ShellFrameView, { ...common, breakpoint: "desktop" }, createElement("main-content")),+ { createNodeMock: () => ({ offsetWidth: 240 }) },+ )+ })+ expect(mocks.observe).toHaveBeenCalledTimes(1)++ await act(async () => {+ renderer.update(createElement(+ ShellFrameView,+ { ...common, breakpoint: "mobile" },+ createElement("main-content"),+ ))+ })+ expect(mocks.disconnect).toHaveBeenCalledTimes(1)+ expect(mocks.observe).toHaveBeenCalledTimes(1)++ await act(async () => {+ renderer.update(createElement(+ ShellFrameView,+ { ...common, breakpoint: "desktop" },+ createElement("main-content"),+ ))+ })+ expect(mocks.observe).toHaveBeenCalledTimes(2)++ await act(async () => renderer.unmount())+ expect(mocks.disconnect).toHaveBeenCalledTimes(2)+ })+})diff --git a/src/web/src/components/community/shell/shell-frame-view.tsx b/src/web/src/components/community/shell/shell-frame-view.tsxnew file mode 100644index 000000000..875661d29--- /dev/null+++ b/src/web/src/components/community/shell/shell-frame-view.tsx@@ -0,0 +1,158 @@+"use client"++import { useEffect, useRef, useState } from "react"+import { useDefaultLayout } from "react-resizable-panels"+import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@/components/ui/resizable"+import { AppSurface } from "@/components/ui/app-surface"+import { Shell } from "./shell"+import { ServerRail } from "./server-rail"+import { UserBar } from "./user-bar"+import { InboxPopover } from "./community-inbox-popover"+import { ShellFrameOverlays } from "./shell-frame-overlays"+import {+ COMMUNITY_RAIL_WIDTH,+ desktopUserBarOverlayWidth,+} from "./shell-frame-geometry"+import type { Breakpoint } from "@/hooks/use-mobile"+import type { ShellFrameProps } from "./shell-frame-types"+import type { useShellRailController } from "./use-shell-rail-controller"+import type { useShellProfileController } from "./use-shell-profile-controller"+import type { useShellInboxController } from "./use-shell-inbox-controller"++type Props = Pick<ShellFrameProps, "mobileZone" | "sidebar" | "children" | "extraDialogs"> & {+ breakpoint: Breakpoint+ cancelPendingNavigation: () => void+ rail: ReturnType<typeof useShellRailController>+ profile: ReturnType<typeof useShellProfileController>+ inbox: ReturnType<typeof useShellInboxController>+}++export function ShellFrameView({+ breakpoint,+ mobileZone,+ sidebar,+ children,+ extraDialogs,+ cancelPendingNavigation,+ rail,+ profile,+ inbox,+}: Props) {+ const { defaultLayout, onLayoutChanged } = useDefaultLayout({ id: "community-shell" })+ const sidebarPanelRef = useRef<HTMLDivElement>(null)+ const [sidebarWidth, setSidebarWidth] = useState(240)+ useEffect(() => {+ const element = sidebarPanelRef.current+ if (!element) return+ setSidebarWidth(element.offsetWidth)+ const observer = new ResizeObserver(([entry]) => setSidebarWidth(entry!.contentRect.width))+ observer.observe(element)+ return () => observer.disconnect()+ }, [breakpoint])++ const inboxElement = <InboxPopover {...inbox.popoverProps} />+ const user = {+ id: profile.currentUser.id,+ name: profile.currentUser.name,+ avatar: profile.currentUser.avatar,+ }++ if (breakpoint === "desktop") {+ return (+ <Shell onNavigationIntent={cancelPendingNavigation}>+ <ServerRail {...rail.railProps} bottomInset={60} />+ <div className="relative flex-1 flex flex-col min-w-0 pt-2">+ <AppSurface className="rounded-tl-xl rounded-tr-none rounded-br-none rounded-bl-none ring-0 border-l border-t border-border/40 shadow-none">+ <ResizablePanelGroup+ id="community-shell"+ orientation="horizontal"+ className="min-h-0 flex-1"+ defaultLayout={defaultLayout}+ onLayoutChanged={onLayoutChanged}+ >+ <ResizablePanel+ id="sidebar"+ defaultSize="24%"+ minSize={160}+ maxSize={360}+ className="flex flex-col pb-14 bg-sidebar"+ >+ <div ref={sidebarPanelRef} className="flex min-h-0 flex-1 flex-col">+ {sidebar()}+ </div>+ </ResizablePanel>+ <ResizableHandle className="bg-transparent" />+ <ResizablePanel+ id="main"+ defaultSize="76%"+ className="flex min-w-0 flex-col bg-background"+ >+ {children}+ </ResizablePanel>+ </ResizablePanelGroup>+ </AppSurface>+ <div+ className="absolute bottom-0 left-0 z-10"+ style={{+ width: desktopUserBarOverlayWidth(sidebarWidth),+ marginLeft: -COMMUNITY_RAIL_WIDTH,+ }}+ >+ <UserBar+ user={user}+ onOpenProfile={profile.openProfile}+ onEditProfile={profile.openUserSettings}+ inbox={inboxElement}+ hasUnread={inbox.hasUnread}+ inboxOpen={inbox.open}+ onInboxOpenChange={inbox.onOpenChange}+ />+ </div>+ </div>+ <ShellFrameOverlays+ controller={profile}+ breakpoint={breakpoint}+ profileStatusSeeds={profile.profile ? {+ initialStatusEmoji: profile.profile.initialStatusEmoji,+ initialStatusText: profile.profile.initialStatusText,+ } : undefined}+ extraDialogs={extraDialogs}+ />+ </Shell>+ )+ }++ return (+ <Shell onNavigationIntent={cancelPendingNavigation}>+ {mobileZone === "nav" && (+ <>+ <ServerRail {...rail.railProps} bottomInset={60} />+ <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-sidebar">+ <div className="flex min-h-0 min-w-0 flex-1">+ {sidebar({ noHeader: false })}+ </div>+ <UserBar+ user={user}+ onOpenProfile={profile.openProfile}+ onEditProfile={profile.openUserSettings}+ inbox={inboxElement}+ hasUnread={inbox.hasUnread}+ inboxOpen={inbox.open}+ onInboxOpenChange={inbox.onOpenChange}+ />+ </div>+ </>+ )}+ {mobileZone === "messages" && (+ <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background">+ {children}+ </div>+ )}+ <ShellFrameOverlays+ controller={profile}+ breakpoint={breakpoint}+ extraDialogs={extraDialogs}+ />+ </Shell>+ )+}diff --git a/src/web/src/components/community/shell/shell-frame.test.ts b/src/web/src/components/community/shell/shell-frame.test.tsnew file mode 100644index 000000000..518eb0960--- /dev/null+++ b/src/web/src/components/community/shell/shell-frame.test.ts@@ -0,0 +1,121 @@+import { createElement } from "react"+import TestRenderer, { act } from "react-test-renderer"+import { beforeEach, describe, expect, it, vi } from "vitest"+import { ShellFrame } from "./shell-frame"++const mocks = vi.hoisted(() => {+ const handlers = {+ previewImage: vi.fn(),+ previewAttachment: vi.fn(),+ openProfile: vi.fn(),+ navigate: vi.fn(),+ cancelPendingNavigation: vi.fn(),+ }+ return {+ onboarding: { current: { status: "active", stage: "server" } as unknown },+ pathname: { current: "/c/channels/s1" },+ registerUiHandlers: vi.fn(),+ setMobileZone: vi.fn(),+ handlers,+ rail: {+ railProps: {},+ navigate: handlers.navigate,+ cancelPendingNavigation: handlers.cancelPendingNavigation,+ },+ profile: {+ previewImage: handlers.previewImage,+ previewAttachment: handlers.previewAttachment,+ openProfile: handlers.openProfile,+ },+ inbox: {},+ }+})++vi.mock("next/navigation", () => ({+ useRouter: () => ({ push: vi.fn(), replace: vi.fn(), prefetch: vi.fn() }),+ usePathname: () => mocks.pathname.current,+}))+vi.mock("@tanstack/react-query", () => ({ useQueryClient: () => ({}) }))+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))+vi.mock("@/lib/community-onboarding", () => ({+ useCommunityOnboarding: () => mocks.onboarding.current,+}))+vi.mock("@/stores/community", () => ({+ useCommunityStore: Object.assign(vi.fn(), {+ getState: () => ({ registerUiHandlers: mocks.registerUiHandlers }),+ }),+}))+vi.mock("./use-shell-rail-controller", () => ({+ useShellRailController: () => mocks.rail,+}))+vi.mock("./use-shell-profile-controller", () => ({+ useShellProfileController: () => mocks.profile,+}))+vi.mock("./use-shell-inbox-controller", () => ({+ useShellInboxController: () => mocks.inbox,+}))+vi.mock("./shell-frame-view", () => ({+ ShellFrameView: (props: Record<string, unknown>) => createElement("shell-frame-view", props),+}))++const baseProps = {+ view: "server" as const,+ activeServerId: "s1",+ mobileZone: "messages" as const,+ setMobileZone: mocks.setMobileZone,+ sidebar: () => createElement("sidebar"),+ goHome: vi.fn(),+ goServer: vi.fn(),+}++describe("ShellFrame orchestration", () => {+ beforeEach(() => {+ mocks.onboarding.current = { status: "active", stage: "server" }+ mocks.pathname.current = "/c/channels/s1"+ mocks.registerUiHandlers.mockClear()+ mocks.setMobileZone.mockClear()+ })++ it("maps active onboarding stages to the existing mobile zones", async () => {+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(createElement(ShellFrame, baseProps))+ })+ expect(mocks.setMobileZone).toHaveBeenLastCalledWith("nav")++ mocks.onboarding.current = { status: "active", stage: "channel" }+ await act(async () => {+ renderer.update(createElement(ShellFrame, baseProps, "next"))+ })+ expect(mocks.setMobileZone).toHaveBeenLastCalledWith("messages")++ mocks.onboarding.current = { status: "complete" }+ mocks.setMobileZone.mockClear()+ await act(async () => {+ renderer.update(createElement(ShellFrame, baseProps, "done"))+ })+ expect(mocks.setMobileZone).not.toHaveBeenCalled()+ })++ it("registers exactly six stable UI handlers", async () => {+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(createElement(ShellFrame, baseProps))+ })+ const first = mocks.registerUiHandlers.mock.calls.at(-1)?.[0]+ expect(Object.keys(first).sort()).toEqual([+ "cancelPendingNavigation",+ "goBackMobile",+ "navigate",+ "openProfile",+ "previewAttachment",+ "previewImage",+ ])++ await act(async () => {+ renderer.update(createElement(ShellFrame, baseProps, "rerender"))+ })+ const second = mocks.registerUiHandlers.mock.calls.at(-1)?.[0]+ for (const key of Object.keys(first)) expect(second[key]).toBe(first[key])+ })+})diff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsxnew file mode 100644index 000000000..ed0d4e6a6--- /dev/null+++ b/src/web/src/components/community/shell/shell-frame.tsx@@ -0,0 +1,103 @@+"use client"++import { useCallback, useEffect } from "react"+import { usePathname, useRouter } from "next/navigation"+import { useQueryClient } from "@tanstack/react-query"+import { useBreakpoint } from "@/hooks/use-mobile"+import { useCommunityOnboarding } from "@/lib/community-onboarding"+import { useCommunityStore } from "@/stores/community"+import { ShellFrameView } from "./shell-frame-view"+import { useShellRailController } from "./use-shell-rail-controller"+import { useShellProfileController } from "./use-shell-profile-controller"+import { useShellInboxController } from "./use-shell-inbox-controller"+import type { ShellFrameProps } from "./shell-frame-types"++/** Shared community shell orchestration for the server and DM layouts. */+export function ShellFrame(props: ShellFrameProps) {+ const {+ view,+ activeServerId,+ mobileZone,+ setMobileZone,+ sidebar,+ children,+ extraDialogs,+ onOpenActiveServerSettings,+ onOpenActiveServerInvite,+ goHome,+ goServer,+ } = props+ const router = useRouter()+ const pathname = usePathname()+ const queryClient = useQueryClient()+ const breakpoint = useBreakpoint()+ const onboardingState = useCommunityOnboarding()++ useEffect(() => {+ if (onboardingState?.status === "active") {+ setMobileZone(onboardingState.stage === "server" ? "nav" : "messages")+ }+ }, [onboardingState, setMobileZone])++ const rail = useShellRailController({+ router,+ pathname,+ queryClient,+ view,+ activeServerId,+ setMobileZone,+ onOpenActiveServerSettings,+ onOpenActiveServerInvite,+ goHome,+ goServer,+ })+ const profile = useShellProfileController({+ router,+ queryClient,+ cancelPendingNavigation: rail.cancelPendingNavigation,+ view,+ activeServerId,+ })+ const inbox = useShellInboxController({+ router,+ queryClient,+ cancelPendingNavigation: rail.cancelPendingNavigation,+ })+ const goBackMobile = useCallback(+ () => setMobileZone("nav"),+ [setMobileZone],+ )++ useEffect(() => {+ useCommunityStore.getState().registerUiHandlers({+ previewImage: profile.previewImage,+ previewAttachment: profile.previewAttachment,+ openProfile: profile.openProfile,+ goBackMobile,+ navigate: rail.navigate,+ cancelPendingNavigation: rail.cancelPendingNavigation,+ })+ }, [+ goBackMobile,+ profile.openProfile,+ profile.previewAttachment,+ profile.previewImage,+ rail.cancelPendingNavigation,+ rail.navigate,+ ])++ return (+ <ShellFrameView+ breakpoint={breakpoint}+ mobileZone={mobileZone}+ sidebar={sidebar}+ extraDialogs={extraDialogs}+ cancelPendingNavigation={rail.cancelPendingNavigation}+ rail={rail}+ profile={profile}+ inbox={inbox}+ >+ {children}+ </ShellFrameView>+ )+}diff --git a/src/web/src/components/community/shell/shell-types.ts b/src/web/src/components/community/shell/shell-types.tsnew file mode 100644index 000000000..2023e20ca--- /dev/null+++ b/src/web/src/components/community/shell/shell-types.ts@@ -0,0 +1 @@+export type View = "server" | "dm" | "settings"diff --git a/src/web/src/components/community/shell.navigation-intent.test.ts b/src/web/src/components/community/shell/shell.navigation-intent.test.tssimilarity index 100%rename from src/web/src/components/community/shell.navigation-intent.test.tsrename to src/web/src/components/community/shell/shell.navigation-intent.test.tsdiff --git a/src/web/src/components/community/shell.tsx b/src/web/src/components/community/shell/shell.tsxsimilarity index 100%rename from src/web/src/components/community/shell.tsxrename to src/web/src/components/community/shell/shell.tsxdiff --git a/src/web/src/components/community/sortable-server.tsx b/src/web/src/components/community/shell/sortable-server.tsxsimilarity index 99%rename from src/web/src/components/community/sortable-server.tsxrename to src/web/src/components/community/shell/sortable-server.tsxindex 37f5453cc..88e3e420b 100644--- a/src/web/src/components/community/sortable-server.tsx+++ b/src/web/src/components/community/shell/sortable-server.tsx@@ -20,7 +20,7 @@ import { ConfirmDialog } from "@/components/ui/confirm-dialog";import { NumberTicker } from "@/components/ui/number-ticker";import { SeededBackdrop } from "@/components/avatar";import { tid } from "@/lib/community/testids";-import type { Server } from "./_types";+import type { Server } from "@/lib/community/models/navigation"type SortableServerProps = {server: Server;diff --git a/src/web/src/components/community/use-rail-order.test.ts b/src/web/src/components/community/shell/use-rail-order.test.tssimilarity index 100%rename from src/web/src/components/community/use-rail-order.test.tsrename to src/web/src/components/community/shell/use-rail-order.test.tsdiff --git a/src/web/src/components/community/use-rail-order.ts b/src/web/src/components/community/shell/use-rail-order.tssimilarity index 99%rename from src/web/src/components/community/use-rail-order.tsrename to src/web/src/components/community/shell/use-rail-order.tsindex a153d97a4..13271e524 100644--- a/src/web/src/components/community/use-rail-order.ts+++ b/src/web/src/components/community/shell/use-rail-order.ts@@ -3,7 +3,7 @@import { useCallback, useEffect, useRef, useState } from "react"import { arrayMove } from "@dnd-kit/sortable"import type { DragEndEvent, DragOverEvent, DragStartEvent } from "@dnd-kit/core"-import type { CommunityFolder } from "./_types"+import type { CommunityFolder } from "@/lib/community/models/navigation"export const FOLDER_PREFIX = "folder:"export function folderId(id: string) { return `${FOLDER_PREFIX}${id}` }diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.test.tsnew file mode 100644index 000000000..a81864f38--- /dev/null+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts@@ -0,0 +1,158 @@+import { createElement } from "react"+import TestRenderer, { act } from "react-test-renderer"+import { beforeEach, describe, expect, it, vi } from "vitest"+import { useShellInboxController } from "./use-shell-inbox-controller"++const mocks = vi.hoisted(() => ({+ markedEnabled: [] as boolean[],+ watch: vi.fn(),+ markAll: vi.fn(),+ deleteMention: vi.fn(),+ unmark: vi.fn(),+ readForum: vi.fn(),+}))++vi.mock("@/hooks/community/use-inbox", () => ({+ useInboxUnreads: () => ({+ servers: [],+ dms: [{ channelId: "dm1", otherUserId: "u2", otherUserName: "Peer", otherUserAvatar: "P" }],+ isLoading: false,+ }),+ useInboxMentions: () => ({ mentions: [], isLoading: false }),+ useInboxMarked: (enabled: boolean) => {+ mocks.markedEnabled.push(enabled)+ return { marked: [], isLoading: false }+ },+}))+vi.mock("@/hooks/community/use-inbox-auto-collapse", () => ({+ useInboxAutoCollapse: () => ({ open: true, onOpenChange: vi.fn(), watchItem: mocks.watch }),+}))+vi.mock("@/hooks/community/mutations", () => ({+ useMarkAllInboxRead: () => ({ mutate: mocks.markAll }),+ useDeleteMention: () => ({ mutate: mocks.deleteMention }),+ useUnmarkMessage: () => ({ mutate: mocks.unmark }),+ useReadForumThreadFromInbox: () => ({ mutate: mocks.readForum }),+}))++type Result = ReturnType<typeof useShellInboxController>++function Capture({ options, onResult }: {+ options: Parameters<typeof useShellInboxController>[0]+ onResult: (result: Result) => void+}) {+ onResult(useShellInboxController(options))+ return null+}++async function renderController() {+ const order: string[] = []+ const pushed: string[] = []+ const router = {+ push: (href: string) => { order.push("push"); pushed.push(href) },+ replace: vi.fn(),+ prefetch: vi.fn(),+ }+ let dmCache = { conversations: [{ id: "dm1", unread: true }, { id: "dm2", unread: true }] }+ const queryClient = {+ setQueryData: vi.fn((_key, updater) => {+ order.push("query")+ dmCache = updater(dmCache)+ }),+ }+ const cancelPendingNavigation = vi.fn(() => { order.push("cancel") })+ mocks.watch.mockImplementation(() => { order.push("watch") })+ mocks.readForum.mockImplementation(() => { order.push("read") })+ let current!: Result+ let renderer!: TestRenderer.ReactTestRenderer+ const options = { router, queryClient, cancelPendingNavigation } as never+ await act(async () => {+ renderer = TestRenderer.create(createElement(Capture, {+ options,+ onResult: (result) => { current = result },+ }))+ })+ return {+ get current() { return current },+ renderer,+ order,+ pushed,+ get dmCache() { return dmCache },+ }+}++describe("useShellInboxController", () => {+ beforeEach(() => {+ mocks.markedEnabled.length = 0+ for (const mock of [mocks.watch, mocks.markAll, mocks.deleteMention, mocks.unmark, mocks.readForum]) {+ mock.mockReset()+ }+ })++ it("keeps Marked lazy and latches it after first selection", async () => {+ const hook = await renderController()+ expect(mocks.markedEnabled.at(-1)).toBe(false)+ await act(async () => hook.current.popoverProps.onMarkedTabSelected?.())+ expect(mocks.markedEnabled.at(-1)).toBe(true)+ await act(async () => hook.current.popoverProps.onMarkedTabSelected?.())+ expect(mocks.markedEnabled.at(-1)).toBe(true)+ })++ it("preserves DM optimistic-clear, watch, cancel, push order", async () => {+ const hook = await renderController()+ hook.order.length = 0+ await act(async () => hook.current.popoverProps.onOpenDm?.("dm1"))+ expect(hook.order).toEqual(["query", "watch", "cancel", "push"])+ expect(mocks.watch).toHaveBeenCalledWith("dm:dm1")+ expect(hook.pushed).toEqual(["/c/me/dm1"])+ expect(hook.dmCache.conversations[0]?.unread).toBe(false)+ expect(hook.dmCache.conversations[1]?.unread).toBe(true)+ })++ it("preserves forum and mention watch keys and non-blocking routes", async () => {+ const hook = await renderController()+ hook.order.length = 0+ await act(async () => hook.current.popoverProps.onOpenForumThread("s1", "forum", "child", "opener"))+ expect(hook.order).toEqual(["watch", "read", "cancel", "push"])+ expect(mocks.watch).toHaveBeenCalledWith("channel:child")+ expect(mocks.readForum).toHaveBeenCalledWith({ parentChannelId: "forum", openerMessageId: "opener" })+ expect(hook.pushed.at(-1)).toBe("/c/channels/s1/child")++ hook.order.length = 0+ await act(async () => hook.current.popoverProps.onOpenMention?.({ id: "m1" } as never))+ expect(hook.order).toEqual([])+ await act(async () => hook.current.popoverProps.onOpenMention?.({ id: "m1", serverId: "s1", channelId: "c1" } as never))+ expect(mocks.watch).toHaveBeenLastCalledWith("mention:m1")+ expect(hook.pushed.at(-1)).toBe("/c/channels/s1/c1")+ })++ it("routes marked rows by server/DM with optional seq and exact watch keys", async () => {+ const hook = await renderController()+ await act(async () => hook.current.popoverProps.onOpenMarked?.({+ id: "mk1",+ serverId: "s1",+ channelId: "c1",+ m: { seq: 7 },+ } as never))+ expect(mocks.watch).toHaveBeenLastCalledWith("marked:mk1")+ expect(hook.pushed.at(-1)).toBe("/c/channels/s1/c1?seq=7")++ await act(async () => hook.current.popoverProps.onOpenMarked?.({+ id: "mk2",+ serverId: null,+ channelId: "dm1",+ m: {},+ } as never))+ expect(mocks.watch).toHaveBeenLastCalledWith("marked:mk2")+ expect(hook.pushed.at(-1)).toBe("/c/me/dm1")+ })++ it("wires mark/delete/unmark payloads", async () => {+ const hook = await renderController()+ await act(async () => hook.current.popoverProps.onMarkAllRead?.())+ await act(async () => hook.current.popoverProps.onDeleteMention?.("mn1"))+ await act(async () => hook.current.popoverProps.onUnmark?.("msg1"))+ expect(mocks.markAll).toHaveBeenCalledWith()+ expect(mocks.deleteMention).toHaveBeenCalledWith({ mentionId: "mn1" })+ expect(mocks.unmark).toHaveBeenCalledWith({ messageId: "msg1" })+ })+})diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.tsnew file mode 100644index 000000000..e7afd5952--- /dev/null+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.ts@@ -0,0 +1,124 @@+"use client"++import { useCallback, useState, type ComponentProps } from "react"+import { communityKeys } from "@/lib/query-keys"+import type { Marked } from "@/lib/community/models/inbox"+import { useInboxUnreads, useInboxMentions, useInboxMarked } from "@/hooks/community/use-inbox"+import { useInboxAutoCollapse } from "@/hooks/community/use-inbox-auto-collapse"+import {+ useMarkAllInboxRead,+ useDeleteMention,+ useUnmarkMessage,+ useReadForumThreadFromInbox,+} from "@/hooks/community/mutations"+import type { InboxPopover } from "./community-inbox-popover"+import type { QueryClient } from "@tanstack/react-query"+import type { ShellRouter } from "./shell-frame-types"++type Options = {+ router: ShellRouter+ queryClient: QueryClient+ cancelPendingNavigation: () => void+}++export function useShellInboxController({+ router,+ queryClient,+ cancelPendingNavigation,+}: Options) {+ const inboxUnreads = useInboxUnreads()+ const inboxMentions = useInboxMentions()+ const unreadFeed = inboxUnreads.servers+ const unreadDms = inboxUnreads.dms+ const mentions = inboxMentions.mentions+ const loading = inboxUnreads.isLoading || inboxMentions.isLoading+ const [markedTabOpened, setMarkedTabOpened] = useState(false)+ const inboxMarked = useInboxMarked(markedTabOpened)+ const { mutate: unmarkMessageMutate } = useUnmarkMessage()+ const markAllInboxRead = useMarkAllInboxRead()+ const deleteMention = useDeleteMention()+ const { mutate: readForumThreadFromInbox } = useReadForumThreadFromInbox()+ const inbox = useInboxAutoCollapse({ unreads: unreadFeed, unreadDms, mentions })+ const watchInboxItem = inbox.watchItem++ const openServerChannel = useCallback((+ serverId: string,+ channelId: string,+ watchKey: string = `channel:${channelId}`,+ ) => {+ watchInboxItem(watchKey)+ cancelPendingNavigation()+ router.push(`/c/channels/${serverId}/${channelId}`)+ }, [cancelPendingNavigation, router, watchInboxItem])++ const openForumThread = useCallback((+ serverId: string,+ parentChannelId: string,+ childChannelId: string,+ openerMessageId: string,+ ) => {+ watchInboxItem(`channel:${childChannelId}`)+ readForumThreadFromInbox({ parentChannelId, openerMessageId })+ cancelPendingNavigation()+ router.push(`/c/channels/${serverId}/${childChannelId}`)+ }, [cancelPendingNavigation, readForumThreadFromInbox, router, watchInboxItem])++ const openMarked = useCallback((marked: Marked) => {+ watchInboxItem(`marked:${marked.id}`)+ cancelPendingNavigation()+ const seqQuery = marked.m.seq != null ? `?seq=${marked.m.seq}` : ""+ if (marked.serverId) {+ router.push(`/c/channels/${marked.serverId}/${marked.channelId}${seqQuery}`)+ } else {+ router.push(`/c/me/${marked.channelId}${seqQuery}`)+ }+ }, [cancelPendingNavigation, router, watchInboxItem])++ const openDm = useCallback((dmId: string) => {+ queryClient.setQueryData(+ communityKeys.dms(),+ (previous: { conversations: { id: string; unread?: boolean }[] } | undefined) =>+ previous+ ? {+ ...previous,+ conversations: previous.conversations.map((dm) =>+ dm.id === dmId ? { ...dm, unread: false } : dm+ ),+ }+ : previous,+ )+ watchInboxItem(`dm:${dmId}`)+ cancelPendingNavigation()+ router.push(`/c/me/${dmId}`)+ }, [cancelPendingNavigation, queryClient, router, watchInboxItem])++ const popoverProps: ComponentProps<typeof InboxPopover> = {+ unreads: unreadFeed,+ unreadDms,+ mentions,+ marked: inboxMarked.marked,+ markedLoading: inboxMarked.isLoading,+ loading,+ onOpenChannel: openServerChannel,+ onOpenForumThread: openForumThread,+ onOpenDm: openDm,+ onOpenMention: (mention) => {+ if (mention.serverId && mention.channelId) {+ openServerChannel(mention.serverId, mention.channelId, `mention:${mention.id}`)+ }+ },+ onOpenMarked: openMarked,+ onMarkedTabSelected: () => setMarkedTabOpened(true),+ onMarkAllRead: () => { markAllInboxRead.mutate() },+ onDeleteMention: (id) => deleteMention.mutate({ mentionId: id }),+ onUnmark: (messageId) => unmarkMessageMutate({ messageId }),+ }++ return {+ popoverProps,+ hasUnread:+ unreadFeed.length > 0 || unreadDms.length > 0 || mentions.length > 0,+ open: inbox.open,+ onOpenChange: inbox.onOpenChange,+ }+}diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.test.ts b/src/web/src/components/community/shell/use-shell-profile-controller.test.tsnew file mode 100644index 000000000..4790cfc41--- /dev/null+++ b/src/web/src/components/community/shell/use-shell-profile-controller.test.ts@@ -0,0 +1,384 @@+import { createElement } from "react"+import TestRenderer, { act } from "react-test-renderer"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { useShellProfileController } from "./use-shell-profile-controller"++const mocks = vi.hoisted(() => ({+ currentUser: {+ id: "self",+ name: "Self",+ avatar: "S",+ aboutMe: "About",+ statusEmoji: "🙂",+ statusText: "Here",+ },+ setCurrentUser: vi.fn(),+ fetchQuery: vi.fn(),+ createDm: vi.fn(),+ acceptDm: vi.fn(),+ updateProfile: vi.fn(),+ uploadAvatar: vi.fn(),+ setUserStatus: vi.fn(),+ communityReset: vi.fn(),+ wsReset: vi.fn(),+ streamReset: vi.fn(),+ clearCache: vi.fn(),+ signOut: vi.fn(),+ toast: vi.fn(),+ toastApiError: vi.fn(),+ validate: vi.fn(),+}))++vi.mock("sonner", () => ({ toast: mocks.toast }))+vi.mock("@/lib/api/client", () => ({ toastApiError: mocks.toastApiError }))+vi.mock("@/hooks/community/use-user-profile", () => ({+ userProfileQueryFn: (id: string) => () => Promise.resolve({ id }),+ PROFILE_STALE_TIME_MS: 300_000,+}))+vi.mock("@/lib/community/image-crop", () => ({ validateIconSourceFile: mocks.validate }))+vi.mock("@/contexts/community/current-user", () => ({+ useCurrentUser: () => mocks.currentUser,+ useSetCurrentUser: () => mocks.setCurrentUser,+}))+vi.mock("@/stores/community", () => ({+ useCommunityStore: Object.assign(vi.fn(), {+ getState: () => ({ reset: mocks.communityReset }),+ }),+}))+vi.mock("@/stores/community/ws", () => ({+ useOnlineUserIds: () => new Set(["self", "remote"]),+ useCommunityWsStore: Object.assign(vi.fn(), {+ getState: () => ({ setUserStatus: mocks.setUserStatus, reset: mocks.wsReset }),+ }),+}))+vi.mock("@/stores/community/message-stream", () => ({+ useMessageStreamStore: Object.assign(vi.fn(), {+ getState: () => ({ resetAll: mocks.streamReset }),+ }),+}))+vi.mock("@/hooks/community/use-friends", () => ({+ useFriends: () => ({ friends: [{ id: "remote", userId: "remote", name: "Remote", avatar: "R", sub: "seed" }] }),+}))+vi.mock("@/hooks/community/use-server-members", () => ({+ useServerMembers: () => ({ members: [{ id: "remote", userId: "remote", name: "Remote", avatar: "R", sub: "seed" }] }),+}))+vi.mock("@/hooks/community/mutations", () => ({+ useCreateOrGetDm: () => ({ mutateAsync: mocks.createDm }),+ useUpdateProfile: () => ({ mutateAsync: mocks.updateProfile }),+ useUploadUserAvatar: () => ({ mutate: mocks.uploadAvatar }),+}))+vi.mock("@/hooks/community/use-dm-message-sender", () => ({+ useDmMessageSender: () => ({ accept: mocks.acceptDm }),+}))+vi.mock("@/components/community/social/profile-lookup", () => ({+ resolveProfileServerId: (_view: string, id?: string) => id,+ resolveProfileContextLabel: () => "Server member",+ resolveProfileTarget: (members: Array<{ userId: string; name: string }>, _friends: unknown, target: { name: string; userId?: string }) =>+ members.find((member) => member.userId === target.userId || member.name === target.name),+ resolveProfileUserId: (member?: { userId: string }, target?: string) => member?.userId ?? target,+ buildSelfProfile: (user: { id: string; name: string; avatar: string }) => ({+ name: user.name,+ userId: user.id,+ avatar: user.avatar,+ about: "About",+ mutual: 0,+ presence: "online",+ }),+}))+vi.mock("@/lib/community/presence", () => ({ resolveProfilePresence: () => "online" }))+vi.mock("@/lib/community/avatar", () => ({ avatarInitial: () => "?" }))+vi.mock("@/lib/query-persister", () => ({ clearPersistedCache: mocks.clearCache }))+vi.mock("@/lib/auth-client", () => ({ signOut: mocks.signOut }))++type Result = ReturnType<typeof useShellProfileController>++function Capture({ options, onResult }: {+ options: Parameters<typeof useShellProfileController>[0]+ onResult: (result: Result) => void+}) {+ onResult(useShellProfileController(options))+ return null+}++async function renderController() {+ const pushed: string[] = []+ const router = {+ push: (href: string) => { pushed.push(href) },+ replace: vi.fn(),+ prefetch: vi.fn(),+ }+ const cancelPendingNavigation = vi.fn()+ const queryClient = { fetchQuery: mocks.fetchQuery }+ let current!: Result+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(createElement(Capture, {+ options: {+ router,+ queryClient,+ cancelPendingNavigation,+ view: "server",+ activeServerId: "s1",+ } as never,+ onResult: (result) => { current = result },+ }))+ })+ return { get current() { return current }, renderer, router, pushed, cancelPendingNavigation }+}++function deferred<T>() {+ let resolve!: (value: T) => void+ const promise = new Promise<T>((done) => { resolve = done })+ return { promise, resolve }+}++describe("useShellProfileController", () => {+ beforeEach(() => {+ for (const mock of Object.values(mocks)) {+ if (typeof mock === "function" && "mockReset" in mock) mock.mockReset()+ }+ mocks.validate.mockReturnValue({ ok: true })+ mocks.updateProfile.mockResolvedValue({})+ mocks.clearCache.mockResolvedValue(undefined)+ mocks.signOut.mockResolvedValue(undefined)+ })++ afterEach(() => {+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+ })++ it("opens self synchronously only for the exact target id", async () => {+ const hook = await renderController()+ await act(async () => hook.current.openProfile("Self", { clientX: 2, clientY: 3 } as never, undefined, "self"))+ expect(hook.current.profile?.data.userId).toBe("self")+ expect(hook.current.profile?.x).toBe(2)+ expect(mocks.fetchQuery).not.toHaveBeenCalled()+ })++ it("does not infer self from matching name or discriminator", async () => {+ const hook = await renderController()+ await act(async () => hook.current.openProfile(+ "Self",+ { clientX: 6, clientY: 7 } as never,+ "0001",+ ))++ expect(hook.current.profile?.data.name).toBe("Self")+ expect(hook.current.profile?.data.userId).toBeUndefined()+ expect(hook.current.profile?.initialStatusEmoji).toBeNull()+ expect(mocks.fetchQuery).not.toHaveBeenCalled()+ })++ it("opens a remote seed before fetch and hydrates only card state", async () => {+ const response = deferred<{+ aboutMe: string+ mutualServers: number+ discriminator: string+ statusEmoji: string | null+ statusText: string | null+ }>()+ mocks.fetchQuery.mockReturnValue(response.promise)+ const hook = await renderController()+ await act(async () => hook.current.openProfile("Remote", { clientX: 4, clientY: 5 } as never, undefined, "remote"))+ expect(hook.current.profile?.data.about).toBe("seed")+ expect(mocks.fetchQuery).toHaveBeenCalledWith(expect.objectContaining({+ staleTime: 300_000,+ }))++ await act(async () => response.resolve({+ aboutMe: "hydrated",+ mutualServers: 3,+ discriminator: "1234",+ statusEmoji: "🌱",+ statusText: "Growing",+ }))+ expect(hook.current.profile?.data).toMatchObject({+ about: "hydrated",+ mutual: 3,+ discriminator: "1234",+ })+ expect(hook.current.profile?.initialStatusEmoji).toBe("🌱")+ expect(mocks.setUserStatus).not.toHaveBeenCalled()+ })++ it("opens empty-text DMs, does not await accepted commits, and blocks rejected sends", async () => {+ mocks.createDm.mockResolvedValue({ conversation: { id: "dm1" } })+ const hook = await renderController()+ await act(async () => hook.current.profileMessage("remote", " "))+ expect(mocks.acceptDm).not.toHaveBeenCalled()+ expect(hook.pushed).toEqual(["/c/me/dm1"])++ hook.pushed.length = 0+ mocks.acceptDm.mockReturnValue({ accepted: false })+ await act(async () => hook.current.profileMessage("remote", "hello"))+ expect(mocks.toast).toHaveBeenLastCalledWith("Failed to send message")+ expect(hook.pushed).toEqual([])++ const never = new Promise<void>(() => {})+ mocks.acceptDm.mockReturnValue({ accepted: true, committed: never })+ await act(async () => hook.current.profileMessage("remote", "hello"))+ expect(hook.pushed).toEqual(["/c/me/dm1"])+ })++ it("writes own status and UserSettings saves to current-user and WS state after mutation", async () => {+ const order: string[] = []+ mocks.updateProfile.mockImplementation(async () => { order.push("mutate") })+ mocks.setCurrentUser.mockImplementation(() => { order.push("current-user") })+ mocks.setUserStatus.mockImplementation(() => { order.push("ws") })+ const hook = await renderController()++ await act(async () => hook.current.updateOwnStatus("🌱", "Growing"))+ expect(order).toEqual(["mutate", "current-user", "ws"])+ expect(mocks.updateProfile).toHaveBeenLastCalledWith({+ statusEmoji: "🌱",+ statusText: "Growing",+ })+ const statusUpdater = mocks.setCurrentUser.mock.calls.at(-1)![0]+ expect(statusUpdater(mocks.currentUser)).toMatchObject({+ statusEmoji: "🌱",+ statusText: "Growing",+ })+ expect(mocks.setUserStatus).toHaveBeenLastCalledWith("self", "🌱", "Growing")++ order.length = 0+ await act(async () => hook.current.userSettingsProps.onSave({+ name: "Renamed",+ aboutMe: "Updated",+ statusEmoji: "🚀",+ statusText: "Shipping",+ }))+ expect(order).toEqual(["mutate", "current-user", "ws"])+ const settingsUpdater = mocks.setCurrentUser.mock.calls.at(-1)![0]+ expect(settingsUpdater(mocks.currentUser)).toMatchObject({+ name: "Renamed",+ aboutMe: "Updated",+ statusEmoji: "🚀",+ statusText: "Shipping",+ })+ expect(mocks.setUserStatus).toHaveBeenLastCalledWith("self", "🚀", "Shipping")++ mocks.setUserStatus.mockClear()+ await act(async () => hook.current.userSettingsProps.onSave({ aboutMe: "About only" }))+ expect(mocks.setUserStatus).not.toHaveBeenCalled()++ const statusError = new Error("status")+ mocks.updateProfile.mockRejectedValueOnce(statusError)+ await act(async () => hook.current.updateOwnStatus(null, null))+ expect(mocks.toastApiError).toHaveBeenLastCalledWith(statusError, "Failed to update status")++ const saveError = new Error("save")+ mocks.updateProfile.mockRejectedValueOnce(saveError)+ await act(async () => hook.current.userSettingsProps.onSave({ name: "Broken" }))+ expect(mocks.toastApiError).toHaveBeenLastCalledWith(saveError, "Failed to save profile")+ })++ it("preserves logout ordering and rejection behavior", async () => {+ const order: string[] = []+ const hook = await renderController()+ hook.cancelPendingNavigation.mockImplementation(() => { order.push("cancel") })+ mocks.communityReset.mockImplementation(() => { order.push("community") })+ mocks.wsReset.mockImplementation(() => { order.push("ws") })+ mocks.streamReset.mockImplementation(() => { order.push("stream") })+ mocks.clearCache.mockImplementation(async () => { order.push("cache"); throw new Error("cache") })+ mocks.signOut.mockImplementation(async () => { order.push("signOut") })+ hook.router.push = (href: string) => { order.push(`push:${href}`) }+ await act(async () => hook.current.userSettingsProps.onLogout())+ expect(order).toEqual(["cancel", "community", "ws", "stream", "cache", "signOut", "push:/sign-in"])++ order.length = 0+ mocks.clearCache.mockResolvedValue(undefined)+ mocks.signOut.mockRejectedValue(new Error("auth"))+ await expect(act(async () => hook.current.userSettingsProps.onLogout())).rejects.toThrow("auth")+ expect(order.some((entry) => entry.startsWith("push:"))).toBe(false)+ })++ it("starts avatar upload before revoking exactly once", async () => {+ const order: string[] = []+ let input: { files?: File[]; onchange?: () => void; click: () => void } | undefined+ vi.stubGlobal("document", {+ createElement: () => {+ input = { click: vi.fn() }+ return input+ },+ })+ vi.stubGlobal("URL", {+ createObjectURL: vi.fn(() => "blob:avatar"),+ revokeObjectURL: vi.fn(() => { order.push("revoke") }),+ })+ mocks.uploadAvatar.mockImplementation(() => { order.push("upload") })+ const hook = await renderController()+ await act(async () => hook.current.userSettingsProps.onUploadAvatar())+ input!.files = [new File(["image"], "avatar.png", { type: "image/png" })]+ await act(async () => input!.onchange?.())+ expect(hook.current.pendingAvatarCrop?.imageSrc).toBe("blob:avatar")+ expect(URL.createObjectURL).toHaveBeenCalledTimes(1)+ await act(async () => hook.current.pendingAvatarCrop?.onCropped(+ new File(["crop"], "avatar.png", { type: "image/png" }),+ ))+ expect(order).toEqual(["upload", "revoke"])+ expect(URL.revokeObjectURL).toHaveBeenCalledTimes(1)+ expect(hook.current.pendingAvatarCrop).toBeNull()++ vi.spyOn(Date, "now").mockReturnValue(123)+ const uploadOptions = mocks.uploadAvatar.mock.calls[0]![1]+ await act(async () => uploadOptions.onSuccess({ url: "/avatar.png" }))+ const avatarUpdater = mocks.setCurrentUser.mock.calls.at(-1)![0]+ expect(avatarUpdater(mocks.currentUser).avatar).toBe("/avatar.png?t=123")+ expect(mocks.toast).toHaveBeenLastCalledWith("Avatar updated")++ const uploadError = new Error("upload")+ uploadOptions.onError(uploadError)+ expect(mocks.toastApiError).toHaveBeenLastCalledWith(+ uploadError,+ "Failed to upload avatar",+ )+ })++ it("rejects invalid avatar files before object URL creation", async () => {+ let input: { files?: File[]; onchange?: () => void; click: () => void } | undefined+ const createObjectURL = vi.fn(() => "blob:invalid")+ vi.stubGlobal("document", {+ createElement: () => {+ input = { click: vi.fn() }+ return input+ },+ })+ vi.stubGlobal("URL", { createObjectURL, revokeObjectURL: vi.fn() })+ mocks.validate.mockReturnValue({ ok: false, error: "Choose a smaller image" })+ const hook = await renderController()++ await act(async () => hook.current.userSettingsProps.onUploadAvatar())+ input!.files = [new File(["large"], "large.png", { type: "image/png" })]+ await act(async () => input!.onchange?.())+ expect(mocks.toast).toHaveBeenLastCalledWith("Choose a smaller image")+ expect(createObjectURL).not.toHaveBeenCalled()+ expect(hook.current.pendingAvatarCrop).toBeNull()+ })++ it("cancels avatar crop with one revoke and no upload", async () => {+ let input: { files?: File[]; onchange?: () => void; click: () => void } | undefined+ const revokeObjectURL = vi.fn()+ vi.stubGlobal("document", {+ createElement: () => {+ input = { click: vi.fn() }+ return input+ },+ })+ vi.stubGlobal("URL", {+ createObjectURL: vi.fn(() => "blob:cancel"),+ revokeObjectURL,+ })+ const hook = await renderController()++ await act(async () => hook.current.userSettingsProps.onUploadAvatar())+ input!.files = [new File(["image"], "avatar.png", { type: "image/png" })]+ await act(async () => input!.onchange?.())+ await act(async () => hook.current.pendingAvatarCrop?.onCancel())++ expect(mocks.uploadAvatar).not.toHaveBeenCalled()+ expect(revokeObjectURL).toHaveBeenCalledTimes(1)+ expect(revokeObjectURL).toHaveBeenCalledWith("blob:cancel")+ expect(hook.current.pendingAvatarCrop).toBeNull()+ })+})diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.ts b/src/web/src/components/community/shell/use-shell-profile-controller.tsnew file mode 100644index 000000000..cd22c25a6--- /dev/null+++ b/src/web/src/components/community/shell/use-shell-profile-controller.ts@@ -0,0 +1,320 @@+"use client"++import { useCallback, useState, type ComponentProps } from "react"+import { toast } from "sonner"+import { toastApiError } from "@/lib/api/client"+import { communityKeys } from "@/lib/query-keys"+import { userProfileQueryFn, PROFILE_STALE_TIME_MS } from "@/hooks/community/use-user-profile"+import { validateIconSourceFile } from "@/lib/community/image-crop"+import type { FileAttachment, ImagePreview } from "@/lib/community/models/message"+import type { Profile } from "@/components/community/social/profile-types"+import {+ resolveProfileContextLabel,+ resolveProfileServerId,+ resolveProfileTarget,+ resolveProfileUserId,+ buildSelfProfile,+} from "@/components/community/social/profile-lookup"+import { resolveProfilePresence } from "@/lib/community/presence"+import { avatarInitial } from "@/lib/community/avatar"+import { signOut } from "@/lib/auth-client"+import { clearPersistedCache } from "@/lib/query-persister"+import { useCommunityStore } from "@/stores/community"+import { useCommunityWsStore, useOnlineUserIds } from "@/stores/community/ws"+import { useMessageStreamStore } from "@/stores/community/message-stream"+import { useCurrentUser, useSetCurrentUser } from "@/contexts/community/current-user"+import { useFriends } from "@/hooks/community/use-friends"+import { useServerMembers } from "@/hooks/community/use-server-members"+import {+ useCreateOrGetDm,+ useUpdateProfile,+ useUploadUserAvatar,+} from "@/hooks/community/mutations"+import { useDmMessageSender } from "@/hooks/community/use-dm-message-sender"+import type { UserSettings } from "@/components/community/settings/user-settings"+import type { ImageCropDialog } from "@/components/community/image-crop-dialog"+import type { QueryClient } from "@tanstack/react-query"+import type { ShellFrameProps, ShellRouter } from "./shell-frame-types"++export type ShellProfileState = {+ data: Profile+ x: number+ y: number+ initialStatusEmoji: string | null+ initialStatusText: string | null+}++type Options = Pick<ShellFrameProps, "view" | "activeServerId"> & {+ router: ShellRouter+ queryClient: QueryClient+ cancelPendingNavigation: () => void+}++export function useShellProfileController({+ router,+ queryClient,+ cancelPendingNavigation,+ view,+ activeServerId,+}: Options) {+ const currentUser = useCurrentUser()+ const setCurrentUser = useSetCurrentUser()+ const onlineUserIds = useOnlineUserIds()+ const { friends } = useFriends()+ const profileServerId = resolveProfileServerId(view, activeServerId)+ const { members } = useServerMembers(profileServerId)+ const createOrGetDm = useCreateOrGetDm()+ const { accept: acceptDmMessage } = useDmMessageSender()+ const updateProfile = useUpdateProfile()+ const uploadUserAvatar = useUploadUserAvatar()++ const [editingProfile, setEditingProfile] = useState(false)+ const [profile, setProfile] = useState<ShellProfileState | null>(null)+ const [preview, setPreview] = useState<ImagePreview | null>(null)+ const [attachmentPreview, setAttachmentPreview] = useState<FileAttachment | null>(null)+ const [pendingAvatarCrop, setPendingAvatarCrop] = useState<{+ src: string+ fileName: string+ } | null>(null)++ const openProfile = useCallback((+ name: string,+ event: React.MouseEvent,+ discriminator?: string,+ targetUserId?: string,+ ) => {+ const isSelf = !!targetUserId && targetUserId === currentUser.id+ if (isSelf) {+ const selfMember = profileServerId+ ? members.find((member) => member.userId === currentUser.id)+ : undefined+ setProfile({+ data: buildSelfProfile(+ currentUser,+ onlineUserIds,+ resolveProfileContextLabel(profileServerId, selfMember),+ ),+ x: event.clientX,+ y: event.clientY,+ initialStatusEmoji: currentUser.statusEmoji ?? null,+ initialStatusText: currentUser.statusText ?? null,+ })+ return+ }++ const member = resolveProfileTarget(members, friends, {+ name,+ discriminator,+ userId: targetUserId,+ })+ const about = member?.sub ?? ""+ const userId = resolveProfileUserId(member, targetUserId)+ setProfile({+ data: {+ name,+ userId,+ avatar: member?.avatar ?? avatarInitial(name),+ contextLabel: resolveProfileContextLabel(profileServerId, member),+ about,+ mutual: 0,+ presence: resolveProfilePresence(false, userId, onlineUserIds),+ },+ x: event.clientX,+ y: event.clientY,+ initialStatusEmoji: member?.statusEmoji ?? null,+ initialStatusText: member?.statusText ?? null,+ })+ if (userId) {+ queryClient+ .fetchQuery({+ queryKey: communityKeys.profile(userId),+ queryFn: userProfileQueryFn(userId),+ staleTime: PROFILE_STALE_TIME_MS,+ })+ .then((profileResponse) => {+ setProfile((previous) =>+ previous+ ? {+ ...previous,+ data: {+ ...previous.data,+ about: profileResponse.aboutMe ?? previous.data.about,+ mutual: profileResponse.mutualServers ?? 0,+ discriminator: profileResponse.discriminator ?? previous.data.discriminator,+ },+ initialStatusEmoji: profileResponse.statusEmoji,+ initialStatusText: profileResponse.statusText,+ }+ : previous,+ )+ })+ .catch((error) => toastApiError(error, "Failed to load profile"))+ }+ }, [currentUser, friends, members, onlineUserIds, profileServerId, queryClient])++ const previewImage = useCallback((image: ImagePreview) => setPreview(image), [])+ const previewAttachment = useCallback(+ (attachment: FileAttachment) => setAttachmentPreview(attachment),+ [],+ )++ const updateOwnStatus = async (statusEmoji: string | null, statusText: string | null) => {+ try {+ await updateProfile.mutateAsync({ statusEmoji, statusText })+ setCurrentUser((user) => ({ ...user, statusEmoji, statusText }))+ useCommunityWsStore.getState().setUserStatus(+ currentUser.id,+ statusEmoji,+ statusText,+ )+ } catch (error) {+ toastApiError(error, "Failed to update status")+ }+ }++ const profileMessage = async (userId: string, text: string) => {+ if (!userId) {+ toast("Could not find user")+ return+ }+ let dmId: string+ try {+ const data = await createOrGetDm.mutateAsync({ userId })+ dmId = data.conversation.id+ } catch (error) {+ toastApiError(error, "Failed to open DM")+ return+ }+ const trimmed = text.trim()+ if (trimmed) {+ const receipt = acceptDmMessage({+ dmId,+ content: trimmed,+ author: {+ id: currentUser.id,+ name: currentUser.name,+ avatar: currentUser.avatar,+ },+ })+ if (!receipt.accepted) {+ toast("Failed to send message")+ return+ }+ void receipt.committed+ }+ cancelPendingNavigation()+ router.push(`/c/me/${dmId}`)+ }++ const onUploadAvatar = () => {+ const input = document.createElement("input")+ input.type = "file"+ input.accept = "image/png,image/jpeg,image/webp"+ input.onchange = () => {+ const file = input.files?.[0]+ if (!file) return+ const check = validateIconSourceFile(file)+ if (!check.ok) {+ toast(check.error)+ return+ }+ setPendingAvatarCrop({ src: URL.createObjectURL(file), fileName: file.name })+ }+ input.click()+ }++ const onSaveProfile: ComponentProps<typeof UserSettings>["onSave"] = async (data) => {+ try {+ await updateProfile.mutateAsync(data)+ setCurrentUser((user) => ({+ ...user,+ ...(data.name ? { name: data.name } : {}),+ ...(data.aboutMe !== undefined ? { aboutMe: data.aboutMe } : {}),+ ...(data.statusEmoji !== undefined ? { statusEmoji: data.statusEmoji } : {}),+ ...(data.statusText !== undefined ? { statusText: data.statusText } : {}),+ }))+ if (data.statusEmoji !== undefined || data.statusText !== undefined) {+ useCommunityWsStore.getState().setUserStatus(+ currentUser.id,+ data.statusEmoji ?? null,+ data.statusText ?? null,+ )+ }+ } catch (error) {+ toastApiError(error, "Failed to save profile")+ }+ }++ const onLogout = async () => {+ cancelPendingNavigation()+ useCommunityStore.getState().reset()+ useCommunityWsStore.getState().reset()+ useMessageStreamStore.getState().resetAll()+ await clearPersistedCache(currentUser.id).catch(() => {})+ await signOut()+ router.push("/sign-in")+ }++ const userSettingsProps: ComponentProps<typeof UserSettings> = {+ onClose: () => setEditingProfile(false),+ userId: currentUser.id,+ userName: currentUser.name,+ aboutMe: currentUser.aboutMe ?? "",+ avatar: currentUser.avatar,+ statusEmoji: currentUser.statusEmoji,+ statusText: currentUser.statusText,+ onUploadAvatar,+ onSave: onSaveProfile,+ onLogout,+ }++ let pendingAvatarCropProps: Omit<ComponentProps<typeof ImageCropDialog>, "maskShape"> | null = null+ if (pendingAvatarCrop) {+ pendingAvatarCropProps = {+ imageSrc: pendingAvatarCrop.src,+ originalFileName: pendingAvatarCrop.fileName,+ onCropped: (file) => {+ uploadUserAvatar.mutate(+ { file },+ {+ onSuccess: (data) => {+ setCurrentUser((user) => ({ ...user, avatar: `${data.url}?t=${Date.now()}` }))+ toast("Avatar updated")+ },+ onError: (error) => toastApiError(error, "Failed to upload avatar"),+ },+ )+ URL.revokeObjectURL(pendingAvatarCrop.src)+ setPendingAvatarCrop(null)+ },+ onCancel: () => {+ URL.revokeObjectURL(pendingAvatarCrop.src)+ setPendingAvatarCrop(null)+ },+ }+ }++ return {+ currentUser,+ openProfile,+ previewImage,+ previewAttachment,+ profile,+ closeProfile: () => setProfile(null),+ profileMessage,+ updateOwnStatus,+ preview,+ closePreview: () => setPreview(null),+ attachmentPreview,+ onAttachmentPreviewOpenChange: (open: boolean) => {+ if (!open) setAttachmentPreview(null)+ },+ editingProfile,+ openUserSettings: () => setEditingProfile(true),+ onUserSettingsOpenChange: (open: boolean) => {+ if (!open) setEditingProfile(false)+ },+ userSettingsProps,+ pendingAvatarCrop: pendingAvatarCropProps,+ }+}diff --git a/src/web/src/components/community/shell/use-shell-rail-controller.test.ts b/src/web/src/components/community/shell/use-shell-rail-controller.test.tsnew file mode 100644index 000000000..f7260ad13--- /dev/null+++ b/src/web/src/components/community/shell/use-shell-rail-controller.test.ts@@ -0,0 +1,399 @@+import { createElement } from "react"+import TestRenderer, { act } from "react-test-renderer"+import { beforeEach, describe, expect, it, vi } from "vitest"+import { useShellRailController } from "./use-shell-rail-controller"++const mocks = vi.hoisted(() => ({+ servers: [{ id: "s1", name: "One" }, { id: "s2", name: "Two" }],+ folders: [],+ createServer: vi.fn(),+ leaveServer: vi.fn(),+ uploadIcon: vi.fn(),+ deleteFolder: vi.fn(),+ reorderServers: vi.fn(),+ reorderFolders: vi.fn(),+ updateFolderItems: vi.fn(),+ createFolder: vi.fn(),+ markVoluntaryLeave: vi.fn(),+ markSwitch: vi.fn(),+ toast: vi.fn(),+ toastApiError: vi.fn(),+}))++vi.mock("sonner", () => ({ toast: mocks.toast }))+vi.mock("@/lib/api/client", () => ({ toastApiError: mocks.toastApiError }))+vi.mock("@/lib/perf/switch-mark", () => ({ markSwitch: mocks.markSwitch }))+vi.mock("@/lib/community/eject-server", () => ({+ markVoluntaryLeave: mocks.markVoluntaryLeave,+ pickPostEjectDestination: () => "/c/me",+}))+vi.mock("@/hooks/community/use-servers", () => ({+ useServers: () => ({+ servers: mocks.servers,+ isLoading: false,+ }),+ serverQueryFn: (id: string) => () => Promise.resolve({ id }),+}))+vi.mock("@/hooks/community/use-folders", () => ({ useFolders: () => ({ folders: mocks.folders }) }))+vi.mock("@/hooks/community/mutations", () => ({+ useCreateServer: () => ({ mutateAsync: mocks.createServer }),+ useLeaveServer: () => ({ mutate: mocks.leaveServer }),+ useUploadServerIcon: () => ({ mutate: mocks.uploadIcon }),+ useDeleteServerFolder: () => ({ mutate: mocks.deleteFolder }),+ useReorderServers: () => ({ mutate: mocks.reorderServers }),+ useReorderFolders: () => ({ mutate: mocks.reorderFolders }),+ useUpdateFolderItems: () => ({ mutate: mocks.updateFolderItems }),+ useCreateServerFolderWith: () => ({ mutate: mocks.createFolder }),+}))+vi.mock("@/stores/community", () => ({+ useCommunityStore: (selector: (state: { currentServerId: string }) => unknown) =>+ selector({ currentServerId: "s1" }),+}))+vi.mock("@/lib/community/last-channel", () => ({+ getLastChannel: () => null,+ pickServerLandingHref: (id: string, channelIds: string[]) =>+ channelIds[0] ? `/c/channels/${id}/${channelIds[0]}` : `/c/channels/${id}`,+}))+vi.mock("@/lib/community/last-me-location", () => ({+ getLastMeLeaf: () => null,+ pickMeLandingLocation: () => "/c/me",+}))++type Result = ReturnType<typeof useShellRailController>++function Capture({ options, onResult }: {+ options: Parameters<typeof useShellRailController>[0]+ onResult: (result: Result) => void+}) {+ onResult(useShellRailController(options))+ return null+}++function deferred() {+ let resolve!: () => void+ const promise = new Promise<void>((done) => { resolve = done })+ return { promise, resolve }+}++async function renderController(overrides: Record<string, unknown> = {}) {+ const pushed: string[] = []+ const replaced: string[] = []+ const prefetched: string[] = []+ const router = {+ push: (href: string) => { pushed.push(href) },+ replace: (href: string) => { replaced.push(href) },+ prefetch: (href: string) => { prefetched.push(href) },+ }+ const cache = new Map<string, unknown>()+ const queryClient = {+ getQueryData: vi.fn((key: unknown[]) => cache.get(String(key.at(-1)))),+ fetchQuery: vi.fn(),+ }+ const options = {+ router,+ pathname: "/c/channels/s1",+ queryClient,+ view: "server",+ activeServerId: "s1",+ setMobileZone: vi.fn(),+ goHome: vi.fn(),+ goServer: vi.fn(),+ ...overrides,+ } as never+ let current!: Result+ let renderer!: TestRenderer.ReactTestRenderer+ const onResult = (result: Result) => { current = result }+ await act(async () => {+ renderer = TestRenderer.create(createElement(Capture, {+ options,+ onResult,+ }))+ })+ return {+ get current() { return current },+ renderer,+ options,+ router,+ queryClient,+ cache,+ pushed,+ replaced,+ prefetched,+ async rerender() {+ await act(async () => {+ renderer.update(createElement(Capture, { options, onResult }))+ })+ },+ }+}++describe("useShellRailController", () => {+ beforeEach(() => {+ for (const mock of Object.values(mocks)) {+ if (typeof mock === "function" && "mockReset" in mock) mock.mockReset()+ }+ })++ it("commits only the latest deferred server navigation", async () => {+ const first = deferred()+ const second = deferred()+ const hook = await renderController()+ hook.queryClient.fetchQuery.mockImplementation(({ queryKey }: { queryKey: unknown[] }) => {+ const id = String(queryKey.at(-1))+ return id === "s1" ? first.promise : second.promise+ })++ await act(async () => {+ hook.current.railProps.onServerNavigate("s1")+ hook.current.railProps.onServerNavigate("s2")+ })+ hook.cache.set("s2", { categories: [{ channels: [{ id: "c2", pending: false }] }] })+ await act(async () => second.resolve())+ hook.cache.set("s1", { categories: [{ channels: [{ id: "c1", pending: false }] }] })+ await act(async () => first.resolve())++ expect(hook.pushed).toEqual(["/c/channels/s2/c2"])+ expect(mocks.markSwitch).toHaveBeenNthCalledWith(1, "server", "s1")+ expect(mocks.markSwitch).toHaveBeenNthCalledWith(2, "server", "s2")+ })++ it("supersedes pending navigation on pathname changes and direct channel navigation", async () => {+ const pathnamePending = deferred()+ const channelPending = deferred()+ const hook = await renderController()+ hook.queryClient.fetchQuery.mockReturnValueOnce(pathnamePending.promise)++ await act(async () => hook.current.railProps.onServerNavigate("s2"))+ hook.options.pathname = "/c/me"+ await hook.rerender()+ hook.cache.set("s2", { categories: [{ channels: [{ id: "late", pending: false }] }] })+ await act(async () => pathnamePending.resolve())+ expect(hook.pushed).toEqual([])++ hook.cache.delete("s2")+ hook.queryClient.fetchQuery.mockReturnValueOnce(channelPending.promise)+ await act(async () => {+ hook.current.railProps.onServerNavigate("s2")+ hook.current.navigate("s1", "c1")+ })+ hook.cache.set("s2", { categories: [{ channels: [{ id: "late-again", pending: false }] }] })+ await act(async () => channelPending.resolve())+ expect(hook.pushed).toEqual(["/c/channels/s1/c1"])+ expect(mocks.markSwitch).toHaveBeenLastCalledWith("channel", "c1")+ })++ it("cancels pending navigation for settings and invite actions", async () => {+ const pending = deferred()+ const invitePending = deferred()+ const openSettings = vi.fn()+ const openInvite = vi.fn()+ const hook = await renderController({+ onOpenActiveServerSettings: openSettings,+ onOpenActiveServerInvite: openInvite,+ })+ hook.queryClient.fetchQuery.mockReturnValue(pending.promise)++ await act(async () => {+ hook.current.railProps.onServerNavigate("s2")+ hook.current.railProps.onOpenSettings("s1")+ })+ expect(openSettings).toHaveBeenCalledTimes(1)+ expect(hook.pushed).toEqual([])+ hook.cache.set("s2", { categories: [{ channels: [{ id: "late", pending: false }] }] })+ await act(async () => pending.resolve())+ expect(hook.pushed).toEqual([])++ hook.cache.delete("s2")+ hook.queryClient.fetchQuery.mockReturnValueOnce(invitePending.promise)+ await act(async () => {+ hook.current.railProps.onServerNavigate("s2")+ hook.current.railProps.onOpenInvitePopover("s1")+ })+ expect(openInvite).toHaveBeenCalledTimes(1)+ hook.cache.set("s2", { categories: [{ channels: [{ id: "invite-late", pending: false }] }] })+ await act(async () => invitePending.resolve())+ expect(hook.pushed).toEqual([])+ await act(async () => hook.current.railProps.onOpenSettings("s2"))+ await act(async () => hook.current.railProps.onOpenInvitePopover("s2"))+ expect(hook.pushed).toEqual([+ "/c/channels/s2?settings=1",+ "/c/channels/s2?invite=1",+ ])++ hook.pushed.length = 0+ await act(async () => {+ hook.current.railProps.onOpenSettings(undefined)+ hook.current.railProps.onOpenInvitePopover(undefined)+ })+ expect(hook.pushed).toEqual([])+ })++ it("cancels pending navigation before invoking the home callback", async () => {+ const pending = deferred()+ const goHome = vi.fn()+ const hook = await renderController({ goHome })+ hook.queryClient.fetchQuery.mockReturnValue(pending.promise)++ await act(async () => {+ hook.current.railProps.onServerNavigate("s2")+ hook.current.railProps.onHome()+ })+ expect(goHome).toHaveBeenCalledTimes(1)+ hook.cache.set("s2", { categories: [{ channels: [{ id: "late", pending: false }] }] })+ await act(async () => pending.resolve())+ expect(hook.pushed).toEqual([])+ })++ it("uses cached and fetched destinations for navigation and prefetch fallbacks", async () => {+ const hook = await renderController()+ hook.cache.set("s1", {+ categories: [{ channels: [{ id: "pending", pending: true }, { id: "cached", pending: false }] }],+ })++ await act(async () => hook.current.railProps.onServerNavigate("s1"))+ await act(async () => hook.current.railProps.onServerPrefetch("s1"))+ await act(async () => hook.current.railProps.onHomePrefetch())+ expect(hook.pushed).toEqual(["/c/channels/s1/cached"])+ expect(hook.prefetched).toEqual(["/c/channels/s1/cached", "/c/me"])+ expect(hook.queryClient.fetchQuery).not.toHaveBeenCalled()++ hook.queryClient.fetchQuery.mockImplementationOnce(async ({ queryKey }: { queryKey: unknown[] }) => {+ const id = String(queryKey.at(-1))+ hook.cache.set(id, { categories: [{ channels: [{ id: "fetched", pending: false }] }] })+ })+ await act(async () => hook.current.railProps.onServerNavigate("s2"))+ expect(hook.pushed).toContain("/c/channels/s2/fetched")+ expect(hook.queryClient.fetchQuery).toHaveBeenLastCalledWith(expect.objectContaining({+ queryKey: expect.any(Array),+ queryFn: expect.any(Function),+ staleTime: Infinity,+ }))++ hook.queryClient.fetchQuery.mockRejectedValueOnce(new Error("offline"))+ await act(async () => hook.current.railProps.onServerPrefetch("s3"))+ expect(hook.prefetched).toContain("/c/channels/s3")+ })++ it("keeps callback fields stable without stabilizing the railProps aggregate", async () => {+ const hook = await renderController()+ const firstProps = hook.current.railProps+ const callbacks = {+ onHome: firstProps.onHome,+ onServerNavigate: firstProps.onServerNavigate,+ onCreateServer: firstProps.onCreateServer,+ onLeaveServer: firstProps.onLeaveServer,+ }+ await hook.rerender()+ expect(hook.current.railProps).not.toBe(firstProps)+ expect(hook.current.railProps.onHome).toBe(callbacks.onHome)+ expect(hook.current.railProps.onServerNavigate).toBe(callbacks.onServerNavigate)+ expect(hook.current.railProps.onCreateServer).toBe(callbacks.onCreateServer)+ expect(hook.current.railProps.onLeaveServer).toBe(callbacks.onLeaveServer)+ })++ it("preserves create and leave side-effect ordering", async () => {+ const order: string[] = []+ mocks.createServer.mockImplementation(async () => {+ order.push("create")+ return { server: { id: "new" } }+ })+ mocks.toast.mockImplementation(() => { order.push("toast") })+ const hook = await renderController()+ hook.router.push = (href: string) => { order.push(`push:${href}`) }+ await act(async () => hook.current.railProps.onCreateServer("New"))+ expect(order).toEqual(["create", "toast", "push:/c/channels/new"])++ order.length = 0+ mocks.markVoluntaryLeave.mockImplementation(() => { order.push("mark") })+ mocks.leaveServer.mockImplementation((_input, options) => {+ order.push("mutate")+ options.onSuccess()+ })+ hook.router.replace = (href: string) => { order.push(`replace:${href}`) }+ await act(async () => hook.current.railProps.onLeaveServer("s1"))+ expect(order).toEqual(["mark", "mutate", "toast", "replace:/c/me"])+ })++ it("preserves optional icon upload and create/leave error reporting", async () => {+ const file = new File(["icon"], "icon.png", { type: "image/png" })+ const order: string[] = []+ mocks.createServer.mockImplementation(async () => {+ order.push("create")+ return { server: { id: "new" } }+ })+ mocks.toast.mockImplementation(() => { order.push("toast") })+ mocks.uploadIcon.mockImplementation(() => { order.push("upload") })+ const hook = await renderController()+ hook.router.push = (href: string) => { order.push(`push:${href}`) }++ await act(async () => hook.current.railProps.onCreateServer("New", file))+ expect(order).toEqual(["create", "toast", "upload", "push:/c/channels/new"])+ expect(mocks.uploadIcon).toHaveBeenCalledWith(+ { serverId: "new", file },+ expect.objectContaining({ onError: expect.any(Function) }),+ )+ const iconError = new Error("icon")+ mocks.uploadIcon.mock.calls[0]![1].onError(iconError)+ expect(mocks.toastApiError).toHaveBeenCalledWith(+ iconError,+ "Server created, but the icon failed to upload",+ )++ const createError = new Error("create")+ mocks.createServer.mockRejectedValueOnce(createError)+ await act(async () => hook.current.railProps.onCreateServer("Broken"))+ expect(mocks.toastApiError).toHaveBeenCalledWith(createError, "Failed to create server")++ await act(async () => hook.current.railProps.onLeaveServer("s2"))+ const leaveError = new Error("leave")+ mocks.leaveServer.mock.calls.at(-1)![1].onError(leaveError)+ expect(mocks.toastApiError).toHaveBeenCalledWith(leaveError, "Failed to leave server")+ })++ it("preserves folder and ordering mutation payloads and toast callbacks", async () => {+ const hook = await renderController()+ await act(async () => {+ hook.current.railProps.onUngroupFolder("f1")+ hook.current.railProps.onReorderRail(["s2", "s1"])+ hook.current.railProps.onReorderFolders(["f2", "f1"])+ hook.current.railProps.onFolderItemsChange("f1", ["s1", "s2"])+ hook.current.railProps.onDragCreateFolder("s1", "s2")+ })++ expect(mocks.deleteFolder).toHaveBeenCalledWith(+ { folderId: "f1" },+ expect.objectContaining({ onSuccess: expect.any(Function), onError: expect.any(Function) }),+ )+ expect(mocks.reorderServers).toHaveBeenCalledWith(+ { serverIds: ["s2", "s1"] },+ expect.objectContaining({ onError: expect.any(Function) }),+ )+ expect(mocks.reorderFolders).toHaveBeenCalledWith(+ { folderIds: ["f2", "f1"] },+ expect.objectContaining({ onError: expect.any(Function) }),+ )+ expect(mocks.updateFolderItems).toHaveBeenCalledWith(+ { folderId: "f1", serverIds: ["s1", "s2"] },+ expect.objectContaining({ onError: expect.any(Function) }),+ )+ expect(mocks.createFolder).toHaveBeenCalledWith(+ { serverIdA: "s1", serverIdB: "s2" },+ expect.objectContaining({ onError: expect.any(Function) }),+ )++ mocks.deleteFolder.mock.calls[0]![1].onSuccess()+ expect(mocks.toast).toHaveBeenLastCalledWith("Group removed")+ const cases = [+ [mocks.deleteFolder, "Failed to remove group"],+ [mocks.reorderServers, "Failed to save server order"],+ [mocks.reorderFolders, "Failed to reorder groups"],+ [mocks.updateFolderItems, "Failed to update group"],+ [mocks.createFolder, "Failed to create group"],+ ] as const+ for (const [mutation, message] of cases) {+ const error = new Error(message)+ mutation.mock.calls[0]![1].onError(error)+ expect(mocks.toastApiError).toHaveBeenLastCalledWith(error, message)+ }+ })+})diff --git a/src/web/src/components/community/shell/use-shell-rail-controller.ts b/src/web/src/components/community/shell/use-shell-rail-controller.tsnew file mode 100644index 000000000..c6ec30aaa--- /dev/null+++ b/src/web/src/components/community/shell/use-shell-rail-controller.ts@@ -0,0 +1,263 @@+"use client"++import { useCallback, useEffect, useMemo, useRef } from "react"+import { toast } from "sonner"+import { toastApiError } from "@/lib/api/client"+import { communityKeys } from "@/lib/query-keys"+import { markSwitch } from "@/lib/perf/switch-mark"+import { markVoluntaryLeave, pickPostEjectDestination } from "@/lib/community/eject-server"+import { serverQueryFn, useServers, type ServerDetail } from "@/hooks/community/use-servers"+import { useFolders } from "@/hooks/community/use-folders"+import {+ useCreateServer,+ useLeaveServer,+ useUploadServerIcon,+ useDeleteServerFolder,+ useReorderServers,+ useReorderFolders,+ useUpdateFolderItems,+ useCreateServerFolderWith,+} from "@/hooks/community/mutations"+import { getLastChannel, pickServerLandingHref } from "@/lib/community/last-channel"+import { getLastMeLeaf, pickMeLandingLocation } from "@/lib/community/last-me-location"+import {+ commitLatestNavigationIntent,+ createNavigationIntentGate,+ supersedeNavigationIntent,+} from "@/lib/community/navigation-intent"+import { useCommunityStore } from "@/stores/community"+import { resolveServerRailOverlayAction } from "./server-rail-actions"+import type { ShellFrameProps, ShellRouter } from "./shell-frame-types"+import type { QueryClient } from "@tanstack/react-query"++type Options = Pick<+ ShellFrameProps,+ | "view"+ | "activeServerId"+ | "setMobileZone"+ | "onOpenActiveServerSettings"+ | "onOpenActiveServerInvite"+ | "goHome"+ | "goServer"+> & {+ router: ShellRouter+ pathname: string+ queryClient: QueryClient+}++export function useShellRailController({+ router,+ pathname,+ queryClient,+ view,+ activeServerId,+ setMobileZone,+ onOpenActiveServerSettings,+ onOpenActiveServerInvite,+ goHome,+ goServer,+}: Options) {+ const serversQuery = useServers()+ const { servers } = serversQuery+ const { folders } = useFolders()+ const currentServerId = useCommunityStore((state) => state.currentServerId)+ const { mutateAsync: createServerAsync } = useCreateServer()+ const { mutate: leaveServerMutate } = useLeaveServer()+ const { mutate: uploadServerIconMutate } = useUploadServerIcon()+ const { mutate: deleteFolderMutate } = useDeleteServerFolder()+ const { mutate: reorderServersMutate } = useReorderServers()+ const { mutate: reorderFoldersMutate } = useReorderFolders()+ const { mutate: updateFolderItemsMutate } = useUpdateFolderItems()+ const { mutate: createFolderWithMutate } = useCreateServerFolderWith()++ const folderServerIds = useMemo(() => {+ const ids = new Set<string>()+ for (const folder of folders) for (const server of folder.servers) ids.add(server.id)+ return ids+ }, [folders])+ const railServers = useMemo(+ () => servers+ .filter((server) => !folderServerIds.has(server.id))+ .map((server) => ({ ...server, active: server.id === activeServerId })),+ [activeServerId, folderServerIds, servers],+ )++ const navigationGateRef = useRef(createNavigationIntentGate())+ const cancelPendingNavigation = useCallback(() => {+ supersedeNavigationIntent(navigationGateRef.current)+ }, [])+ useEffect(() => {+ cancelPendingNavigation()+ }, [cancelPendingNavigation, pathname])++ const serverDestination = useCallback((id: string) => {+ const detail = queryClient.getQueryData<ServerDetail>(communityKeys.server(id))+ const channelIds = detail?.categories.flatMap((category) =>+ category.channels.filter((channel) => !channel.pending).map((channel) => channel.id)+ ) ?? []+ return pickServerLandingHref(id, channelIds, getLastChannel(id))+ }, [queryClient])+ const resolveServerDestination = useCallback(async (id: string) => {+ const root = `/c/channels/${id}`+ const immediate = serverDestination(id)+ if (immediate !== root) return immediate+ try {+ await queryClient.fetchQuery({+ queryKey: communityKeys.server(id),+ queryFn: serverQueryFn(id),+ staleTime: Infinity,+ })+ } catch {+ return root+ }+ return serverDestination(id)+ }, [queryClient, serverDestination])++ const onServerNavigate = useCallback((id: string) => {+ markSwitch("server", id)+ void commitLatestNavigationIntent(+ navigationGateRef.current,+ () => resolveServerDestination(id),+ (destination) => router.push(destination),+ )+ }, [resolveServerDestination, router])+ const onHome = useCallback(() => {+ cancelPendingNavigation()+ goHome()+ }, [cancelPendingNavigation, goHome])+ const onServerPrefetch = useCallback((id: string) => {+ void resolveServerDestination(id).then((destination) => router.prefetch(destination))+ }, [resolveServerDestination, router])+ const onHomePrefetch = useCallback(+ () => router.prefetch(pickMeLandingLocation(getLastMeLeaf())),+ [router],+ )+ const onCreateServer = useCallback(async (name: string, icon?: File) => {+ try {+ const data = await createServerAsync({ name })+ const newId = data.server.id+ toast(`Server "${name}" created`)+ if (icon) {+ uploadServerIconMutate(+ { serverId: newId, file: icon },+ { onError: (error) => toastApiError(error, "Server created, but the icon failed to upload") },+ )+ }+ cancelPendingNavigation()+ router.push(`/c/channels/${newId}`)+ } catch (error) {+ toastApiError(error, "Failed to create server")+ }+ }, [cancelPendingNavigation, createServerAsync, router, uploadServerIconMutate])+ const onLeaveServer = useCallback((id: string) => {+ markVoluntaryLeave(id)+ leaveServerMutate(+ { serverId: id },+ {+ onSuccess: () => {+ toast("Left server")+ if (currentServerId === id) {+ cancelPendingNavigation()+ router.replace(pickPostEjectDestination(servers, id))+ }+ },+ onError: (error) => toastApiError(error, "Failed to leave server"),+ },+ )+ }, [cancelPendingNavigation, currentServerId, leaveServerMutate, router, servers])+ const onOpenSettings = useCallback((id?: string) => {+ if (!id) return+ cancelPendingNavigation()+ const action = resolveServerRailOverlayAction({+ targetServerId: id,+ activeServerId,+ overlay: "settings",+ hasActiveOpener: !!onOpenActiveServerSettings,+ })+ if (action.kind === "open-active") onOpenActiveServerSettings?.()+ else router.push(action.href)+ }, [activeServerId, cancelPendingNavigation, onOpenActiveServerSettings, router])+ const onOpenInvitePopover = useCallback((id?: string) => {+ if (!id) return+ cancelPendingNavigation()+ const action = resolveServerRailOverlayAction({+ targetServerId: id,+ activeServerId,+ overlay: "invite",+ hasActiveOpener: !!onOpenActiveServerInvite,+ })+ if (action.kind === "open-active") onOpenActiveServerInvite?.()+ else router.push(action.href)+ }, [activeServerId, cancelPendingNavigation, onOpenActiveServerInvite, router])+ const onUngroupFolder = useCallback((folderId: string) => {+ deleteFolderMutate(+ { folderId },+ { onSuccess: () => toast("Group removed"), onError: (error) => toastApiError(error, "Failed to remove group") },+ )+ }, [deleteFolderMutate])+ const onReorderRail = useCallback((serverIds: string[]) => {+ reorderServersMutate(+ { serverIds },+ { onError: (error) => toastApiError(error, "Failed to save server order") },+ )+ }, [reorderServersMutate])+ const onReorderFolders = useCallback((folderIds: string[]) => {+ reorderFoldersMutate(+ { folderIds },+ { onError: (error) => toastApiError(error, "Failed to reorder groups") },+ )+ }, [reorderFoldersMutate])+ const onFolderItemsChange = useCallback((folderId: string, serverIds: string[]) => {+ updateFolderItemsMutate(+ { folderId, serverIds },+ { onError: (error) => toastApiError(error, "Failed to update group") },+ )+ }, [updateFolderItemsMutate])+ const onDragCreateFolder = useCallback((serverIdA: string, serverIdB: string) => {+ createFolderWithMutate(+ { serverIdA, serverIdB },+ { onError: (error) => toastApiError(error, "Failed to create group") },+ )+ }, [createFolderWithMutate])++ const navigate = useCallback((serverId: string, channelId?: string) => {+ markSwitch(channelId ? "channel" : "server", channelId ?? serverId)+ if (channelId) {+ cancelPendingNavigation()+ router.push(`/c/channels/${serverId}/${channelId}`)+ return+ }+ void commitLatestNavigationIntent(+ navigationGateRef.current,+ () => resolveServerDestination(serverId),+ (destination) => router.push(destination),+ )+ }, [cancelPendingNavigation, resolveServerDestination, router])++ return {+ railProps: {+ servers: railServers,+ folders,+ activeServerId,+ serversLoading: serversQuery.isLoading,+ setMobileZone,+ view,+ onHome,+ onHomePrefetch,+ onServer: goServer,+ onServerNavigate,+ onServerPrefetch,+ onCreateServer,+ onLeaveServer,+ onOpenSettings,+ onOpenInvitePopover,+ onUngroupFolder,+ onReorderRail,+ onReorderFolders,+ onFolderItemsChange,+ onDragCreateFolder,+ },+ navigate,+ cancelPendingNavigation,+ }+}diff --git a/src/web/src/components/community/user-bar.test.ts b/src/web/src/components/community/shell/user-bar.test.tssimilarity index 100%rename from src/web/src/components/community/user-bar.test.tsrename to src/web/src/components/community/shell/user-bar.test.tsdiff --git a/src/web/src/components/community/user-bar.tsx b/src/web/src/components/community/shell/user-bar.tsxsimilarity index 96%rename from src/web/src/components/community/user-bar.tsxrename to src/web/src/components/community/shell/user-bar.tsxindex b9b9afe72..8119d1286 100644--- a/src/web/src/components/community/user-bar.tsx+++ b/src/web/src/components/community/shell/user-bar.tsx@@ -3,8 +3,8 @@import type React from "react"import { Inbox, Settings } from "lucide-react"import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover"-import { Avatar } from "./avatar"-import type { OpenProfile } from "./_types"+import { Avatar } from "../avatar"+import type { OpenProfile } from "@/components/community/social/profile-types"import { resolveProfilePresence } from "@/lib/community/presence"// UserBar always renders the signed-in viewer, so presence resolves throughdiff --git a/src/web/src/components/community/bot-approval-card.test.ts b/src/web/src/components/community/social/bot-approval-card.test.tssimilarity index 100%rename from src/web/src/components/community/bot-approval-card.test.tsrename to src/web/src/components/community/social/bot-approval-card.test.tsdiff --git a/src/web/src/components/community/bot-approval-card.tsx b/src/web/src/components/community/social/bot-approval-card.tsxsimilarity index 100%rename from src/web/src/components/community/bot-approval-card.tsxrename to src/web/src/components/community/social/bot-approval-card.tsxdiff --git a/src/web/src/components/community/community-invite-card.test.ts b/src/web/src/components/community/social/community-invite-card.test.tssimilarity index 92%rename from src/web/src/components/community/community-invite-card.test.tsrename to src/web/src/components/community/social/community-invite-card.test.tsindex e61261602..16dc98922 100644--- a/src/web/src/components/community/community-invite-card.test.ts+++ b/src/web/src/components/community/social/community-invite-card.test.ts@@ -41,7 +41,7 @@ describe("resolveInviteCardPresentation", () => {describe("invite-card perspective wiring", () => {it("derives sender perspective from the message author and viewer", () => {- const message = readComponent("message.tsx")+ const message = readComponent("../messages/message.tsx")expect(message).toContain("m.authorId === viewerUserId ? \"sender\" : \"recipient\"")expect(message).toContain("a.authorId !== b.authorId")@@ -49,7 +49,7 @@ describe("invite-card perspective wiring", () => {})it("keeps Share as Image explicitly neutral", () => {- const shareDialog = readComponent("message-share-dialog.tsx")+ const shareDialog = readComponent("../messages/message-share-dialog.tsx")expect(shareDialog).toContain('perspective="neutral"')})diff --git a/src/web/src/components/community/community-invite-card.tsx b/src/web/src/components/community/social/community-invite-card.tsxsimilarity index 97%rename from src/web/src/components/community/community-invite-card.tsxrename to src/web/src/components/community/social/community-invite-card.tsxindex ba301675d..f24da1845 100644--- a/src/web/src/components/community/community-invite-card.tsx+++ b/src/web/src/components/community/social/community-invite-card.tsx@@ -5,14 +5,14 @@ import { useQuery } from "@tanstack/react-query"import { toast } from "sonner"import { apiFetch } from "@/lib/api/client"import { avatarInitial } from "@/lib/community/avatar"-import { ServerIcon } from "./server-icon"+import { ServerIcon } from "../server-icon"import { communityKeys } from "@/lib/query-keys"import { useServers } from "@/hooks/community/use-servers"import { useJoinServer } from "@/hooks/community/mutations/servers"import { Button } from "@/components/ui/button"import { Skeleton } from "@/components/ui/skeleton"import { tid } from "@/lib/community/testids"-import type { MessagePerspective } from "./_types"+import type { MessagePerspective } from "@/components/community/messages/message-presentation-types"export function resolveInviteCardPresentation(perspective: MessagePerspective,diff --git a/src/web/src/components/community/friends-page.tsx b/src/web/src/components/community/social/friends-page.tsxsimilarity index 98%rename from src/web/src/components/community/friends-page.tsxrename to src/web/src/components/community/social/friends-page.tsxindex 55fefda9a..439c4611c 100644--- a/src/web/src/components/community/friends-page.tsx+++ b/src/web/src/components/community/social/friends-page.tsx@@ -9,11 +9,12 @@ import { Input } from "@/components/ui/input"import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuSeparator } from "@/components/ui/context-menu"import { Skeleton } from "@/components/ui/skeleton"-import { Avatar } from "./avatar"+import { Avatar } from "../avatar"import { avatarInitial } from "@/lib/community/avatar"-import { EmptyState } from "./empty-state"+import { EmptyState } from "../empty-state"import { hasStatus } from "./status-presets"-import type { Friend, PendingRequest, BlockedUser, OpenProfile } from "./_types"+import type { Friend, PendingRequest, BlockedUser } from "@/lib/community/models/people"+import type { OpenProfile } from "@/components/community/social/profile-types"import { isSelfBotFriendship, isPresenceOffline, MIN_SEARCH_LENGTH } from "@alook/shared"function FriendSection({ title, count, emptyLabel, children }: {diff --git a/src/web/src/components/community/invite-dialog.tsx b/src/web/src/components/community/social/invite-dialog.tsxsimilarity index 98%rename from src/web/src/components/community/invite-dialog.tsxrename to src/web/src/components/community/social/invite-dialog.tsxindex 47ede8c21..52924c872 100644--- a/src/web/src/components/community/invite-dialog.tsx+++ b/src/web/src/components/community/social/invite-dialog.tsx@@ -7,7 +7,7 @@ import { Dialog, DialogContent } from "@/components/ui/dialog"import { Input } from "@/components/ui/input"import { Button } from "@/components/ui/button"import { Skeleton } from "@/components/ui/skeleton"-import { Avatar } from "./avatar"+import { Avatar } from "../avatar"import { hasStatus } from "./status-presets"import { useInvitableFriends } from "@/hooks/community/use-invitable-friends"import {@@ -16,7 +16,7 @@ import {} from "@/hooks/community/mutations"import { useDmMessageSender } from "@/hooks/community/use-dm-message-sender"import { useCurrentUser } from "@/contexts/community/current-user"-import type { Friend } from "./_types"+import type { Friend } from "@/lib/community/models/people"const INVITE_ORIGIN =typeof window !== "undefined" ? window.location.origin : ""diff --git a/src/web/src/components/community/profile-card.test.ts b/src/web/src/components/community/social/profile-card.test.tssimilarity index 97%rename from src/web/src/components/community/profile-card.test.tsrename to src/web/src/components/community/social/profile-card.test.tsindex cd440833c..c35b915e3 100644--- a/src/web/src/components/community/profile-card.test.ts+++ b/src/web/src/components/community/social/profile-card.test.ts@@ -4,7 +4,7 @@ import { describe, it, expect } from "vitest"import { resolveCardStatus, resolveProfileBackdropSeed } from "./profile-card"import { ProfileCard } from "./profile-card"import { serializeBeamSeed } from "@/lib/avatar/seed-url"-import type { Profile } from "./_types"+import type { Profile } from "@/components/community/social/profile-types"function renderProfile(overrides: Partial<Profile> = {}) {return renderToStaticMarkup(createElement(ProfileCard, {diff --git a/src/web/src/components/community/profile-card.tsx b/src/web/src/components/community/social/profile-card.tsxsimilarity index 99%rename from src/web/src/components/community/profile-card.tsxrename to src/web/src/components/community/social/profile-card.tsxindex 477d4a68b..19febf911 100644--- a/src/web/src/components/community/profile-card.tsx+++ b/src/web/src/components/community/social/profile-card.tsx@@ -4,11 +4,11 @@ import { useState } from "react"import { MessagesSquare, Shield } from "lucide-react"import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover"import { Badge } from "@/components/ui/badge"-import { Avatar } from "./avatar"+import { Avatar } from "../avatar"import { SeededBackdrop } from "@/components/avatar"import { resolveAvatar } from "@/lib/avatar/resolve"import { StatusEditor, hasStatus } from "./status-editor"-import type { Profile } from "./_types"+import type { Profile } from "@/components/community/social/profile-types"import type { Breakpoint } from "@/hooks/use-mobile"import { useCommunityWsStore } from "@/stores/community/ws"import { tid } from "@/lib/community/testids"diff --git a/src/web/src/components/community/profile-lookup.test.ts b/src/web/src/components/community/social/profile-lookup.test.tssimilarity index 98%rename from src/web/src/components/community/profile-lookup.test.tsrename to src/web/src/components/community/social/profile-lookup.test.tsindex 9c27479f2..2632436f3 100644--- a/src/web/src/components/community/profile-lookup.test.ts+++ b/src/web/src/components/community/social/profile-lookup.test.ts@@ -6,7 +6,7 @@ import {resolveProfileUserId,buildSelfProfile,} from "./profile-lookup"-import type { Member, Friend } from "./_types"+import type { Member, Friend } from "@/lib/community/models/people"import type { CurrentUser } from "@/contexts/community/current-user"function member(overrides: Partial<Member>): Member {diff --git a/src/web/src/components/community/profile-lookup.ts b/src/web/src/components/community/social/profile-lookup.tssimilarity index 93%rename from src/web/src/components/community/profile-lookup.tsrename to src/web/src/components/community/social/profile-lookup.tsindex 9c446718b..67ac4976d 100644--- a/src/web/src/components/community/profile-lookup.ts+++ b/src/web/src/components/community/social/profile-lookup.ts@@ -1,4 +1,6 @@-import type { Member, Friend, Profile, View } from "./_types"+import type { Member, Friend } from "@/lib/community/models/people"+import type { Profile } from "@/components/community/social/profile-types"+import type { View } from "@/components/community/shell/shell-types"import type { CurrentUser } from "@/contexts/community/current-user"import { resolveProfilePresence } from "@/lib/community/presence"import { avatarInitial } from "@/lib/community/avatar"diff --git a/src/web/src/components/community/social/profile-types.ts b/src/web/src/components/community/social/profile-types.tsnew file mode 100644index 000000000..73a6e2145--- /dev/null+++ b/src/web/src/components/community/social/profile-types.ts@@ -0,0 +1,37 @@+import type React from "react"+import type { Presence } from "@/lib/community/models/people"++// ── Profile ──────────────────────────────────────────────────────────────────+export type Profile = {+ name: string+ // Stable user id of the profile's owner — the exact-match key for DM-target+ // resolution and self-detection (never match by non-unique display name).+ // Optional so mock/older Profile-constructing sites keep type-checking.+ userId?: string+ // Variable-width (≥4-digit) decimal discriminator derived from user.id+ // (`"0042"`, widens on collision) — undefined while the profile fetch is in+ // flight. Shown at its true width, never re-padded. See computeDiscriminator+ // in @alook/shared.+ discriminator?: string+ avatar: string+ contextLabel?: string+ about: string+ mutual: number+ // Live online/offline dot on the card's avatar — undefined when no+ // member/friend match could be resolved (e.g. a stale mention). See+ // `resolveProfilePresence` in shell-frame.tsx.+ presence?: Presence+}++// Shared callback signature for opening a user's profile card at a click point.+// `userId` is the exact-match disambiguator — pass it whenever the caller+// already has the clicked person's userId (member rows, message authors,+// thread openers) so same-named members never collide. `discriminator` is+// the fallback disambiguator for a mention pill, which only carries a+// `#0042` tag (see message-markdown.tsx) and no userId.+export type OpenProfile = (+ name: string,+ e: React.MouseEvent,+ discriminator?: string,+ userId?: string,+) => voiddiff --git a/src/web/src/components/community/status-editor.tsx b/src/web/src/components/community/social/status-editor.tsxsimilarity index 98%rename from src/web/src/components/community/status-editor.tsxrename to src/web/src/components/community/social/status-editor.tsxindex 187f42af0..02d22773e 100644--- a/src/web/src/components/community/status-editor.tsx+++ b/src/web/src/components/community/social/status-editor.tsx@@ -7,7 +7,7 @@ import { MAX_STATUS_TEXT_LENGTH } from "@alook/shared"import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover"import { Input } from "@/components/ui/input"import { Separator } from "@/components/ui/separator"-import { EmojiPickerPopover } from "./emoji-picker"+import { EmojiPickerPopover } from "../messages/emoji-picker"import { STATUS_PRESETS, matchingPreset, hasStatus } from "./status-presets"export { hasStatus } from "./status-presets"diff --git a/src/web/src/components/community/status-presets.test.ts b/src/web/src/components/community/social/status-presets.test.tssimilarity index 100%rename from src/web/src/components/community/status-presets.test.tsrename to src/web/src/components/community/social/status-presets.test.tsdiff --git a/src/web/src/components/community/status-presets.ts b/src/web/src/components/community/social/status-presets.tssimilarity index 100%rename from src/web/src/components/community/status-presets.tsrename to src/web/src/components/community/social/status-presets.tsdiff --git a/src/web/src/components/home/landing-content.test.ts b/src/web/src/components/home/landing-content.test.tsindex 2b1afe1ce..9bc34df80 100644--- a/src/web/src/components/home/landing-content.test.ts+++ b/src/web/src/components/home/landing-content.test.ts@@ -110,7 +110,7 @@ describe("landing content contract", () => {it("keeps product-demo labels out of the homepage heading tree", () => {const root = webRoot()const shellSource = readFileSync(path.join(root, "src/components/home/landing-shell-motion.tsx"), "utf8")- const dmHeaderSource = readFileSync(path.join(root, "src/components/community/dm-header.tsx"), "utf8")+ const dmHeaderSource = readFileSync(path.join(root, "src/components/community/channels/dm-header.tsx"), "utf8")const pairMachineSource = readFileSync(path.join(root, "src/components/community/machines/pair-machine-sheet.tsx"),"utf8",diff --git a/src/web/src/components/home/landing-page.tsx b/src/web/src/components/home/landing-page.tsxindex 2ce1b8904..9df8e0c31 100644--- a/src/web/src/components/home/landing-page.tsx+++ b/src/web/src/components/home/landing-page.tsx@@ -4,7 +4,7 @@ import Image from "next/image"import Link from "next/link"import { useEffect, useRef, type PointerEvent as ReactPointerEvent } from "react"import { GeneratedAvatar } from "@/components/avatar"-import { ProfileCard } from "@/components/community/profile-card"+import { ProfileCard } from "@/components/community/social/profile-card"import { ProviderLogo } from "@/components/provider-logo"import { HeroSection } from "./hero-section"import { HeroAvatarSwarm } from "./hero-avatar-swarm"diff --git a/src/web/src/components/home/landing-shell-motion.tsx b/src/web/src/components/home/landing-shell-motion.tsxindex d61ab6db8..c8dce1846 100644--- a/src/web/src/components/home/landing-shell-motion.tsx+++ b/src/web/src/components/home/landing-shell-motion.tsx@@ -29,23 +29,26 @@ import { Card } from "@/components/ui/card"import { Input } from "@/components/ui/input"import { AppSurface } from "@/components/ui/app-surface"import { SheetBody, SheetFooter, SheetHeader } from "@/components/ui/sheet"-import { Shell } from "@/components/community/shell"-import { ServerRail } from "@/components/community/server-rail"-import { ChannelSidebar } from "@/components/community/channel-sidebar"-import { DmSidebar } from "@/components/community/dm-sidebar"-import { DmHeader } from "@/components/community/dm-header"-import { ChannelHeader } from "@/components/community/channel-header"+import { Shell } from "@/components/community/shell/shell"+import { ServerRail } from "@/components/community/shell/server-rail"+import { ChannelSidebar } from "@/components/community/channels/channel-sidebar"+import { DmSidebar } from "@/components/community/channels/dm-sidebar"+import { DmHeader } from "@/components/community/channels/dm-header"+import { ChannelHeader } from "@/components/community/channels/channel-header"import { Avatar } from "@/components/community/avatar"-import { Message } from "@/components/community/message"-import { InboxPopover } from "@/components/community/community-inbox-popover"+import { Message } from "@/components/community/messages/message"+import { InboxPopover } from "@/components/community/shell/community-inbox-popover"import { MachineCard } from "@/components/community/machines/machine-card"import { PairMachineSteps } from "@/components/community/machines/pair-machine-sheet"import { ConnectTile } from "@/components/community/onboarding-tiles/connect-tile"import { BotFormFields } from "@/components/community/bots/bot-form-fields"import { BotRuntimeFields } from "@/components/community/bots/bot-runtime-fields"-import { UserBar } from "@/components/community/user-bar"-import { useChannelTree } from "@/components/community/use-channel-tree"-import type { Category, DM, RenderMsg, Server, UnreadServer } from "@/components/community/_types"+import { UserBar } from "@/components/community/shell/user-bar"+import { useChannelTree } from "@/components/community/channels/use-channel-tree"+import type { Category, Server } from "@/lib/community/models/navigation"+import type { DM } from "@/lib/community/models/people"+import type { RenderMsg } from "@/lib/community/models/message"+import type { UnreadServer } from "@/lib/community/models/inbox"import { serializeBeamSeed } from "@/lib/avatar/seed-url"import { tid } from "@/lib/community/testids"import {diff --git a/src/web/src/hooks/community/community-ws/cache.test.ts b/src/web/src/hooks/community/community-ws/cache.test.tsindex 6ce29554e..85d1196a8 100644--- a/src/web/src/hooks/community/community-ws/cache.test.ts+++ b/src/web/src/hooks/community/community-ws/cache.test.ts@@ -3,7 +3,7 @@ import type {CommunityReactionAdd,CommunityReactionRemove,} from "@alook/shared"-import type { Msg } from "@/components/community/_types"+import type { Msg } from "@/lib/community/models/message"import {applyReactionToCache,applyReactionToMessage,diff --git a/src/web/src/hooks/community/community-ws/cache.ts b/src/web/src/hooks/community/community-ws/cache.tsindex 09a4233cd..8c182f383 100644--- a/src/web/src/hooks/community/community-ws/cache.ts+++ b/src/web/src/hooks/community/community-ws/cache.ts@@ -3,8 +3,7 @@ import type {CommunityReactionAdd,CommunityReactionRemove,} from "@alook/shared"-import type { Msg } from "@/components/community/_types"-import type { MessagesPage } from "@/hooks/community/use-messages"+import type { MessagesPage, Msg } from "@/lib/community/models/message"export type PageCache = InfiniteData<MessagesPage>diff --git a/src/web/src/hooks/community/community-ws/message-events.ts b/src/web/src/hooks/community/community-ws/message-events.tsindex b88ed243e..c142610c4 100644--- a/src/web/src/hooks/community/community-ws/message-events.ts+++ b/src/web/src/hooks/community/community-ws/message-events.ts@@ -10,7 +10,7 @@ import type {import { communityKeys } from "@/lib/query-keys"import { projectCommunityMessageCreate } from "@/lib/community/message-wire"import type { CanonicalMessage } from "@/lib/community/message-stream"-import type { Msg } from "@/components/community/_types"+import type { Msg } from "@/lib/community/models/message"import { useCommunityStore } from "@/stores/community"import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"import {diff --git a/src/web/src/hooks/community/fetch-all-server-members.ts b/src/web/src/hooks/community/fetch-all-server-members.tsindex 53372b88a..199880bb0 100644--- a/src/web/src/hooks/community/fetch-all-server-members.ts+++ b/src/web/src/hooks/community/fetch-all-server-members.ts@@ -1,5 +1,5 @@import { MAX_MEMBERS_PAGE_SIZE } from "@alook/shared"-import type { Member } from "@/components/community/_types"+import type { Member } from "@/lib/community/models/people"import { apiFetch } from "@/lib/api/client"type MembersPage = {diff --git a/src/web/src/hooks/community/forum-opener-title-reconciliation.ts b/src/web/src/hooks/community/forum-opener-title-reconciliation.tsindex 70b69817c..2c2707d16 100644--- a/src/web/src/hooks/community/forum-opener-title-reconciliation.ts+++ b/src/web/src/hooks/community/forum-opener-title-reconciliation.ts@@ -2,8 +2,8 @@import type { InfiniteData, QueryClient } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"-import type { Msg, UnreadServer } from "@/components/community/_types"-import type { MessagesPage } from "@/hooks/community/use-messages"+import type { MessagesPage, Msg } from "@/lib/community/models/message"+import type { UnreadServer } from "@/lib/community/models/inbox"import type { ThreadsResponse } from "@/hooks/community/use-channel-panels"import type { ForumActivityPage } from "@/hooks/community/use-forum-feed"import {diff --git a/src/web/src/hooks/community/mutations/folders.ts b/src/web/src/hooks/community/mutations/folders.tsindex 36332ffb0..5b383d630 100644--- a/src/web/src/hooks/community/mutations/folders.ts+++ b/src/web/src/hooks/community/mutations/folders.ts@@ -3,7 +3,7 @@import { useMutation, useQueryClient } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"-import type { CommunityFolder, FolderServer } from "@/components/community/_types"+import type { CommunityFolder, FolderServer } from "@/lib/community/models/navigation"import type { FoldersResponse } from "@/hooks/community/use-folders"import type { ServersResponse } from "@/hooks/community/use-servers"diff --git a/src/web/src/hooks/community/mutations/messages.test.ts b/src/web/src/hooks/community/mutations/messages.test.tsindex d782da414..9f963b4db 100644--- a/src/web/src/hooks/community/mutations/messages.test.ts+++ b/src/web/src/hooks/community/mutations/messages.test.ts@@ -10,7 +10,7 @@import { describe, it, expect, vi, beforeEach } from "vitest"import { QueryClient } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"-import type { Msg } from "@/components/community/_types"+import type { Msg } from "@/lib/community/models/message"// ── React shim (mirrors use-community-ws.test.ts) ────────────────────────let refs: Map<string, { current: unknown }> = new Map()diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.tsindex 9b5278c2e..94b328cf4 100644--- a/src/web/src/hooks/community/mutations/messages.ts+++ b/src/web/src/hooks/community/mutations/messages.ts@@ -25,10 +25,10 @@ import {type CanonicalMessage,type MessageScope,} from "@/lib/community/message-stream"-import type { Msg, Attachment } from "@/components/community/_types"-import type { MessagesPage } from "@/hooks/community/use-messages"+import type { Attachment, MessagesPage, Msg } from "@/lib/community/models/message"import type { PinsResponse } from "@/hooks/community/use-channel-panels"import type { MarkedResponse, MessageMarkedResponse } from "@/hooks/community/use-inbox"+import { scheduleMarkRead } from "@/lib/community/pending-reads"import {getForumSidebarBase,hasForumSidebarThread,@@ -39,6 +39,14 @@ import {import { reconcileForumOpenerTitle } from "@/hooks/community/forum-opener-title-reconciliation"import { isBlocked, type MentionType } from "@alook/shared"+export {+ _resetPendingReads_forTesting,+ flushPendingReads,+ MARK_CHANNEL_READ_DEBOUNCE_MS,+ scheduleMarkRead,+} from "@/lib/community/pending-reads"+export type { ScheduleMarkReadOpts } from "@/lib/community/pending-reads"+/*** Message-scoped mutation hooks — the split of the God-context's* `sendMessage`/`toggleReaction`/`pinMessage`/etc. into standalone@@ -800,134 +808,6 @@ export function useCreateThread() {// ── Read state ─────────────────────────────────────────────────────────────-// #13 read-stampede: debounce mark-channel-read at 500ms per channelId. On-// unmount / channel switch, `flushPendingReads()` runs any pending timer-// immediately so the user's last-read pointer isn't lost.-export const MARK_CHANNEL_READ_DEBOUNCE_MS = 500--/**- * A single pending mark-read carries the debounce timer, a `fire` closure,- * and the most recently queued `messageId` (or `undefined` for a no-body- * mass mark-read). Re-scheduling within the debounce window replaces the- * pending `messageId` — monotone forward semantics live one layer up in- * `useChannelWatermark`, so this layer just uses whichever value the last- * caller passed.- *- * Both the timer callback and `flushPendingReads()` invoke `fire` — same- * code path, whether the window elapsed naturally or was flushed early.- */-type PendingRead = {- timer: ReturnType<typeof setTimeout>- fire: () => void- // Latest queued message id — captured in the closure so `fire` reads the- // freshest value even after the timer was scheduled with a stale one.- messageId: string | undefined-}-const pendingReads = new Map<string, PendingRead>()--/** Testing hook — clears any pending mark-read timer without firing. */-export function _resetPendingReads_forTesting() {- for (const p of pendingReads.values()) clearTimeout(p.timer)- pendingReads.clear()-}--/**- * Flush every pending mark-read immediately. Each entry's `fire` runs the- * same code the timer would have — so `onDone` (typically the inbox- * invalidate) still fires exactly once per PUT, even when a caller flushes- * mid-window.- */-export function flushPendingReads() {- const pending = [...pendingReads.values()]- for (const p of pending) {- clearTimeout(p.timer)- p.fire()- }-}--export type ScheduleMarkReadOpts = {- /**- * When set, PUT `{ lastReadMessageId }` — advances the read pointer to- * that message's `(createdAt, id)`. Omit for the mass mark-read case- * (no body). The mutation layer trusts whatever value the caller passes- * most recently; monotonicity is the caller's responsibility (see- * `useChannelWatermark` / `useDmWatermark`). Body key matches the DM +- * thread read routes.- */- messageId?: string- onDone: () => void-}--/**- * Resolve a schedule key to a target read-endpoint URL. The debounce key- * is a string namespace so `channelId` and `dm:<dmId>` coexist in the same- * `pendingReads` map without ever aliasing each other — a channel and a- * DM with the same underlying id would otherwise share a debounce slot- * and clobber each other's pointers.- *- * Channel keys are bare ids (legacy — the debounce was channel-only- * before B2). DM keys are prefixed with `"dm:"` so the map stays keyed by- * unique strings without a discriminated-union tag on `PendingRead`.- */-function resolveReadEndpoint(key: string): string {- // DM and channel both resolve through the one canonical read door (a DM is a- // channel row in the same id-space); the `dm:` key prefix only strips to the- // channelId, no per-type URL fork.- const channelId = key.startsWith("dm:") ? key.slice(3) : key- return `/api/community/channels/${channelId}/read`-}--/**- * Debounce a mark-read PUT. Same-key re-invokes within the 500ms window- * replace the pending intent (previous `messageId` and `onDone` are- * dropped; the new pair takes over). Nothing is left "hanging" because- * `mutationFn` no longer awaits the debounced work.- *- * `key` is a string namespace: a bare `channelId` for channel/thread reads- * (legacy contract — every existing call site passes a channel id- * directly) or `"dm:<dmId>"` for DM reads. `resolveReadEndpoint` maps the- * key back to the target URL. Consumers should never build the DM- * namespace directly — call `useAdvanceDmWatermark` which handles it.- */-export function scheduleMarkRead(- key: string,- opts: ScheduleMarkReadOpts,-): void {- const existing = pendingReads.get(key)- if (existing) clearTimeout(existing.timer)- // `entry` is captured inside `fire` so it can read the freshest- // `messageId` at the moment the PUT actually issues — even if a later- // schedule call updated it in place. Cleaner than closing over a mutable- // outer variable.- const entry: PendingRead = {- // Timer is filled in below after fire is defined.- timer: undefined as unknown as ReturnType<typeof setTimeout>,- messageId: opts.messageId,- fire: () => {- // Idempotent: if the map has already moved on (fire ran, or a fresh- // scheduling replaced us), do nothing. This is what makes it safe for- // both the timer AND `flushPendingReads()` to call `fire` in the same- // tick — only the first wins.- const cur = pendingReads.get(key)- if (cur !== entry) return- pendingReads.delete(key)- const body = entry.messageId- ? JSON.stringify({ lastReadMessageId: entry.messageId })- : undefined- const init: RequestInit = body- ? { method: "PUT", body }- : { method: "PUT" }- void apiFetch(resolveReadEndpoint(key), init)- .then(() => opts.onDone())- .catch(() => {- // Silent — the inbox will reconcile once the WS invalidate fires.- })- },- }- entry.timer = setTimeout(entry.fire, MARK_CHANNEL_READ_DEBOUNCE_MS)- pendingReads.set(key, entry)-}-export type MarkChannelReadArgs = { channelId: string }/**diff --git a/src/web/src/hooks/community/use-bots.ts b/src/web/src/hooks/community/use-bots.tsindex 021dfaa88..bfa469bb7 100644--- a/src/web/src/hooks/community/use-bots.ts+++ b/src/web/src/hooks/community/use-bots.ts@@ -3,7 +3,7 @@import { useQuery, useMutation, useQueryClient, type UseQueryResult } from "@tanstack/react-query"import { apiFetch, readUploadError } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"-import type { BotActivityDay } from "@/components/community/bots/bot-activity-heatmap"+import type { BotActivityDay } from "@/lib/community/models/people"export type BotSummary = {id: stringdiff --git a/src/web/src/hooks/community/use-channel-members.ts b/src/web/src/hooks/community/use-channel-members.tsindex 716d20374..0cdcf9a5f 100644--- a/src/web/src/hooks/community/use-channel-members.ts+++ b/src/web/src/hooks/community/use-channel-members.ts@@ -4,7 +4,7 @@ import { useMutation, useQuery, useQueryClient, type UseQueryResult } from "@tanimport { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import type { CommunityRole } from "@alook/shared"-import type { CommunityUserCore } from "@/components/community/_types"+import type { CommunityUserCore } from "@/lib/community/models/people"import { fetchAllServerMembers } from "./fetch-all-server-members"// Canonical member shape (superset of the pre-audience roster). `source` tagsdiff --git a/src/web/src/hooks/community/use-channel-panels.ts b/src/web/src/hooks/community/use-channel-panels.tsindex 8556cfba4..46e71382e 100644--- a/src/web/src/hooks/community/use-channel-panels.ts+++ b/src/web/src/hooks/community/use-channel-panels.ts@@ -3,7 +3,7 @@import { useQuery, type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"-import type { Thread, Msg } from "@/components/community/_types"+import type { Thread, Msg } from "@/lib/community/models/message"// Frozen empty fallbacks — see `use-servers.ts` for the rationale.const EMPTY_THREADS: readonly Thread[] = Object.freeze([])diff --git a/src/web/src/hooks/community/use-channel-route-model.ts b/src/web/src/hooks/community/use-channel-route-model.tsindex 07ce70b61..c7c415573 100644--- a/src/web/src/hooks/community/use-channel-route-model.ts+++ b/src/web/src/hooks/community/use-channel-route-model.ts@@ -7,7 +7,7 @@ import { isForum as isForumType } from "@alook/shared"import { useServer } from "./use-servers"import { useCommunityStore, useCurrentChannelMeta } from "@/stores/community"import { toastApiError } from "@/lib/api/client"-import { isDefinitiveChildMetaFailure } from "@/components/community/eject-server"+import { isDefinitiveChildMetaFailure } from "@/lib/community/eject-server"import { clearLastChannel, getLastChannel } from "@/lib/community/last-channel"import { communityWsSubscribe, communityWsUnsubscribe } from "./use-community-ws"import { useChildChannelMeta } from "./use-child-channel-meta"diff --git a/src/web/src/hooks/community/use-channel-watermark.test.ts b/src/web/src/hooks/community/use-channel-watermark.test.tsindex 1b76b4d25..f90944b6a 100644--- a/src/web/src/hooks/community/use-channel-watermark.test.ts+++ b/src/web/src/hooks/community/use-channel-watermark.test.ts@@ -181,6 +181,8 @@ const flushSpy = vi.fn()vi.mock("@/hooks/community/mutations/messages", () => ({useAdvanceChannelWatermark: () => advanceSpy,+}))+vi.mock("@/lib/community/pending-reads", () => ({flushPendingReads: () => flushSpy(),}))diff --git a/src/web/src/hooks/community/use-channel-watermark.ts b/src/web/src/hooks/community/use-channel-watermark.tsindex 07628e806..6cc80985e 100644--- a/src/web/src/hooks/community/use-channel-watermark.ts+++ b/src/web/src/hooks/community/use-channel-watermark.ts@@ -1,9 +1,9 @@"use client"import { useEffect, useRef } from "react"-import { flushPendingReads } from "@/hooks/community/mutations/messages"+import { flushPendingReads } from "@/lib/community/pending-reads"import { useAdvanceChannelWatermark } from "@/hooks/community/mutations/messages"-import type { Msg } from "@/components/community/_types"+import type { Msg } from "@/lib/community/models/message"import { useCurrentUser } from "@/contexts/community/current-user"/**diff --git a/src/web/src/hooks/community/use-dm-message-sender.ts b/src/web/src/hooks/community/use-dm-message-sender.tsindex 521b98abb..803a34d8f 100644--- a/src/web/src/hooks/community/use-dm-message-sender.ts+++ b/src/web/src/hooks/community/use-dm-message-sender.ts@@ -1,8 +1,8 @@"use client"import { useCallback } from "react"-import type { Msg } from "@/components/community/_types"-import type { SendAttachment } from "@/components/community/composer"+import type { Msg } from "@/lib/community/models/message"+import type { SendAttachment } from "@/lib/community/models/message"import { toastApiError } from "@/lib/api/client"import { toOptimisticReplyPreview } from "@/lib/community/reply-preview"import { useMessageStreamStore } from "@/stores/community/message-stream"diff --git a/src/web/src/hooks/community/use-dm-watermark.test.ts b/src/web/src/hooks/community/use-dm-watermark.test.tsindex d2b17ae72..49d415bcb 100644--- a/src/web/src/hooks/community/use-dm-watermark.test.ts+++ b/src/web/src/hooks/community/use-dm-watermark.test.ts@@ -142,6 +142,8 @@ const flushSpy = vi.fn()vi.mock("@/hooks/community/mutations/messages", () => ({useAdvanceDmWatermark: () => advanceSpy,+}))+vi.mock("@/lib/community/pending-reads", () => ({flushPendingReads: () => flushSpy(),}))diff --git a/src/web/src/hooks/community/use-dm-watermark.ts b/src/web/src/hooks/community/use-dm-watermark.tsindex 64fcd573e..3b6c34590 100644--- a/src/web/src/hooks/community/use-dm-watermark.ts+++ b/src/web/src/hooks/community/use-dm-watermark.ts@@ -1,9 +1,9 @@"use client"import { useEffect, useRef } from "react"-import { flushPendingReads } from "@/hooks/community/mutations/messages"+import { flushPendingReads } from "@/lib/community/pending-reads"import { useAdvanceDmWatermark } from "@/hooks/community/mutations/messages"-import type { Msg } from "@/components/community/_types"+import type { Msg } from "@/lib/community/models/message"import { useCurrentUser } from "@/contexts/community/current-user"/**diff --git a/src/web/src/hooks/community/use-dms.ts b/src/web/src/hooks/community/use-dms.tsindex a2009a0a5..123d35fbb 100644--- a/src/web/src/hooks/community/use-dms.ts+++ b/src/web/src/hooks/community/use-dms.ts@@ -3,7 +3,7 @@import { useQuery, type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"-import type { DM } from "@/components/community/_types"+import type { DM } from "@/lib/community/models/people"/*** Fetches the DM conversation sidebar list.diff --git a/src/web/src/hooks/community/use-folders.ts b/src/web/src/hooks/community/use-folders.tsindex d2b7c74f8..a1719237f 100644--- a/src/web/src/hooks/community/use-folders.ts+++ b/src/web/src/hooks/community/use-folders.ts@@ -4,7 +4,7 @@ import { useQuery, type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import { avatarInitial } from "@/lib/community/avatar"-import type { CommunityFolder } from "@/components/community/_types"+import type { CommunityFolder } from "@/lib/community/models/navigation"/*** Fetches the user's server-folder groupings for the rail.diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.tsindex 4cd896265..8cf99f5b7 100644--- a/src/web/src/hooks/community/use-forum-feed.ts+++ b/src/web/src/hooks/community/use-forum-feed.ts@@ -7,7 +7,7 @@ import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import { avatarInitial } from "@/lib/community/avatar"import { readForumTagSelection, validateForumTagSelection, writeForumTagSelection } from "@/lib/community/forum-tag-selection"-import type { ForumThread } from "@/components/community/_types"+import type { ForumThread } from "@/lib/community/models/message"import { useForumTags } from "./use-channel-panels"type ActivityThread = {diff --git a/src/web/src/hooks/community/use-friends.ts b/src/web/src/hooks/community/use-friends.tsindex 3ec82f854..ccfe3615e 100644--- a/src/web/src/hooks/community/use-friends.ts+++ b/src/web/src/hooks/community/use-friends.ts@@ -3,7 +3,7 @@import { useQuery, keepPreviousData, type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"-import type { Friend, PendingRequest, BlockedUser } from "@/components/community/_types"+import type { Friend, PendingRequest, BlockedUser } from "@/lib/community/models/people"/*** The community read routes wrap their D1 hits in `readOrStale` (seediff --git a/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts b/src/web/src/hooks/community/use-inbox-auto-collapse.test.tsindex d3f9300e5..62af0efd2 100644--- a/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts+++ b/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts@@ -1,7 +1,7 @@import { describe, it, expect } from "vitest"import React from "react"import TestRenderer, { act } from "react-test-renderer"-import type { Mention, UnreadDm, UnreadServer } from "@/components/community/_types"+import type { Mention, UnreadDm, UnreadServer } from "@/lib/community/models/inbox"import {inboxItemPresent,useInboxAutoCollapse,diff --git a/src/web/src/hooks/community/use-inbox-auto-collapse.ts b/src/web/src/hooks/community/use-inbox-auto-collapse.tsindex 912bb8e4a..ac6482e98 100644--- a/src/web/src/hooks/community/use-inbox-auto-collapse.ts+++ b/src/web/src/hooks/community/use-inbox-auto-collapse.ts@@ -1,7 +1,7 @@"use client"import { useCallback, useEffect, useRef, useState } from "react"-import type { Mention, UnreadDm, UnreadServer } from "@/components/community/_types"+import type { Mention, UnreadDm, UnreadServer } from "@/lib/community/models/inbox"/*** Inbox auto-collapse.diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.tsindex 921665453..dd1859ac0 100644--- a/src/web/src/hooks/community/use-inbox.ts+++ b/src/web/src/hooks/community/use-inbox.ts@@ -3,7 +3,7 @@import { useQuery, keepPreviousData, type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"-import type { UnreadServer, UnreadDm, Mention, Marked } from "@/components/community/_types"+import type { UnreadServer, UnreadDm, Mention, Marked } from "@/lib/community/models/inbox"class StaleReadError extends Error {constructor() { super("stale D1 read"); this.name = "StaleReadError" }diff --git a/src/web/src/hooks/community/use-invitable-friends.ts b/src/web/src/hooks/community/use-invitable-friends.tsindex bf70d8a64..a8bb48cd6 100644--- a/src/web/src/hooks/community/use-invitable-friends.ts+++ b/src/web/src/hooks/community/use-invitable-friends.ts@@ -3,7 +3,7 @@import { useQuery, type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"-import type { Friend } from "@/components/community/_types"+import type { Friend } from "@/lib/community/models/people"import { fetchAllServerMembers } from "./fetch-all-server-members"/**diff --git a/src/web/src/hooks/community/use-message.ts b/src/web/src/hooks/community/use-message.tsindex babd50f3c..523fc929e 100644--- a/src/web/src/hooks/community/use-message.ts+++ b/src/web/src/hooks/community/use-message.ts@@ -3,7 +3,7 @@import { useQuery, type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"-import type { Msg } from "@/components/community/_types"+import type { Msg } from "@/lib/community/models/message"/*** Fetches a single hydrated message by id — the payload shape returned bydiff --git a/src/web/src/hooks/community/use-messages.test.ts b/src/web/src/hooks/community/use-messages.test.tsindex 493446839..78a961a69 100644--- a/src/web/src/hooks/community/use-messages.test.ts+++ b/src/web/src/hooks/community/use-messages.test.ts@@ -1,7 +1,7 @@import { describe, it, expect, vi, beforeEach } from "vitest"import { QueryClient, type InfiniteData } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"-import type { Msg } from "@/components/community/_types"+import type { Msg } from "@/lib/community/models/message"const apiFetchMock = vi.fn()vi.mock("@/lib/api/client", () => ({diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.tsindex e5c4ab321..449a5d3e2 100644--- a/src/web/src/hooks/community/use-messages.ts+++ b/src/web/src/hooks/community/use-messages.ts@@ -9,8 +9,12 @@ import {import { useCallback, useEffect, useMemo, useRef, useState } from "react"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"-import type { Msg } from "@/components/community/_types"-import { flushPendingReads } from "@/hooks/community/mutations/messages"+import type {+ MessagesPage,+ MessagesPageParam,+ Msg,+} from "@/lib/community/models/message"+import { flushPendingReads } from "@/lib/community/pending-reads"import {materializeMessageStream,type CanonicalMessage,@@ -36,29 +40,7 @@ import { useMessageOverlay, useMessageStreamStore } from "@/stores/community/mes* single `invalidateQueries({ queryKey: communityKeys.channelMessages(id) })`* refreshes every page in one call.*/-export type MessagesPage = {- messages: Msg[]- latestSeq?: number- // Anchor / since mode- hasMoreOlder?: boolean- hasMoreNewer?: boolean- olderCursor?: string- newerCursor?: string- // Legacy (newest + older continuation) mode- hasMore?: boolean- cursor?: string-}--// Discriminated pageParam. The queryFn dispatches on `mode` — the URL param-// map is: newest → no param, older → cursor, newer/since → since, anchor →-// anchor. Since is reserved for future direct catch-up (Commit C); A2 never-// fires it, but the type covers it so the server contract stays honest.-export type MessagesPageParam =- | { mode: "newest" }- | { mode: "anchor"; anchor: string }- | { mode: "since"; since: string }- | { mode: "older"; cursor: string }- | { mode: "newer"; cursor: string }+export type { MessagesPage, MessagesPageParam } from "@/lib/community/models/message"function buildMessagesUrl(base: string, pageParam: MessagesPageParam, tag?: string | null): string {const params = new URLSearchParams()diff --git a/src/web/src/hooks/community/use-scroll-anchor.compensate-delta.test.ts b/src/web/src/hooks/community/use-scroll-anchor.compensate-delta.test.tsindex c3c9ab298..606fa8333 100644--- a/src/web/src/hooks/community/use-scroll-anchor.compensate-delta.test.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.compensate-delta.test.ts@@ -2,7 +2,7 @@ import { describe, it, expect } from "vitest"import React from "react"import TestRenderer, { act } from "react-test-renderer"import { useScrollAnchor } from "./use-scroll-anchor"-import type { FlatItem } from "@/components/community/message-list-items"+import type { FlatItem } from "@/lib/community/message-list-items"// Render-level coverage for something `computeHeroScrollCompensation`'s// pure-function tests can't reach — it lives in `useScrollAnchor`'s effectdiff --git a/src/web/src/hooks/community/use-scroll-anchor.test.ts b/src/web/src/hooks/community/use-scroll-anchor.test.tsindex b968b0165..afe805cab 100644--- a/src/web/src/hooks/community/use-scroll-anchor.test.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.test.ts@@ -11,7 +11,7 @@ import {type ScrollAnchorState,type ScrollAnchorMessage,} from "./use-scroll-anchor"-import type { FlatItem } from "@/components/community/message-list-items"+import type { FlatItem } from "@/lib/community/message-list-items"import type { VirtualItem } from "@tanstack/react-virtual"const msgs = (...ids: string[]): ScrollAnchorMessage[] => ids.map((id) => ({ id }))diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.tsindex f58872396..a3c8c5901 100644--- a/src/web/src/hooks/community/use-scroll-anchor.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.ts@@ -1,7 +1,7 @@import { useCallback, useLayoutEffect, useRef } from "react"import { useVirtualizer, type ReactVirtualizer, type VirtualItem } from "@tanstack/react-virtual"import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS } from "./virtualizer-react-options"-import { estimateRowHeight, computeBelowCount, type FlatItem } from "@/components/community/message-list-items"+import { estimateRowHeight, computeBelowCount, type FlatItem } from "@/lib/community/message-list-items"// Virtualized rewrite of message-list's scroll-anchoring logic. The// pre-virtualization version (see git history) hand-rolled 4 branches —diff --git a/src/web/src/hooks/community/use-server-members.test.ts b/src/web/src/hooks/community/use-server-members.test.tsindex 42225bdf5..967c48024 100644--- a/src/web/src/hooks/community/use-server-members.test.ts+++ b/src/web/src/hooks/community/use-server-members.test.ts@@ -27,7 +27,7 @@ import {type MemberOverlayEvent,} from "./use-server-members"import { communityKeys } from "@/lib/query-keys"-import type { Member } from "@/components/community/_types"+import type { Member } from "@/lib/community/models/people"import type {CommunityMemberJoin,CommunityMemberLeave,diff --git a/src/web/src/hooks/community/use-server-members.ts b/src/web/src/hooks/community/use-server-members.tsindex 6aa768ca8..85e10f37c 100644--- a/src/web/src/hooks/community/use-server-members.ts+++ b/src/web/src/hooks/community/use-server-members.ts@@ -8,7 +8,7 @@ import {} from "@tanstack/react-query"import { apiFetch, toastApiError } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"-import type { Member } from "@/components/community/_types"+import type { Member } from "@/lib/community/models/people"import type {CommunityMemberJoin,CommunityMemberLeave,diff --git a/src/web/src/hooks/community/use-server-panels.ts b/src/web/src/hooks/community/use-server-panels.tsindex 762df20e0..e944d5dd3 100644--- a/src/web/src/hooks/community/use-server-panels.ts+++ b/src/web/src/hooks/community/use-server-panels.ts@@ -3,7 +3,7 @@import { useQuery, keepPreviousData, type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"-import type { InviteRow } from "@/components/community/_types"+import type { InviteRow } from "@/lib/community/models/people"class StaleReadError extends Error {constructor() { super("stale D1 read"); this.name = "StaleReadError" }diff --git a/src/web/src/hooks/community/use-servers.ts b/src/web/src/hooks/community/use-servers.tsindex 8c4e886c9..de77bd7e8 100644--- a/src/web/src/hooks/community/use-servers.ts+++ b/src/web/src/hooks/community/use-servers.ts@@ -5,7 +5,7 @@ import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import { avatarInitial } from "@/lib/community/avatar"import { isServerOwner, UNCATEGORIZED_CATEGORY_ID } from "@alook/shared"-import type { Server, Category, Channel } from "@/components/community/_types"+import type { Server, Category, Channel } from "@/lib/community/models/navigation"/*** Fetches the sidebar list of servers the current user is in.diff --git a/src/web/src/components/community/eject-server.test.ts b/src/web/src/lib/community/eject-server.test.tssimilarity index 98%rename from src/web/src/components/community/eject-server.test.tsrename to src/web/src/lib/community/eject-server.test.tsindex 0646f2045..682e8eca1 100644--- a/src/web/src/components/community/eject-server.test.ts+++ b/src/web/src/lib/community/eject-server.test.ts@@ -6,7 +6,7 @@ import {runAuthoritativeServerEject,isDefinitiveChildMetaFailure,} from "./eject-server"-import type { Server } from "./_types"+import type { Server } from "./models/navigation"import { ApiError } from "@/lib/errors"function makeServer(id: string): Server {diff --git a/src/web/src/components/community/eject-server.ts b/src/web/src/lib/community/eject-server.tssimilarity index 98%rename from src/web/src/components/community/eject-server.tsrename to src/web/src/lib/community/eject-server.tsindex 1f324271a..7263e73f9 100644--- a/src/web/src/components/community/eject-server.ts+++ b/src/web/src/lib/community/eject-server.ts@@ -1,4 +1,4 @@-import type { Server } from "./_types"+import type { Server } from "./models/navigation"import { ApiError } from "@/lib/errors"// Module-scoped marker set. The "Leave" button in the server rail marksdiff --git a/src/web/src/lib/community/fanout.ts b/src/web/src/lib/community/fanout.tsindex 654e537de..a84122ddc 100644--- a/src/web/src/lib/community/fanout.ts+++ b/src/web/src/lib/community/fanout.ts@@ -220,7 +220,7 @@ async function getProfileAudience(db: Database, userId: string): Promise<string[* (server co-members + friends). Self is intentionally excluded from their* own audience — the caller updates the local WS store directly on save* success instead (see `setUserStatus` call sites in `shell-frame.tsx` /- * `edit-profile-dialog.tsx`).+ * `settings/user-settings.tsx`).*/export async function fanOutStatusUpdate(userId: string,diff --git a/src/web/src/components/community/format-time.ts b/src/web/src/lib/community/format-time.tssimilarity index 100%rename from src/web/src/components/community/format-time.tsrename to src/web/src/lib/community/format-time.tsdiff --git a/src/web/src/lib/community/mention-extension.test.ts b/src/web/src/lib/community/mention-extension.test.tsindex 2ae4a64bf..811508ec5 100644--- a/src/web/src/lib/community/mention-extension.test.ts+++ b/src/web/src/lib/community/mention-extension.test.ts@@ -1,5 +1,5 @@import { describe, it, expect, vi } from "vitest"-import type { Member } from "@/components/community/_types"+import type { Member } from "@/lib/community/models/people"import {buildCommunityMentionExtension,rankMentionItems,diff --git a/src/web/src/lib/community/mention-extension.ts b/src/web/src/lib/community/mention-extension.tsindex c4b381a04..2f68a03c1 100644--- a/src/web/src/lib/community/mention-extension.ts+++ b/src/web/src/lib/community/mention-extension.ts@@ -1,6 +1,6 @@import Mention from "@tiptap/extension-mention"import { MENTION_TYPES, type MentionType } from "@alook/shared"-import type { Member } from "@/components/community/_types"+import type { Member } from "@/lib/community/models/people"export type MentionContext = "channel" | "thread" | "dm"diff --git a/src/web/src/components/community/message-list-items.test.ts b/src/web/src/lib/community/message-list-items.test.tssimilarity index 99%rename from src/web/src/components/community/message-list-items.test.tsrename to src/web/src/lib/community/message-list-items.test.tsindex e8ef30437..eb90cd1b9 100644--- a/src/web/src/components/community/message-list-items.test.ts+++ b/src/web/src/lib/community/message-list-items.test.ts@@ -1,6 +1,6 @@import { describe, it, expect } from "vitest"import { flattenMessageItems, estimateRowHeight, computeBelowCount } from "./message-list-items"-import type { Msg } from "./_types"+import type { Msg } from "./models/message"function msg(overrides: Partial<Msg> & { id: string }): Msg {return {diff --git a/src/web/src/components/community/message-list-items.ts b/src/web/src/lib/community/message-list-items.tssimilarity index 99%rename from src/web/src/components/community/message-list-items.tsrename to src/web/src/lib/community/message-list-items.tsindex f3d3f9921..673e6f4e1 100644--- a/src/web/src/components/community/message-list-items.ts+++ b/src/web/src/lib/community/message-list-items.ts@@ -1,5 +1,5 @@import { dateKey, formatDateLabel } from "./format-time"-import type { Msg, RenderMsg } from "./_types"+import type { Msg, RenderMsg } from "./models/message"function messageDisplayKey(message: Msg): string {const nonce = message.clientNoncediff --git a/src/web/src/lib/community/message-stream.test.ts b/src/web/src/lib/community/message-stream.test.tsindex ea329d6b4..a16c58605 100644--- a/src/web/src/lib/community/message-stream.test.ts+++ b/src/web/src/lib/community/message-stream.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest"-import type { Msg } from "@/components/community/_types"+import type { Msg } from "@/lib/community/models/message"import {MAX_LIVE_MESSAGE_DELTAS,emptyMessageOverlay,diff --git a/src/web/src/lib/community/message-stream.ts b/src/web/src/lib/community/message-stream.tsindex 8bcd6d3e1..7a34d972c 100644--- a/src/web/src/lib/community/message-stream.ts+++ b/src/web/src/lib/community/message-stream.ts@@ -1,4 +1,4 @@-import type { Msg } from "@/components/community/_types"+import type { Msg } from "@/lib/community/models/message"import type { MentionType } from "@alook/shared"import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"import { formatAttachmentSize } from "@/lib/community/attachment-presentation"diff --git a/src/web/src/lib/community/message-wire.ts b/src/web/src/lib/community/message-wire.tsindex d6763cdf5..abda4a507 100644--- a/src/web/src/lib/community/message-wire.ts+++ b/src/web/src/lib/community/message-wire.ts@@ -1,5 +1,5 @@import type { CommunityMessageCreate } from "@alook/shared"-import type { Msg } from "@/components/community/_types"+import type { Msg } from "@/lib/community/models/message"import { avatarInitial } from "@/lib/community/avatar"import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"import { formatAttachmentSize } from "@/lib/community/attachment-presentation"diff --git a/src/web/src/lib/community/models/inbox.ts b/src/web/src/lib/community/models/inbox.tsnew file mode 100644index 000000000..a478d7c93--- /dev/null+++ b/src/web/src/lib/community/models/inbox.ts@@ -0,0 +1,83 @@+import type { MentionKind } from "@alook/shared"+import type { EntityKind } from "./navigation"+import type { Msg } from "./message"++// ── Mentions / inbox ─────────────────────────────────────────────────────────+export type Mention = {+ id: string+ // "mention" (@-mention) vs "reply" (reply to your message). Drives the row+ // label ("mentioned you" vs "replied to you"). Optional for back-compat with+ // any cached payload written before the field existed.+ kind?: MentionKind+ server: string+ serverId?: string+ channel: string+ channelId?: string+ m: Msg+}++// A single per-user saved ("marked") message, as returned by+// `/api/community/users/me/marks`. Cross-channel newest-first — each row carries+// the serverId + channelId + seq needed to deep-link back to the message+// (unlike a Mention, which only opens the channel, a Marked row jumps to the+// exact message via the `?msg=<id>` deep-link). `id` is the mark row's own id,+// used to unmark from the list.+export type Marked = {+ id: string // the mark row id (for DELETE / list removal)+ // A DM has no server: `serverId` is null and `server` may be the peer's name+ // or empty. The null serverId is the discriminator the jump uses — server+ // rows deep-link via `?msg=`, DM rows navigate to `/c/me/<channelId>` and+ // open the context sheet.+ server: string+ serverId: string | null+ channel: string+ // For a server message this is the channel id; for a DM it's the DM channel+ // id, which is also the frontend `/c/me/<id>` route param.+ channelId: string+ m: Msg+}++// A single unread child thread nested under its parent channel.+type UnreadChild = {+ channelId: string+ channelName: string+ // Raw stored channel type — drives the inbox entity icon (thread →+ // MessagesSquare). Optional for backward-compat with cached responses.+ type?: EntityKind+ lastMessageAt: string+ mentionCount: number+ // Present when this row projects an unread opener from the parent forum.+ // The child id remains the navigation target; this opener id is the parent+ // channel's progressive-read target.+ openerMessageId?: string+}++// "Unreads" — channels with unread messages, grouped by server. Each channel+// may carry `children` (unread child threads) rendered as indented+// sub-rows; a parent can appear solely to host unread children.+export type UnreadServer = {+ serverId: string+ serverName: string+ channels: Array<{+ channelId: string+ channelName: string+ // Raw stored channel type — drives the inbox entity icon so a forum+ // channel shows the forum glyph, not a generic hash.+ type?: EntityKind+ lastMessageAt: string+ mentionCount: number+ children: UnreadChild[]+ }>+}++// "Unreads" — DMs with unread messages, rendered as a flat sibling section+// under the same Unreads tab as channels.+export type UnreadDm = {+ // The DM's channel id (a DM is a channel now). Kept as the row's stable key+ // and the value passed to `onOpenDm` / the `/c/me/:id` route.+ channelId: string+ otherUserId: string+ otherUserName: string+ otherUserAvatar: string+ lastMessageAt: string+}diff --git a/src/web/src/lib/community/models/message.ts b/src/web/src/lib/community/models/message.tsnew file mode 100644index 000000000..57eb59c04--- /dev/null+++ b/src/web/src/lib/community/models/message.ts@@ -0,0 +1,154 @@+import type { FriendApprovalPayload } from "@alook/shared"++// ── Messages ───────────────────────────────────────────────────────────────+type AttachmentMetadata = {+ name: string+ url: string+ contentType?: string+ sizeBytes?: number+}++export type FileAttachment = AttachmentMetadata & { kind: "file"; size: string }++export type Attachment =+ | (AttachmentMetadata & { kind: "image"; thumbnailUrl?: string; width?: number; height?: number })+ | FileAttachment++export type ImagePreview = { originalUrl: string; thumbnailUrl?: string; name: string }++type Embed = {+ provider?: string+ url?: string+ title: string+ desc?: string+ color?: string+ image?: { url: string; width?: number; height?: number }+ thumbnail?: { url: string }+ fields?: { name: string; value: string; inline?: boolean }[]+ footer?: { text: string; iconUrl?: string }+ author?: { name: string; url?: string; iconUrl?: string }+}++export type Reaction = { emoji: string; count: number; me: boolean; userIds: string[] }++export type Msg = {+ id: string // nanoid+ // Exhaustive discriminator (#12 — was `type?: "system"`, an incomplete+ // partial discriminator that let `!m.type` silently misclassify a future+ // third kind as an ordinary chat message). `mapMessageForApi`/`mapMessageForWs`+ // always emit one of these two values now — never `undefined`.+ type: "chat" | "system"+ // Only ever set alongside `type: "system"` for a thread-creation system+ // message (see `message-payload.ts`'s `splitType`). The `"join"` value+ // that used to be part of this type is removed — no code path has ever+ // produced it (join notifications are pure WS events with no persisted+ // message row, and stay that way — see the debt-record's Out of scope).+ systemKind?: "thread"+ // Author's user id — populated by `mapMessageForApi` / WS message-create,+ // consumed by `useChannelWatermark` to skip self-authored messages when+ // advancing the read pointer. Optional to keep optimistic rows valid+ // before the server response reconciles.+ authorId?: string+ authorName?: string+ color?: string+ seq?: number // Per-scope (channel/DM) monotonic sequence number+ createdAt?: string // ISO 8601 timestamp — the UI formats for display+ authorAvatar?: string+ failed?: boolean+ // Idempotency nonce (mutation-idempotency plan). Stamped on optimistic rows+ // this client created and echoed back on the WS message-create, so a+ // 500-after-commit send that the user never retried self-heals: the WS row+ // reconciles the failed optimistic row by nonce instead of appearing twice.+ clientNonce?: string+ content?: string+ embeds?: Embed[]+ attachments?: Attachment[]+ reactions?: Reaction[]+ replyTo?: { id: string; authorName: string; text: string; deleted?: boolean }+ thread?: {+ id: string+ name: string+ messageCount: number+ lastReplyAt?: string+ tags?: string[]+ preview?: string+ participants?: { id: string; name: string; avatar: string }[]+ participantCount?: number+ }+ // Present only on a friend-approval DM card. Its presence (not the message+ // `type`) is the discriminator for rendering <BotApprovalCard>.+ approval?: FriendApprovalPayload+}++// `grouped` is a RENDER-TIME decision (computed by `message-list.tsx`'s+// cluster-building `useMemo`, based on adjacent messages' author/timestamp)+// — never a fact about a message itself, so it never belonged on `Msg`+// (#7). `<Message>` and any other consumer that needs the clustering+// decision takes a `RenderMsg`, not a bare `Msg` with `grouped` spread on.+export type RenderMsg = Msg & { grouped: boolean }++// ── Threads / forum ──────────────────────────────────────────────────────────+// Child-thread summaries shown in side panels and forum lists. Actual+// message content for a thread or post is loaded into `ctx.messages` once the+// user navigates into the child channel — these summaries don't carry messages.+export type Thread = {+ id: string // nanoid+ name: string+ messageCount: number+ lastMessageAt: string+ parent: { authorName: string; text: string }+ // The root message's per-channel seq, when the thread was created from a+ // parent message (omitted only for legacy rootless threads).+ // Used by `channel-ref-pill.tsx` to match a `/server/channel/#N` ref.+ parentSeq?: number+ // Stable opener identity used to reconcile forum-title edits without+ // accidentally patching a same-named or re-rooted child.+ openerMessageId?: string+}++export type ForumThread = Thread & {+ authorId: string+ authorAvatar: string+ openerMessageId: string+ tags: string[]+ preview: string+ // The post's participant (notify) set — creator first, then whoever+ // spoke/was mentioned/was added. Drives the card's AvatarGroup. Always+ // present (empty for a post with no participant rows yet, e.g. one created+ // before the notify-scope change shipped).+ participants: { id: string; name: string; avatar: string }[]+ // Total participant rows before the card-preview cap is applied.+ participantCount: number+}++export type SendAttachment = {+ file: File+ thumbnailBlob?: Blob+ previewObjectUrl?: string+ width?: number+ height?: number+}++export type MessagesPage = {+ messages: Msg[]+ latestSeq?: number+ // Anchor / since mode+ hasMoreOlder?: boolean+ hasMoreNewer?: boolean+ olderCursor?: string+ newerCursor?: string+ // Legacy (newest + older continuation) mode+ hasMore?: boolean+ cursor?: string+}++// Discriminated pageParam. The queryFn dispatches on `mode` — the URL param+// map is: newest → no param, older → cursor, newer/since → since, anchor →+// anchor. Since is reserved for future direct catch-up; the type covers it so+// the server contract stays honest.+export type MessagesPageParam =+ | { mode: "newest" }+ | { mode: "anchor"; anchor: string }+ | { mode: "since"; since: string }+ | { mode: "older"; cursor: string }+ | { mode: "newer"; cursor: string }diff --git a/src/web/src/lib/community/models/navigation.ts b/src/web/src/lib/community/models/navigation.tsnew file mode 100644index 000000000..ea45b2d13--- /dev/null+++ b/src/web/src/lib/community/models/navigation.ts@@ -0,0 +1,53 @@+import type { ChannelType } from "@alook/shared"++export type EntityKind = "text" | "forum" | "thread"++// ── Servers / rail ───────────────────────────────────────────────────────────+export type Server = {+ id: string // nanoid+ name: string+ discriminator?: string+ initial: string+ active: boolean+ mentions: number+ isOwner?: boolean+ icon?: string | null+}++export type FolderServer = {+ id: string+ initial: string+ name: string+ icon?: string | null+}++export type CommunityFolder = {+ id: string+ name: string+ position: number+ servers: FolderServer[]+}++// ── Channels / categories ────────────────────────────────────────────────────+export type Channel = {+ id: string // nanoid+ name: string+ active: boolean+ unread: boolean+ muted?: boolean+ type?: ChannelType+ tags?: string[]+ creatorId?: string | null+ // Optimistic placeholder row — non-interactive until the create resolves.+ pending?: boolean+}++export type Category = {+ id: string+ name: string+ channels: Channel[]+ private?: number | boolean+ creatorId?: string | null+ // Optimistic placeholder category — reconciled when the create resolves.+ pending?: boolean+}diff --git a/src/web/src/lib/community/models/people.ts b/src/web/src/lib/community/models/people.tsnew file mode 100644index 000000000..06e4e7327--- /dev/null+++ b/src/web/src/lib/community/models/people.ts@@ -0,0 +1,89 @@+export type Presence = "online" | "offline"++// ── Members / friends / DMs ──────────────────────────────────────────────────+// Identity fields shared by every community user view-model (member / friend /+// DM). All three are required `string`: `user.name`/`user.discriminator` are+// NOT NULL columns always projected on live payloads. Requiring `discriminator`+// here (in one place) moves the "a mention target always has a tag" guarantee+// to compile time — see plans/mandatory-mention-discriminator.md. `userId` is+// NOT part of the core: it's required on Member/DM but optional on Friend, so+// each type declares it. Only types whose identity fields are identically+// shaped extend this — AddableMember/ThreadParticipant (nullable projections),+// Profile/UserProfile (renamed/merged shapes) intentionally stay standalone.+export type CommunityUserCore = {+ name: string+ discriminator: string+ avatar: string+}++export type Member = CommunityUserCore & {+ id: string+ userId: string+ status: Presence+ sub: string+ role: import("@alook/shared").CommunityRole+ // Custom status (emoji + short term) — see `Profile.statusEmoji`/`statusText`.+ statusEmoji?: string | null+ statusText?: string | null+ // Populated only when the drawer shows a private channel/post roster or a+ // thread participant set — drives the row's Leave/Remove right-click menu.+ // - isCreator: this user owns the unit (row locked — never removable/leaveable).+ // - source: for a channel/post, only "explicit" rows are removable (an+ // admin-by-role or inherited public member isn't an explicit roster row).+ // Thread participants are always "explicit"-equivalent (a real row).+ isCreator?: boolean+ source?: "explicit" | "inherited" | "admin"+}++export type Friend = CommunityUserCore & {+ id: string+ // Optional here (unlike Member/DM) — some friend rows predate a resolved+ // userId; that's the one field that keeps Friend from a plain intersection.+ userId?: string+ status: Presence+ sub: string+ // Custom status (emoji + short term) — see `Profile.statusEmoji`/`statusText`.+ statusEmoji?: string | null+ statusText?: string | null+}++export type PendingRequest = {+ id: string+ userId: string+ name: string+ avatar: string+ kind: "incoming" | "outgoing"+ // The gating owner id while a bot-touched row is pending; null once+ // unlocked. Drives whether Approve/Reject buttons render.+ needsOwnerApproval?: string | null+}++export type BlockedUser = { id: string; userId?: string; name: string; avatar: string }++// DM summary shown in the DM sidebar. Actual conversation history is loaded+// into `ctx.messages` once the user opens the DM — DM summaries don't carry+// inline messages.+export type DM = CommunityUserCore & {+ id: string // DM conversation nanoid — NOT the peer's user id (that's `userId`)+ userId: string+ status: Presence+ preview: string+ unread?: boolean+}++// ── Settings rows ──────────────────────────────────────────────────────────+export type InviteRow = {+ code: string+ uses: number+ maxUses: number | null // null = unlimited+ expiresAt: string | null // ISO timestamp or null = never+ by: string+ creatorId: string | null+}++export type BotActivityDay = {+ // Calendar day, "YYYY-MM-DD".+ day: string+ handledCount: number+ sentCount: number+}diff --git a/src/web/src/lib/community/pending-reads.ts b/src/web/src/lib/community/pending-reads.tsnew file mode 100644index 000000000..c915cdca3--- /dev/null+++ b/src/web/src/lib/community/pending-reads.ts@@ -0,0 +1,126 @@+import { apiFetch } from "@/lib/api/client"++export const MARK_CHANNEL_READ_DEBOUNCE_MS = 500++/**+ * A single pending mark-read carries the debounce timer, a `fire` closure,+ * and the most recently queued `messageId` (or `undefined` for a no-body+ * mass mark-read). Re-scheduling within the debounce window replaces the+ * pending `messageId` — monotone forward semantics live one layer up in+ * `useChannelWatermark`, so this layer just uses whichever value the last+ * caller passed.+ *+ * Both the timer callback and `flushPendingReads()` invoke `fire` — same+ * code path, whether the window elapsed naturally or was flushed early.+ */+type PendingRead = {+ timer: ReturnType<typeof setTimeout>+ fire: () => void+ // Latest queued message id — captured in the closure so `fire` reads the+ // freshest value even after the timer was scheduled with a stale one.+ messageId: string | undefined+}++const pendingReads = new Map<string, PendingRead>()++export function _resetPendingReads_forTesting() {+ for (const p of pendingReads.values()) clearTimeout(p.timer)+ pendingReads.clear()+}++/**+ * Flush every pending mark-read immediately. Each entry's `fire` runs the+ * same code the timer would have — so `onDone` (typically the inbox+ * invalidate) still fires exactly once per PUT, even when a caller flushes+ * mid-window.+ */+export function flushPendingReads() {+ const pending = [...pendingReads.values()]+ for (const p of pending) {+ clearTimeout(p.timer)+ p.fire()+ }+}++export type ScheduleMarkReadOpts = {+ /**+ * When set, PUT `{ lastReadMessageId }` — advances the read pointer to+ * that message's `(createdAt, id)`. Omit for the mass mark-read case+ * (no body). The mutation layer trusts whatever value the caller passes+ * most recently; monotonicity is the caller's responsibility (see+ * `useChannelWatermark` / `useDmWatermark`). Body key matches the DM ++ * thread read routes.+ */+ messageId?: string+ onDone: () => void+}++/**+ * Resolve a schedule key to a target read-endpoint URL. The debounce key+ * is a string namespace so `channelId` and `dm:<dmId>` coexist in the same+ * `pendingReads` map without ever aliasing each other — a channel and a+ * DM with the same underlying id would otherwise share a debounce slot+ * and clobber each other's pointers.+ *+ * Channel keys are bare ids (legacy — the debounce was channel-only+ * before B2). DM keys are prefixed with `"dm:"` so the map stays keyed by+ * unique strings without a discriminated-union tag on `PendingRead`.+ */+function resolveReadEndpoint(key: string): string {+ // DM and channel both resolve through the one canonical read door (a DM is a+ // channel row in the same id-space); the `dm:` key prefix only strips to the+ // channelId, no per-type URL fork.+ const channelId = key.startsWith("dm:") ? key.slice(3) : key+ return `/api/community/channels/${channelId}/read`+}++/**+ * Debounce a mark-read PUT. Same-key re-invokes within the 500ms window+ * replace the pending intent (previous `messageId` and `onDone` are+ * dropped; the new pair takes over). Nothing is left "hanging" because+ * `mutationFn` no longer awaits the debounced work.+ *+ * `key` is a string namespace: a bare `channelId` for channel/thread reads+ * (legacy contract — every existing call site passes a channel id+ * directly) or `"dm:<dmId>"` for DM reads. `resolveReadEndpoint` maps the+ * key back to the target URL. Consumers should never build the DM+ * namespace directly — call `useAdvanceDmWatermark` which handles it.+ */+export function scheduleMarkRead(+ key: string,+ opts: ScheduleMarkReadOpts,+): void {+ const existing = pendingReads.get(key)+ if (existing) clearTimeout(existing.timer)+ // `entry` is captured inside `fire` so it can read the freshest+ // `messageId` at the moment the PUT actually issues — even if a later+ // schedule call updated it in place. Cleaner than closing over a mutable+ // outer variable.+ const entry: PendingRead = {+ // Timer is filled in below after fire is defined.+ timer: undefined as unknown as ReturnType<typeof setTimeout>,+ messageId: opts.messageId,+ fire: () => {+ // Idempotent: if the map has already moved on (fire ran, or a fresh+ // scheduling replaced us), do nothing. This is what makes it safe for+ // both the timer AND `flushPendingReads()` to call `fire` in the same+ // tick — only the first wins.+ const cur = pendingReads.get(key)+ if (cur !== entry) return+ pendingReads.delete(key)+ const body = entry.messageId+ ? JSON.stringify({ lastReadMessageId: entry.messageId })+ : undefined+ const init: RequestInit = body+ ? { method: "PUT", body }+ : { method: "PUT" }+ void apiFetch(resolveReadEndpoint(key), init)+ .then(() => opts.onDone())+ .catch(() => {+ // Silent — the inbox will reconcile once the WS invalidate fires.+ })+ },+ }+ entry.timer = setTimeout(entry.fire, MARK_CHANNEL_READ_DEBOUNCE_MS)+ pendingReads.set(key, entry)+}diff --git a/src/web/src/lib/community/presence.ts b/src/web/src/lib/community/presence.tsindex 82e363264..48666645e 100644--- a/src/web/src/lib/community/presence.ts+++ b/src/web/src/lib/community/presence.ts@@ -1,4 +1,4 @@-import type { Presence } from "@/components/community/_types"+import type { Presence } from "@/lib/community/models/people"/*** The single client-side presence-overlay helper.diff --git a/src/web/src/lib/query-persister.test.ts b/src/web/src/lib/query-persister.test.tsindex 00b5e529d..06d2129f4 100644--- a/src/web/src/lib/query-persister.test.ts+++ b/src/web/src/lib/query-persister.test.ts@@ -11,7 +11,7 @@ import {shouldPersistQuery,shouldPersistQueryKey,} from "@/lib/query-persister"-import type { MessagesPage } from "@/hooks/community/use-messages"+import type { MessagesPage } from "@/lib/community/models/message"// ── shouldPersistQueryKey ─────────────────────────────────────────────────diff --git a/src/web/src/lib/query-persister.ts b/src/web/src/lib/query-persister.tsindex 7e8e5b562..3c8c8a0a8 100644--- a/src/web/src/lib/query-persister.ts+++ b/src/web/src/lib/query-persister.ts@@ -4,8 +4,7 @@ import type {Persister,} from "@tanstack/react-query-persist-client"import { del, get, set } from "idb-keyval"-import type { Msg } from "@/components/community/_types"-import type { MessagesPage } from "@/hooks/community/use-messages"+import type { MessagesPage, Msg } from "@/lib/community/models/message"/*** IDB namespace root. Bumping the tail segment (`v1` → `v2`) invalidates everydiff --git a/src/web/src/stores/community/index.test.ts b/src/web/src/stores/community/index.test.tsindex 6d5eebed9..2902e639f 100644--- a/src/web/src/stores/community/index.test.ts+++ b/src/web/src/stores/community/index.test.ts@@ -8,7 +8,7 @@ import { useCommunityStore } from "./index"const { flushPendingReadsSpy } = vi.hoisted(() => ({flushPendingReadsSpy: vi.fn(),}))-vi.mock("@/hooks/community/mutations/messages", () => ({+vi.mock("@/lib/community/pending-reads", () => ({flushPendingReads: flushPendingReadsSpy,}))@@ -124,9 +124,9 @@ describe("useCommunityStore", () => {})it("reset flushes pending mark-reads before wiping state", async () => {- // `reset()` uses a dynamic import to avoid a circular dependency with- // `mutations/messages`. The `import()` resolves asynchronously — poll- // via `vi.waitFor` instead of assuming a fixed microtask count.+ // `reset()` uses a dynamic import so store initialization does not load+ // the queue implementation eagerly. Poll instead of assuming a fixed+ // microtask count.useCommunityStore.getState().reset()await vi.waitFor(() => expect(flushPendingReadsSpy).toHaveBeenCalledTimes(1))})diff --git a/src/web/src/stores/community/index.ts b/src/web/src/stores/community/index.tsindex f61c476a8..9d4366a3a 100644--- a/src/web/src/stores/community/index.ts+++ b/src/web/src/stores/community/index.ts@@ -3,6 +3,7 @@import { create } from "zustand"import { useShallow } from "zustand/react/shallow"import type React from "react"+import type { FileAttachment, ImagePreview } from "@/lib/community/models/message"/*** Zustand store for community client-only state.@@ -72,8 +73,8 @@ type CommunitySubscription = {}type CommunityUiHandlers = {- previewImage?: (image: import("@/components/community/_types").ImagePreview) => void- previewAttachment?: (attachment: import("@/components/community/_types").FileAttachment) => void+ previewImage?: (image: ImagePreview) => void+ previewAttachment?: (attachment: FileAttachment) => voidopenProfile?: (name: string, e: React.MouseEvent, discriminator?: string, userId?: string) => voidgoBackMobile?: () => void// Jump to message `seq` within the CURRENT channel/DM — the page registers@@ -243,12 +244,11 @@ export const useCommunityStore = create<CommunityStoreState>((set, get) => ({reset: () => {// Flush any pending mark-channel-read PUTs before we wipe local state so// the last-read pointer isn't stranded in the 500ms debounce window- // (sign-out, hard-reset, tab close). Dynamic import avoids a circular- // dependency: `mutations/messages.ts` already imports this store, so a- // static import here would form a cycle. Fire-and-forget is fine — the- // PUTs go out under the still-live auth cookie.- void import("@/hooks/community/mutations/messages").then((m) =>- m.flushPendingReads(),+ // (sign-out, hard-reset, tab close). Dynamic import avoids coupling the+ // store to the mutation hooks that consume this queue. Fire-and-forget is+ // fine — the PUTs go out under the still-live auth cookie.+ void import("@/lib/community/pending-reads").then((module) =>+ module.flushPendingReads(),)// Fire-and-forget: clear every outstanding timer so nothing lingers past// sign-out or a hard-reset.