Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): unify composer accessory rail and ws recovery (#523)

Gener8d55d5fde4d4
diff --git a/DESIGN.md b/DESIGN.md
index afc5b2c8f..c671c23a0 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -69,6 +69,7 @@ Inspired by vintage Macintosh product photography — a warm cream object on a d
| `border` / `input` / `ring` | Dividers, field outlines, and the focus ring. |
| `destructive` | Errors and irreversible actions only. Warm red — never repurpose it for emphasis. |
| `status-online` / `status-offline` | Presence dots only (green / red). Reserved — do not use as UI accents. |
+| `warning` | Recoverable degraded states that need attention without implying failure. Muted amber. |
| `sidebar-*` | Sidebar-scoped variants of the above, so the rail can read distinctly from content. |
Rules:
diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.css
index d4c94669d..f87bec51a 100644
--- a/src/web/src/app/globals.css
+++ b/src/web/src/app/globals.css
@@ -40,6 +40,7 @@
--color-status-online: var(--status-online);
--color-status-offline: var(--status-offline);
--color-destructive: var(--destructive);
+ --color-warning: var(--warning);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
@@ -349,6 +350,7 @@ body.community-onboarding-active.driver-active :is(
--accent: oklch(0.94 0.008 80);
--accent-foreground: oklch(0.22 0.03 230);
--destructive: oklch(0.577 0.245 27.325);
+ --warning: oklch(0.62 0.11 75);
--border: oklch(0.86 0.01 80);
--input: oklch(0.86 0.01 80);
--ring: oklch(0.55 0.03 230);
@@ -402,6 +404,7 @@ body.community-onboarding-active.driver-active :is(
--accent: oklch(0.27 0.008 60);
--accent-foreground: oklch(0.93 0.006 80);
--destructive: oklch(0.704 0.191 22.216);
+ --warning: oklch(0.76 0.1 75);
--border: oklch(1 0.005 80 / 10%);
--input: oklch(1 0.005 80 / 15%);
--ring: oklch(0.55 0.01 60);
diff --git a/src/web/src/components/community/messages/composer-accessory-rail.test.ts b/src/web/src/components/community/messages/composer-accessory-rail.test.ts
new file mode 100644
index 000000000..1d7af65ed
--- /dev/null
+++ b/src/web/src/components/community/messages/composer-accessory-rail.test.ts
@@ -0,0 +1,165 @@
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { tid } from "@/lib/community/testids"
+import { useCommunityWsStore } from "@/stores/community/ws"
+import { ComposerAccessoryRail } from "./composer-accessory-rail"
+
+vi.mock("@/components/ui/number-ticker", () => ({
+ NumberTicker: ({ value }: { value: number }) => React.createElement("ticker", { value }),
+}))
+
+vi.mock("@/components/ui/tooltip", () => ({
+ Tooltip: ({ children }: { children: React.ReactNode }) => React.createElement("tooltip", null, children),
+ TooltipTrigger: ({
+ render,
+ children,
+ }: {
+ render: React.ReactElement
+ children: React.ReactNode
+ }) => React.cloneElement(render, {}, children),
+ TooltipContent: ({ children }: { children: React.ReactNode }) => React.createElement("tooltip-content", null, children),
+}))
+
+const baseProps = {
+ typingNames: ["A very long teammate name that must not cover the center control"],
+ scrollCount: 4,
+ scrollMode: "jump" as const,
+ onScroll: vi.fn(),
+ selectMode: false,
+ selectedCount: 0,
+ onCancelSelection: vi.fn(),
+ onShareSelection: vi.fn(),
+}
+
+describe("ComposerAccessoryRail", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ useCommunityWsStore.getState().reset()
+ })
+
+ afterEach(() => {
+ useCommunityWsStore.getState().reset()
+ })
+
+ function render(overrides: Partial<typeof baseProps> = {}) {
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(React.createElement(ComposerAccessoryRail, {
+ ...baseProps,
+ ...overrides,
+ }))
+ })
+ return renderer!
+ }
+
+ it("owns the only floating position and lays out normal typing, scroll, and no healthy WS node", () => {
+ const renderer = render()
+ const rail = renderer.root.findByProps({ "data-testid": tid.composerAccessoryRail })
+ expect(rail.props.className).toContain("absolute")
+ expect(rail.props.className).toContain("px-2")
+ expect(rail.props.className).toContain("sm:px-4")
+ expect(renderer.root.findByProps({ "data-testid": tid.typingIndicator }).props.className)
+ .toContain("min-w-0")
+ expect(renderer.root.findByProps({ "data-testid": tid.scrollToPresent }).props["aria-label"])
+ .toBe("Jump to present, 4 unread below")
+ expect(renderer.root.findAllByProps({ "data-testid": tid.wsStatus })).toHaveLength(0)
+ expect(renderer.root.findAllByProps({ "data-testid": tid.wsRetry })).toHaveLength(0)
+
+ const positioned = renderer.root.findAll((node) =>
+ typeof node.props.className === "string" && node.props.className.includes("absolute"))
+ expect(positioned).toEqual([rail])
+ })
+
+ it("shows an accessible muted warning reconnecting control without a spinner", () => {
+ useCommunityWsStore.getState().setConnectionStatus("reconnecting")
+ const renderer = render({ scrollCount: 0, typingNames: [] })
+ const status = renderer.root.findByProps({ "data-testid": tid.wsStatus })
+ expect(status.props).toMatchObject({
+ "data-ws-status": "reconnecting",
+ "aria-label": "WebSocket reconnecting",
+ "aria-live": "polite",
+ role: "status",
+ tabIndex: 0,
+ })
+ expect(status.type).toBe("span")
+ expect(status.props.className).toContain("text-warning")
+ expect(status.props.className).toContain("focus-visible:ring-3")
+ expect(renderer.root.findByType("tooltip-content").children).toContain("Reconnecting…")
+ expect(renderer.root.findAll((node) => node.props.className?.includes("animate-spin"))).toHaveLength(0)
+ })
+
+ it("shows a destructive failed retry button with a 40px desktop hit target", () => {
+ const reconnectNow = vi.fn()
+ useCommunityWsStore.getState().bindReconnectNow(reconnectNow)
+ useCommunityWsStore.getState().setConnectionStatus("failed")
+ const renderer = render({ scrollCount: 0, typingNames: [] })
+ const retry = renderer.root.findByProps({ "data-testid": tid.wsRetry })
+ expect(retry.type).toBe("button")
+ expect(retry.props["aria-label"]).toBe("WebSocket connection failed. Retry now")
+ expect(retry.props.className).toContain("text-destructive")
+ expect(retry.props.className).toContain("sm:size-10")
+ act(() => retry.props.onClick())
+ expect(reconnectNow).toHaveBeenCalledOnce()
+ })
+
+ it("replaces scroll with selection controls and preserves desktop typing", () => {
+ const renderer = render({ selectMode: true, selectedCount: 3 })
+ const rail = renderer.root.findByProps({ "data-testid": tid.composerAccessoryRail })
+ expect(rail.props["data-selection"]).toBe("active")
+ expect(renderer.root.findAllByProps({ "data-testid": tid.scrollToPresent })).toHaveLength(0)
+ expect(renderer.root.findByProps({ "data-testid": tid.messageSelectionToolbar })).toBeTruthy()
+ expect(renderer.root.findByProps({ "data-testid": tid.typingIndicator })).toBeTruthy()
+
+ const grid = rail.findAllByType("div").find((node) => node.props.className?.includes("grid w-full"))!
+ expect(grid.props.className).toContain("grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)]")
+ })
+
+ it("uses a symmetric mobile selection grid with a compact capped toolbar and hides typing below sm", () => {
+ useCommunityWsStore.getState().setConnectionStatus("failed")
+ const renderer = render({ selectMode: true, selectedCount: 12 })
+ const rail = renderer.root.findByProps({ "data-testid": tid.composerAccessoryRail })
+ const grid = rail.findAllByType("div").find((node) => node.props.className?.includes("grid w-full"))!
+ expect(grid.props.className).toContain("grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)]")
+ expect(grid.props.className).toContain("gap-1")
+ expect(grid.props.className).toContain("sm:gap-2")
+
+ const typingParent = renderer.root.findAllByType("div")
+ .find((node) => node.props.className?.includes("hidden w-full min-w-0"))!
+ expect(typingParent.props.className).toContain("hidden")
+ expect(typingParent.props.className).toContain("w-full")
+ expect(typingParent.props.className).toContain("sm:block")
+ const toolbar = renderer.root.findByProps({ "data-testid": tid.messageSelectionToolbar })
+ expect(toolbar.props.className).toContain("h-10")
+ expect(toolbar.props.className).toContain("max-w-[calc(100vw-7rem)]")
+ expect(toolbar.props.className).toContain("sm:h-auto")
+ const toolbarSlot = rail.findAllByType("div")
+ .find((node) => node.props.className?.includes("col-start-2"))!
+ expect(toolbarSlot.props.className).toContain("justify-self-center")
+
+ const count = toolbar.findAllByType("span")
+ .find((node) => node.props.className?.includes("flex-1"))!
+ expect(count.children.join("")).toBe("12 selected")
+ expect(count.props.className).toContain("flex-1")
+ expect(count.props.className).toContain("truncate")
+
+ const cancel = renderer.root.findByProps({ "aria-label": "Cancel message selection" })
+ expect(cancel.props.className).toContain("h-8")
+ expect(cancel.props.className).toContain("w-11")
+ expect(cancel.props.className).toContain("after:-inset-y-1.5")
+
+ const share = renderer.root.findByProps({
+ "aria-label": "Share 12 selected messages as image",
+ })
+ expect(share.props.className).toContain("h-8")
+ expect(share.props.className).toContain("px-2")
+ expect(share.props.className).toContain("after:-inset-y-1.5")
+
+ const wsRetry = renderer.root.findByProps({ "data-testid": tid.wsRetry })
+ expect(wsRetry.props.className).toContain("size-11")
+ const wsSlot = rail.findAllByType("div")
+ .find((node) => node.props.className?.includes("col-start-3"))!
+ expect(wsSlot.props.className).toContain("min-w-11")
+ expect(wsSlot.props.className).toContain("justify-self-end")
+ })
+})
diff --git a/src/web/src/components/community/messages/composer-accessory-rail.tsx b/src/web/src/components/community/messages/composer-accessory-rail.tsx
new file mode 100644
index 000000000..9ba76a1a3
--- /dev/null
+++ b/src/web/src/components/community/messages/composer-accessory-rail.tsx
@@ -0,0 +1,214 @@
+"use client"
+
+import { ArrowDown, ImageIcon, Radio, WifiOff, X } from "lucide-react"
+import { Button } from "@/components/ui/button"
+import { NumberTicker } from "@/components/ui/number-ticker"
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
+import { tid } from "@/lib/community/testids"
+import { cn } from "@/lib/utils"
+import { useCommunityWsStore } from "@/stores/community/ws"
+import { TypingIndicator } from "./typing-indicator"
+
+export function ComposerAccessoryRail({
+ typingNames,
+ scrollCount,
+ scrollMode,
+ onScroll,
+ selectMode,
+ selectedCount,
+ onCancelSelection,
+ onShareSelection,
+}: {
+ typingNames: string[]
+ scrollCount: number
+ scrollMode: "scroll" | "jump"
+ onScroll: () => void
+ selectMode: boolean
+ selectedCount: number
+ onCancelSelection: () => void
+ onShareSelection: () => void
+}) {
+ const connectionStatus = useCommunityWsStore((state) => state.connectionStatus)
+ const reconnectNow = useCommunityWsStore((state) => state.reconnectNow)
+
+ return (
+ <div
+ data-testid={tid.composerAccessoryRail}
+ data-selection={selectMode ? "active" : "inactive"}
+ className="pointer-events-none absolute inset-x-0 bottom-3 z-20 px-2 sm:px-4"
+ >
+ <div
+ className={cn(
+ "grid w-full items-end gap-1 sm:gap-2",
+ selectMode
+ ? "grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)]"
+ : "grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)]",
+ )}
+ >
+ {selectMode ? (
+ <>
+ <div className="hidden w-full min-w-0 sm:col-start-1 sm:block">
+ <TypingIndicator names={typingNames} className="w-fit" />
+ </div>
+ <div className="col-start-2 min-w-0 justify-self-center">
+ <SelectionToolbar
+ selectedCount={selectedCount}
+ onCancel={onCancelSelection}
+ onShare={onShareSelection}
+ />
+ </div>
+ <div className="col-start-3 min-w-11 justify-self-end">
+ <WsStatusControl status={connectionStatus} onRetry={reconnectNow} />
+ </div>
+ </>
+ ) : (
+ <>
+ <div className="col-start-1 w-full min-w-0">
+ <TypingIndicator names={typingNames} className="w-fit" />
+ </div>
+ <div className="col-start-2 justify-self-center">
+ <ScrollControl count={scrollCount} mode={scrollMode} onClick={onScroll} />
+ </div>
+ <div className="col-start-3 justify-self-end">
+ <WsStatusControl status={connectionStatus} onRetry={reconnectNow} />
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ )
+}
+
+function SelectionToolbar({
+ selectedCount,
+ onCancel,
+ onShare,
+}: {
+ selectedCount: number
+ onCancel: () => void
+ onShare: () => void
+}) {
+ return (
+ <div
+ data-testid={tid.messageSelectionToolbar}
+ className="pointer-events-auto flex h-10 w-max min-w-0 max-w-[calc(100vw-7rem)] items-center gap-1 rounded-full border border-border/60 bg-card p-1 shadow-(--e2) sm:h-auto sm:max-w-full"
+ >
+ <span className="min-w-0 flex-1 truncate px-1 text-xs text-muted-foreground sm:px-2 sm:text-sm">
+ {selectedCount} selected
+ </span>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={onCancel}
+ aria-label="Cancel message selection"
+ className="relative h-8 w-11 shrink-0 rounded-lg px-0 after:absolute after:-inset-y-1.5 after:inset-x-0 after:content-[''] sm:h-7 sm:w-auto sm:px-2 sm:after:hidden"
+ />
+ }
+ >
+ <X /> <span className="hidden sm:inline">Cancel</span>
+ </TooltipTrigger>
+ <TooltipContent>Cancel selection</TooltipContent>
+ </Tooltip>
+ <Button
+ size="sm"
+ disabled={selectedCount === 0}
+ onClick={onShare}
+ aria-label={`Share ${selectedCount} selected messages as image`}
+ className="relative h-8 shrink-0 rounded-lg px-2 after:absolute after:-inset-y-1.5 after:inset-x-0 after:content-[''] sm:h-7 sm:after:hidden"
+ >
+ <ImageIcon />
+ <span className="sm:hidden">Share</span>
+ <span className="hidden sm:inline">Share image</span>
+ </Button>
+ </div>
+ )
+}
+
+function ScrollControl({
+ count,
+ mode,
+ onClick,
+}: {
+ count: number
+ mode: "scroll" | "jump"
+ onClick: () => void
+}) {
+ if (count <= 0) return null
+ const aria = mode === "jump"
+ ? `Jump to present, ${count} unread below`
+ : `Scroll to bottom, ${count} more below`
+ return (
+ <button
+ type="button"
+ data-testid={tid.scrollToPresent}
+ onClick={onClick}
+ aria-label={aria}
+ className="pointer-events-auto flex h-8 items-center gap-1.5 justify-self-center 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 focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
+ >
+ <ArrowDown className="size-3.5 text-muted-foreground" />
+ <NumberTicker value={count} />
+ </button>
+ )
+}
+
+function WsStatusControl({
+ status,
+ onRetry,
+}: {
+ status: "connected" | "reconnecting" | "failed"
+ onRetry: () => void
+}) {
+ if (status === "connected") return null
+ const failed = status === "failed"
+ const label = failed
+ ? "WebSocket connection failed. Retry now"
+ : "WebSocket reconnecting"
+ const triggerClassName = cn(
+ "pointer-events-auto relative grid size-11 place-items-center rounded-full outline-none transition-colors focus-visible:ring-3 focus-visible:ring-ring/50 sm:size-10",
+ failed
+ ? "text-destructive hover:bg-destructive/10"
+ : "cursor-default text-warning",
+ )
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={failed ? (
+ <button
+ type="button"
+ data-testid={tid.wsRetry}
+ data-ws-status={status}
+ aria-label={label}
+ onClick={onRetry}
+ className={triggerClassName}
+ />
+ ) : (
+ <span
+ role="status"
+ aria-live="polite"
+ tabIndex={0}
+ data-testid={tid.wsStatus}
+ data-ws-status={status}
+ aria-label={label}
+ className={triggerClassName}
+ />
+ )}
+ >
+ {!failed && (
+ <span className="absolute size-8 rounded-full bg-warning/10 motion-safe:animate-pulse" />
+ )}
+ <span
+ className={cn(
+ "relative grid size-8 place-items-center rounded-full border bg-background/90 shadow-(--e1) backdrop-blur-sm",
+ failed ? "border-destructive/30" : "border-warning/30",
+ )}
+ >
+ {failed ? <WifiOff className="size-4" /> : <Radio className="size-4" />}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>{failed ? "Connection failed · Retry" : "Reconnecting…"}</TooltipContent>
+ </Tooltip>
+ )
+}
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.ts
index 67a70f2ec..3890179fb 100644
--- a/src/web/src/components/community/messages/message-list-view.test.ts
+++ b/src/web/src/components/community/messages/message-list-view.test.ts
@@ -2,21 +2,20 @@ 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 { ComposerAccessoryRail } from "./composer-accessory-rail"
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("./composer-accessory-rail", () => ({
+ ComposerAccessoryRail: vi.fn((props: Record<string, unknown>) => React.createElement("accessory-rail", props)),
}))
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 mockedRail = vi.mocked(ComposerAccessoryRail)
const mockedShareDialog = vi.mocked(MessageShareDialog)
function props(overrides: Partial<ResolvedMessageListProps> = {}): ResolvedMessageListProps {
@@ -77,9 +76,12 @@ describe("renderMessageListView", () => {
act(() => {
renderer = TestRenderer.create(renderMessageListView(listProps, state, renderRows))
})
- expect(mockedTyping).toHaveBeenCalledWith({ names: ["Alice"] }, undefined)
+ expect(mockedRail).toHaveBeenCalledWith(expect.objectContaining({
+ typingNames: ["Alice"],
+ scrollCount: 3,
+ selectMode: false,
+ }), 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)
})
@@ -93,10 +95,11 @@ describe("renderMessageListView", () => {
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(mockedRail).toHaveBeenCalledWith(expect.objectContaining({
+ typingNames: [],
+ scrollCount: 0,
+ }), 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)
})
@@ -121,10 +124,15 @@ describe("renderMessageListView", () => {
() => React.createElement("virtual-rows"),
))
})
- const [cancel, share] = renderer!.root.findAllByType(Button)
- act(() => cancel.props.onClick())
+ const rail = renderer!.root.findByType("accessory-rail")
+ expect(rail.props).toMatchObject({
+ selectMode: true,
+ selectedCount: 1,
+ typingNames: ["Alice"],
+ })
+ act(() => rail.props.onCancelSelection())
expect(exitSelect).toHaveBeenCalledOnce()
- act(() => share.props.onClick())
+ act(() => rail.props.onShareSelection())
expect(setShareOpen).toHaveBeenCalledWith(true)
expect(mockedShareDialog).toHaveBeenCalledWith(expect.objectContaining({
m: state.selectedMessages,
@@ -133,12 +141,7 @@ describe("renderMessageListView", () => {
}), 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))
+ expect(renderer!.root.findAllByType("accessory-rail")).toHaveLength(1)
})
it("keeps both sentinels and the direct rows callback in the exact loaded DOM positions", () => {
diff --git a/src/web/src/components/community/messages/message-list-view.tsx b/src/web/src/components/community/messages/message-list-view.tsx
index 0c966a2bb..5833c68bd 100644
--- a/src/web/src/components/community/messages/message-list-view.tsx
+++ b/src/web/src/components/community/messages/message-list-view.tsx
@@ -1,11 +1,8 @@
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 { ComposerAccessoryRail } from "./composer-accessory-rail"
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"
@@ -16,30 +13,16 @@ export function renderMessageListView(
) {
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}
+ <ComposerAccessoryRail
+ typingNames={controller.isLoading ? [] : props.typingUsers ?? []}
+ scrollCount={controller.isLoading ? 0 : controller.pillCount}
+ scrollMode={controller.pillMode}
+ onScroll={controller.pillOnClick}
+ selectMode={controller.selectMode}
+ selectedCount={controller.selectedIds.size}
+ onCancelSelection={controller.exitSelect}
+ onShareSelection={() => controller.setShareOpen(true)}
/>
- {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}
@@ -47,7 +30,6 @@ export function renderMessageListView(
onClose={controller.closeShare}
/>
)}
- <TypingIndicator names={controller.isLoading ? [] : props.typingUsers ?? []} />
<div
ref={controller.scrollRef}
className="flex-1 overflow-x-clip overflow-y-auto thin-scrollbar"
@@ -98,40 +80,6 @@ export function renderMessageListView(
)
}
-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],
diff --git a/src/web/src/components/community/messages/typing-indicator.tsx b/src/web/src/components/community/messages/typing-indicator.tsx
index d6b1d33fa..03b430f78 100644
--- a/src/web/src/components/community/messages/typing-indicator.tsx
+++ b/src/web/src/components/community/messages/typing-indicator.tsx
@@ -1,13 +1,8 @@
-// Typing indicator — soft opacity pulse + "{names} is/are typing…".
-// Uses the `typing-dot` keyframe in globals.css so we stay on the house easing
-// curve and inherit the `prefers-reduced-motion` rules already wired there.
-// Rendered as a floating pill (same visual family as `ScrollDownButton`) so
-// new activity doesn't shift the message list layout when someone starts
-// typing.
import { tid } from "@/lib/community/testids"
+import { cn } from "@/lib/utils"
-export function TypingIndicator({ names }: { names: string[] }) {
- const visible = names.length > 0
+export function TypingIndicator({ names, className }: { names: string[]; className?: string }) {
+ if (names.length === 0) return null
const label = names.length === 0
? null
: names.length === 1
@@ -17,23 +12,18 @@ export function TypingIndicator({ names }: { names: string[] }) {
: <><span className="font-medium text-foreground">{names.length} people</span> are typing…</>
return (
<div
- data-testid={visible ? tid.typingIndicator : undefined}
- className={`pointer-events-none absolute bottom-3 left-3 z-10 transition-all duration-200 ease-out ${
- visible ? "translate-y-0 opacity-100" : "translate-y-2 opacity-0"
- }`}
+ data-testid={tid.typingIndicator}
+ className={cn(
+ "pointer-events-none flex h-8 min-w-0 max-w-full items-center gap-2 rounded-full border border-border bg-background/90 px-3 text-xs text-muted-foreground shadow-(--e1) backdrop-blur-sm",
+ className,
+ )}
>
- <div className="flex h-8 items-center gap-2 rounded-full border border-border bg-background/90 px-3 text-xs text-muted-foreground shadow-(--e1) backdrop-blur-sm">
- <span className="flex gap-1">
- {[0, 1, 2].map((i) => (
- <span
- key={i}
- className="size-1.5 rounded-full bg-muted-foreground"
- style={{ animation: "typing-dot 1.4s ease-in-out infinite", animationDelay: `${i * 160}ms` }}
- />
- ))}
- </span>
- <span>{label}</span>
- </div>
+ <span className="flex shrink-0 gap-1">
+ <span className="size-1.5 rounded-full bg-muted-foreground motion-safe:animate-[typing-dot_1.4s_ease-in-out_infinite]" />
+ <span className="size-1.5 rounded-full bg-muted-foreground motion-safe:animate-[typing-dot_1.4s_ease-in-out_160ms_infinite]" />
+ <span className="size-1.5 rounded-full bg-muted-foreground motion-safe:animate-[typing-dot_1.4s_ease-in-out_320ms_infinite]" />
+ </span>
+ <span className="min-w-0 truncate">{label}</span>
</div>
)
}
diff --git a/src/web/src/hooks/community/community-ws/connection-status.test.ts b/src/web/src/hooks/community/community-ws/connection-status.test.ts
new file mode 100644
index 000000000..cc967dbe4
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/connection-status.test.ts
@@ -0,0 +1,101 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import {
+ COMMUNITY_WS_FAILED_AFTER_MS,
+ COMMUNITY_WS_RECONNECTING_GRACE_MS,
+ createCommunityWsConnectionStatusController,
+} from "./connection-status"
+
+describe("community websocket connection status", () => {
+ beforeEach(() => vi.useFakeTimers())
+ afterEach(() => vi.useRealTimers())
+
+ function setup() {
+ const publish = vi.fn()
+ const reconnectTransport = vi.fn()
+ const controller = createCommunityWsConnectionStatusController({
+ publish,
+ reconnectTransport,
+ })
+ return { controller, publish, reconnectTransport }
+ }
+
+ it("hides a short initial handshake and clears both thresholds on auth", () => {
+ const { controller, publish } = setup()
+ controller.handlePhase("reconnecting")
+ expect(publish).toHaveBeenLastCalledWith("connected")
+
+ vi.advanceTimersByTime(COMMUNITY_WS_RECONNECTING_GRACE_MS - 1)
+ expect(publish).not.toHaveBeenCalledWith("reconnecting")
+
+ controller.handlePhase("authenticated")
+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS)
+ expect(publish).toHaveBeenLastCalledWith("connected")
+ expect(publish).not.toHaveBeenCalledWith("failed")
+ })
+
+ it("publishes reconnecting after grace and failed after one continuous outage", () => {
+ const { controller, publish } = setup()
+ controller.handlePhase("reconnecting")
+ vi.advanceTimersByTime(COMMUNITY_WS_RECONNECTING_GRACE_MS)
+ expect(publish).toHaveBeenLastCalledWith("reconnecting")
+
+ controller.handlePhase("reconnecting")
+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS - COMMUNITY_WS_RECONNECTING_GRACE_MS)
+ expect(publish).toHaveBeenLastCalledWith("failed")
+ expect(publish.mock.calls.filter(([status]) => status === "failed")).toHaveLength(1)
+ })
+
+ it("publishes reconnecting immediately after a previously authenticated socket drops", () => {
+ const { controller, publish } = setup()
+ controller.handlePhase("reconnecting")
+ controller.handlePhase("authenticated")
+ publish.mockClear()
+
+ controller.handlePhase("reconnecting")
+ expect(publish).toHaveBeenCalledOnce()
+ expect(publish).toHaveBeenLastCalledWith("reconnecting")
+
+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS)
+ expect(publish).toHaveBeenLastCalledWith("failed")
+ })
+
+ it("suspends hidden outages and starts fresh thresholds when visible again", () => {
+ const { controller, publish } = setup()
+ controller.handlePhase("reconnecting")
+ vi.advanceTimersByTime(COMMUNITY_WS_RECONNECTING_GRACE_MS)
+ controller.handlePhase("suspended")
+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS)
+ expect(publish).toHaveBeenLastCalledWith("connected")
+
+ controller.handlePhase("reconnecting")
+ vi.advanceTimersByTime(COMMUNITY_WS_RECONNECTING_GRACE_MS)
+ expect(publish).toHaveBeenLastCalledWith("reconnecting")
+ })
+
+ it("manual retry leaves failed immediately, calls one transport retry, and rearms failure", () => {
+ const { controller, publish, reconnectTransport } = setup()
+ controller.handlePhase("reconnecting")
+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS)
+ expect(publish).toHaveBeenLastCalledWith("failed")
+
+ controller.reconnectNow()
+ expect(publish).toHaveBeenLastCalledWith("reconnecting")
+ expect(reconnectTransport).toHaveBeenCalledOnce()
+
+ controller.handlePhase("reconnecting")
+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS)
+ expect(publish).toHaveBeenLastCalledWith("failed")
+ expect(reconnectTransport).toHaveBeenCalledOnce()
+ })
+
+ it("dispose clears timers and ignores callbacks or retries", () => {
+ const { controller, publish, reconnectTransport } = setup()
+ controller.handlePhase("reconnecting")
+ controller.dispose()
+ vi.runAllTimers()
+ controller.handlePhase("reconnecting")
+ controller.reconnectNow()
+ expect(publish).toHaveBeenCalledTimes(1)
+ expect(reconnectTransport).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/hooks/community/community-ws/connection-status.ts b/src/web/src/hooks/community/community-ws/connection-status.ts
new file mode 100644
index 000000000..832392938
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/connection-status.ts
@@ -0,0 +1,85 @@
+import type { UserWsConnectionPhase } from "@/lib/use-user-ws"
+import type { CommunityWsConnectionStatus } from "@/stores/community/ws"
+
+export const COMMUNITY_WS_RECONNECTING_GRACE_MS = 1_500
+export const COMMUNITY_WS_FAILED_AFTER_MS = 30_000
+
+export type CommunityWsConnectionStatusController = {
+ handlePhase: (phase: UserWsConnectionPhase) => void
+ reconnectNow: () => void
+ dispose: () => void
+}
+
+export function createCommunityWsConnectionStatusController({
+ publish,
+ reconnectTransport,
+}: {
+ publish: (status: CommunityWsConnectionStatus) => void
+ reconnectTransport: () => void
+}): CommunityWsConnectionStatusController {
+ let reconnectingTimer: ReturnType<typeof setTimeout> | null = null
+ let failedTimer: ReturnType<typeof setTimeout> | null = null
+ let outageActive = false
+ let hasAuthenticated = false
+ let disposed = false
+
+ const clearTimers = () => {
+ if (reconnectingTimer !== null) clearTimeout(reconnectingTimer)
+ if (failedTimer !== null) clearTimeout(failedTimer)
+ reconnectingTimer = null
+ failedTimer = null
+ }
+
+ const armFailedTimer = () => {
+ failedTimer = setTimeout(() => {
+ failedTimer = null
+ if (!disposed && outageActive) publish("failed")
+ }, COMMUNITY_WS_FAILED_AFTER_MS)
+ }
+
+ const handlePhase = (phase: UserWsConnectionPhase) => {
+ if (disposed) return
+ if (phase === "authenticated") {
+ hasAuthenticated = true
+ outageActive = false
+ clearTimers()
+ publish("connected")
+ return
+ }
+ if (phase === "suspended") {
+ outageActive = false
+ clearTimers()
+ publish("connected")
+ return
+ }
+ if (outageActive) return
+ outageActive = true
+ if (hasAuthenticated) {
+ publish("reconnecting")
+ } else {
+ publish("connected")
+ reconnectingTimer = setTimeout(() => {
+ reconnectingTimer = null
+ if (!disposed && outageActive) publish("reconnecting")
+ }, COMMUNITY_WS_RECONNECTING_GRACE_MS)
+ }
+ armFailedTimer()
+ }
+
+ const reconnectNow = () => {
+ if (disposed) return
+ outageActive = true
+ clearTimers()
+ publish("reconnecting")
+ armFailedTimer()
+ reconnectTransport()
+ }
+
+ const dispose = () => {
+ disposed = true
+ outageActive = false
+ clearTimers()
+ }
+
+ return { handlePhase, reconnectNow, dispose }
+}
diff --git a/src/web/src/hooks/community/community-ws/test-harness.ts b/src/web/src/hooks/community/community-ws/test-harness.ts
index f79a6d618..427650c5d 100644
--- a/src/web/src/hooks/community/community-ws/test-harness.ts
+++ b/src/web/src/hooks/community/community-ws/test-harness.ts
@@ -1,7 +1,7 @@
import { QueryClient } from "@tanstack/react-query"
import type { CommunityMessageCreate } from "@alook/shared"
import { vi } from "vitest"
-import type { UseUserWsOptions } from "@/lib/use-user-ws"
+import type { UseUserWsOptions, UserWsConnectionPhase } from "@/lib/use-user-ws"
import { useMessageStreamStore } from "@/stores/community/message-stream"
type ShimCallback = (...args: unknown[]) => unknown
@@ -54,16 +54,19 @@ vi.mock("@tanstack/react-query", async () => {
export let capturedOnMessage: ((msg: unknown) => void) | null = null
export let capturedOnReconnect: ((info: { reconnectDurationMs: number }) => void | Promise<void>) | null = null
+export let capturedConnectionStateChange: ((phase: UserWsConnectionPhase) => void | Promise<void>) | null = null
export let capturedUseUserWsOptions: UseUserWsOptions | undefined
let stableSend: ReturnType<typeof vi.fn> = vi.fn()
+let stableReconnectNow: ReturnType<typeof vi.fn> = vi.fn()
export let useUserWsCallCount = 0
vi.mock("@/lib/use-user-ws", () => ({
useUserWs: (onMessage: (msg: unknown) => void, options?: UseUserWsOptions) => {
useUserWsCallCount += 1
capturedOnMessage = onMessage
capturedOnReconnect = options?.onReconnect ?? null
+ capturedConnectionStateChange = options?.onConnectionStateChange ?? null
capturedUseUserWsOptions = options
- return { send: stableSend }
+ return { send: stableSend, reconnectNow: stableReconnectNow }
},
}))
@@ -92,15 +95,21 @@ export function getStableSend() {
return stableSend
}
+export function getStableReconnectNow() {
+ return stableReconnectNow
+}
+
function resetHarnessState() {
resetHookInstance()
pendingEffects = []
effectCleanups = []
capturedOnMessage = null
capturedOnReconnect = null
+ capturedConnectionStateChange = null
capturedUseUserWsOptions = undefined
capturedQueryClient = new QueryClient()
stableSend = vi.fn()
+ stableReconnectNow = vi.fn()
useUserWsCallCount = 0
markReadMutate.mockClear()
}
diff --git a/src/web/src/hooks/community/use-community-ws.test.ts b/src/web/src/hooks/community/use-community-ws.test.ts
index 3830c8431..27edfc2ec 100644
--- a/src/web/src/hooks/community/use-community-ws.test.ts
+++ b/src/web/src/hooks/community/use-community-ws.test.ts
@@ -3,12 +3,14 @@
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import {
+ capturedConnectionStateChange,
capturedOnMessage,
capturedOnReconnect,
capturedQueryClient,
capturedUseUserWsOptions,
cleanupCommunityWsHarness,
flushEffects,
+ getStableReconnectNow,
getStableSend,
mountHook,
resetCommunityWsHarness,
@@ -16,6 +18,10 @@ import {
setStableSend,
useUserWsCallCount,
} from "./community-ws/test-harness"
+import {
+ COMMUNITY_WS_FAILED_AFTER_MS,
+ COMMUNITY_WS_RECONNECTING_GRACE_MS,
+} from "./community-ws/connection-status"
beforeEach(resetCommunityWsHarness)
afterEach(cleanupCommunityWsHarness)
@@ -78,6 +84,49 @@ describe("useCommunityWs — public helper contracts", () => {
})
})
+describe("useCommunityWs — connection status publication", () => {
+ it("publishes the grace, failed, authenticated, and manual retry states from the root", async () => {
+ vi.useFakeTimers()
+ const { useCommunityWsStore } = await import("@/stores/community/ws")
+ await mountHook()
+ flushEffects()
+
+ capturedConnectionStateChange!("reconnecting")
+ expect(useCommunityWsStore.getState().connectionStatus).toBe("connected")
+ vi.advanceTimersByTime(COMMUNITY_WS_RECONNECTING_GRACE_MS)
+ expect(useCommunityWsStore.getState().connectionStatus).toBe("reconnecting")
+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS - COMMUNITY_WS_RECONNECTING_GRACE_MS)
+ expect(useCommunityWsStore.getState().connectionStatus).toBe("failed")
+
+ useCommunityWsStore.getState().reconnectNow()
+ expect(useCommunityWsStore.getState().connectionStatus).toBe("reconnecting")
+ expect(getStableReconnectNow()).toHaveBeenCalledOnce()
+
+ capturedConnectionStateChange!("authenticated")
+ expect(useCommunityWsStore.getState().connectionStatus).toBe("connected")
+
+ capturedConnectionStateChange!("reconnecting")
+ expect(useCommunityWsStore.getState().connectionStatus).toBe("reconnecting")
+ })
+
+ it("suspends threshold timers and re-arms on the next visible reconnect", async () => {
+ vi.useFakeTimers()
+ const { useCommunityWsStore } = await import("@/stores/community/ws")
+ await mountHook()
+ flushEffects()
+
+ capturedConnectionStateChange!("reconnecting")
+ vi.advanceTimersByTime(COMMUNITY_WS_RECONNECTING_GRACE_MS)
+ capturedConnectionStateChange!("suspended")
+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS)
+ expect(useCommunityWsStore.getState().connectionStatus).toBe("connected")
+
+ capturedConnectionStateChange!("reconnecting")
+ vi.advanceTimersByTime(COMMUNITY_WS_RECONNECTING_GRACE_MS)
+ expect(useCommunityWsStore.getState().connectionStatus).toBe("reconnecting")
+ })
+})
+
describe("useCommunityWs — double-mount detection", () => {
it("owns exactly one useUserWs call for one hook mount", async () => {
await mountHook()
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index 499d2aa52..6f1937148 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -2,7 +2,10 @@
import { useCallback, useEffect, useRef } from "react"
import { useQueryClient } from "@tanstack/react-query"
-import { useUserWs } from "@/lib/use-user-ws"
+import {
+ useUserWs,
+ type UserWsConnectionPhase,
+} from "@/lib/use-user-ws"
import { useCommunityStore } from "@/stores/community"
import { useCommunityWsStore } from "@/stores/community/ws"
import { reconcileCommunityWsReconnect } from "@/hooks/community/community-ws/reconnect"
@@ -28,6 +31,10 @@ import {
TYPING_INDICATOR_THROTTLE_MS,
} from "@alook/shared"
import { trackCommunityWsFrameDropped } from "@/lib/analytics"
+import {
+ createCommunityWsConnectionStatusController,
+ type CommunityWsConnectionStatusController,
+} from "@/hooks/community/community-ws/connection-status"
export type {
Subscription,
@@ -120,6 +127,20 @@ export function communityWsResetTypingThrottle(target: { channelId: string }) {
export function useCommunityWs(options?: UseCommunityWsOptions): void {
const queryClient = useQueryClient()
+ const reconnectTransportRef = useRef<() => void>(() => undefined)
+ const connectionControllerRef = useRef<CommunityWsConnectionStatusController | null>(null)
+ const getConnectionController = useCallback(() => {
+ if (connectionControllerRef.current === null) {
+ connectionControllerRef.current = createCommunityWsConnectionStatusController({
+ publish: useCommunityWsStore.getState().setConnectionStatus,
+ reconnectTransport: () => reconnectTransportRef.current(),
+ })
+ }
+ return connectionControllerRef.current
+ }, [])
+ const handleConnectionStateChange = useCallback((phase: UserWsConnectionPhase) => {
+ getConnectionController().handlePhase(phase)
+ }, [getConnectionController])
const viewerUserIdRef = useRef<string | null>(options?.viewerUserId ?? null)
useEffect(() => {
viewerUserIdRef.current = options?.viewerUserId ?? null
@@ -268,12 +289,16 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
const handleReconnect = useCallback(async ({ reconnectDurationMs }: { reconnectDurationMs: number }) => {
await reconcileCommunityWsReconnect(queryClient, reconnectDurationMs)
}, [queryClient])
- const { send } = useUserWs(handleMessage, {
+ const { send, reconnectNow } = useUserWs(handleMessage, {
onReconnect: handleReconnect,
onDisconnect: useCommunityWsStore.getState().markAccessDisconnected,
onAuthenticated: useCommunityWsStore.getState().markAccessConnected,
+ onConnectionStateChange: handleConnectionStateChange,
requestDaemonStatusOnAuth: false,
})
+ useEffect(() => {
+ reconnectTransportRef.current = reconnectNow
+ }, [reconnectNow])
// Publish the send binding so free helpers (`communityWsSendTyping`) can
// dispatch without holding a hook reference. Single-instance assumption
@@ -297,6 +322,23 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
}
}, [send])
+ useEffect(() => {
+ const controller = getConnectionController()
+ const retry = () => controller.reconnectNow()
+ useCommunityWsStore.getState().bindReconnectNow(retry)
+ return () => {
+ controller.dispose()
+ if (connectionControllerRef.current === controller) {
+ connectionControllerRef.current = null
+ }
+ const store = useCommunityWsStore.getState()
+ if (store.reconnectNow === retry) {
+ store.bindReconnectNow(() => undefined)
+ store.setConnectionStatus("connected")
+ }
+ }
+ }, [getConnectionController])
+
// Cleanup: flush the inbox debounce if the hook unmounts mid-window so the
// parent surface doesn't leave a scheduled fetch dangling.
useEffect(() => {
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 817f1c940..6eac3f6e6 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -5,6 +5,11 @@ export const tid = {
composerInput: "community-composer-input",
composerSend: "community-composer-send",
composerAttach: "community-composer-attach",
+ composerAccessoryRail: "community-composer-accessory-rail",
+ scrollToPresent: "community-scroll-to-present",
+ messageSelectionToolbar: "community-message-selection-toolbar",
+ wsStatus: "community-ws-status",
+ wsRetry: "community-ws-retry",
serverAdd: "community-server-add",
serverRailScroll: "community-server-rail-scroll",
channelSidebarScroll: "community-channel-sidebar-scroll",
diff --git a/src/web/src/lib/use-user-ws.test.ts b/src/web/src/lib/use-user-ws.test.ts
index 0bc0b7f0b..166c65680 100644
--- a/src/web/src/lib/use-user-ws.test.ts
+++ b/src/web/src/lib/use-user-ws.test.ts
@@ -81,6 +81,7 @@ let effectMemo: Map<string, {
cleanup?: () => void
}> = new Map()
let effectCounter = 0
+let latestHookResult: ReturnType<typeof import("./use-user-ws")["useUserWs"]> | null = null
function depsEqual(left: unknown[], right: unknown[]) {
return left.length === right.length && left.every((value, index) => Object.is(value, right[index]))
@@ -155,6 +156,7 @@ function resetMockState() {
callbackCounter = 0
effectMemo = new Map()
effectCounter = 0
+ latestHookResult = null
mockDocument.visibilityState = "visible"
mockDocument.reset()
mockWindow.reset()
@@ -176,7 +178,7 @@ describe("useUserWs", () => {
) {
// Re-import to get fresh module with fresh mocks
const mod = await import("./use-user-ws")
- mod.useUserWs(onMessage, options)
+ latestHookResult = mod.useUserWs(onMessage, options)
// Wait for async connect to complete
await flushPromises()
return mod
@@ -390,6 +392,147 @@ describe("useUserWs", () => {
expect(MockWebSocket.instances.length).toBeGreaterThan(instancesBefore)
})
+ it("publishes reconnecting, authenticated, and suspended lifecycle phases", async () => {
+ setupTokenFetch()
+ const onConnectionStateChange = vi.fn()
+ await mountHook(vi.fn(), {
+ onConnectionStateChange,
+ requestDaemonStatusOnAuth: false,
+ })
+ const ws = MockWebSocket.instances[0]!
+
+ expect(onConnectionStateChange).toHaveBeenLastCalledWith("reconnecting")
+ ws.simulateOpen()
+ ws.simulateMessage({ type: "auth.ok" })
+ expect(onConnectionStateChange).toHaveBeenLastCalledWith("authenticated")
+
+ mockDocument.visibilityState = "hidden"
+ ws.simulateClose()
+ expect(onConnectionStateChange).toHaveBeenLastCalledWith("suspended")
+ })
+
+ it("publishes suspended without fetching during a hidden cold start and resumes once visible", async () => {
+ setupTokenFetch()
+ mockDocument.visibilityState = "hidden"
+ const onConnectionStateChange = vi.fn()
+
+ await mountHook(vi.fn(), {
+ onConnectionStateChange,
+ requestDaemonStatusOnAuth: false,
+ })
+ expect(onConnectionStateChange).toHaveBeenLastCalledWith("suspended")
+ expect(mockFetch).not.toHaveBeenCalled()
+
+ mockDocument.dispatch("visibilitychange")
+ expect(onConnectionStateChange).toHaveBeenLastCalledWith("suspended")
+ expect(mockFetch).not.toHaveBeenCalled()
+
+ mockDocument.visibilityState = "visible"
+ mockDocument.dispatch("visibilitychange")
+ await flushPromises()
+ expect(mockFetch).toHaveBeenCalledOnce()
+ expect(MockWebSocket.instances).toHaveLength(1)
+ })
+
+ it("manual reconnect retires the current socket and starts exactly one fresh generation", async () => {
+ setupTokenFetch()
+ const onAuthenticated = vi.fn()
+ await mountHook(vi.fn(), {
+ onAuthenticated,
+ requestDaemonStatusOnAuth: false,
+ })
+ const first = MockWebSocket.instances[0]!
+ first.simulateOpen()
+ first.simulateMessage({ type: "auth.ok" })
+ expect(onAuthenticated).toHaveBeenCalledOnce()
+
+ latestHookResult!.reconnectNow()
+ await flushPromises()
+
+ expect(first.closed).toBe(true)
+ expect(MockWebSocket.instances).toHaveLength(2)
+ const replacement = MockWebSocket.instances[1]!
+ first.simulateMessage({ type: "auth.ok" })
+ expect(onAuthenticated).toHaveBeenCalledOnce()
+
+ replacement.simulateOpen()
+ replacement.simulateMessage({ type: "auth.ok" })
+ expect(onAuthenticated).toHaveBeenCalledTimes(2)
+ await vi.advanceTimersByTimeAsync(5_000)
+ expect(MockWebSocket.instances).toHaveLength(2)
+ })
+
+ it("manual reconnect invalidates an older pending token before it can create a socket", async () => {
+ const firstTokenResponse = deferred<{
+ ok: boolean
+ json: () => Promise<{ userId: string; token: string }>
+ }>()
+ const secondTokenResponse = deferred<{
+ ok: boolean
+ json: () => Promise<{ userId: string; token: string }>
+ }>()
+ mockFetch
+ .mockReturnValueOnce(firstTokenResponse.promise)
+ .mockReturnValueOnce(secondTokenResponse.promise)
+
+ await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ latestHookResult!.reconnectNow()
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+
+ firstTokenResponse.resolve({
+ ok: true,
+ json: () => Promise.resolve({ userId: "stale-user", token: "stale-token" }),
+ })
+ await flushPromises()
+ expect(MockWebSocket.instances).toHaveLength(0)
+
+ secondTokenResponse.resolve({
+ ok: true,
+ json: () => Promise.resolve({ userId: "latest-user", token: "latest-token" }),
+ })
+ await flushPromises()
+ expect(MockWebSocket.instances).toHaveLength(1)
+ expect(MockWebSocket.instances[0]?.url).toContain("latest-user")
+ })
+
+ it("manual reconnect clears a scheduled automatic retry before opening one replacement", async () => {
+ setupTokenFetch()
+ await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const first = MockWebSocket.instances[0]!
+ first.simulateOpen()
+ first.simulateClose()
+
+ latestHookResult!.reconnectNow()
+ await flushPromises()
+ expect(MockWebSocket.instances).toHaveLength(2)
+
+ await vi.advanceTimersByTimeAsync(5_000)
+ expect(MockWebSocket.instances).toHaveLength(2)
+ })
+
+ it("manual reconnect while hidden invalidates the generation and remains suspended", async () => {
+ setupTokenFetch()
+ const onConnectionStateChange = vi.fn()
+ await mountHook(vi.fn(), {
+ onConnectionStateChange,
+ requestDaemonStatusOnAuth: false,
+ })
+ const first = MockWebSocket.instances[0]!
+ first.simulateOpen()
+ first.simulateMessage({ type: "auth.ok" })
+ const fetchCount = mockFetch.mock.calls.length
+
+ mockDocument.visibilityState = "hidden"
+ onConnectionStateChange.mockClear()
+ latestHookResult!.reconnectNow()
+
+ expect(first.closed).toBe(true)
+ expect(onConnectionStateChange).toHaveBeenLastCalledWith("suspended")
+ expect(mockFetch).toHaveBeenCalledTimes(fetchCount)
+ await vi.advanceTimersByTimeAsync(60_000)
+ expect(MockWebSocket.instances).toEqual([first])
+ })
+
it("passes an AbortSignal to the token fetch and aborts it at the hard timeout", async () => {
mockFetch.mockImplementation((_url: string, init?: RequestInit) => new Promise((_resolve, reject) => {
init?.signal?.addEventListener("abort", () => {
diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.ts
index c6c791ac1..e9dc5f8b9 100644
--- a/src/web/src/lib/use-user-ws.ts
+++ b/src/web/src/lib/use-user-ws.ts
@@ -37,15 +37,18 @@ function isPageHidden(): boolean {
*/
export type WsMessageIncoming = WsMessage & { [key: string]: unknown }
+export type UserWsConnectionPhase = "authenticated" | "reconnecting" | "suspended"
+
export type UseUserWsOptions = {
onReconnect?: (info: { reconnectDurationMs: number }) => void | Promise<void>
onDisconnect?: () => void | Promise<void>
onAuthenticated?: () => void | Promise<void>
+ onConnectionStateChange?: (phase: UserWsConnectionPhase) => void | Promise<void>
requestDaemonStatusOnAuth?: boolean
}
function runLifecycleCallback(
- name: "authenticated" | "disconnect" | "reconnect",
+ name: "authenticated" | "connection-state" | "disconnect" | "reconnect",
callback: (() => void | Promise<void>) | undefined,
) {
if (!callback) return
@@ -80,13 +83,14 @@ function reportDroppedFrame(
export function useUserWs(
onMessage: (msg: WsMessageIncoming) => void,
options?: UseUserWsOptions,
-): { send: (msg: object) => void } {
+): { send: (msg: object) => void; reconnectNow: () => void } {
const wsRef = useRef<WebSocket | null>(null)
const reconnectDelay = useRef(WS_RECONNECT_INIT)
const onMessageRef = useRef(onMessage)
const onReconnectRef = useRef(options?.onReconnect)
const onDisconnectRef = useRef(options?.onDisconnect)
const onAuthenticatedRef = useRef(options?.onAuthenticated)
+ const onConnectionStateChangeRef = useRef(options?.onConnectionStateChange)
const requestDaemonStatusOnAuthRef = useRef(options?.requestDaemonStatusOnAuth ?? true)
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const tokenAbortRef = useRef<AbortController | null>(null)
@@ -112,7 +116,12 @@ export function useUserWs(
useEffect(() => {
onDisconnectRef.current = options?.onDisconnect
onAuthenticatedRef.current = options?.onAuthenticated
- }, [options?.onAuthenticated, options?.onDisconnect])
+ onConnectionStateChangeRef.current = options?.onConnectionStateChange
+ }, [
+ options?.onAuthenticated,
+ options?.onConnectionStateChange,
+ options?.onDisconnect,
+ ])
useEffect(() => {
requestDaemonStatusOnAuthRef.current = options?.requestDaemonStatusOnAuth ?? true
@@ -150,7 +159,13 @@ export function useUserWs(
}, [])
const connect = useCallback(async () => {
- if (isPageHidden()) return
+ if (isPageHidden()) {
+ runLifecycleCallback("connection-state", () =>
+ onConnectionStateChangeRef.current?.("suspended"))
+ return
+ }
+ runLifecycleCallback("connection-state", () =>
+ onConnectionStateChangeRef.current?.("reconnecting"))
const generation = connectionGenerationRef.current + 1
connectionGenerationRef.current = generation
if (reconnectTimerRef.current !== null) {
@@ -278,6 +293,8 @@ export function useUserWs(
? 0
: Math.max(0, Date.now() - disconnectedAtRef.current)
disconnectedAtRef.current = null
+ runLifecycleCallback("connection-state", () =>
+ onConnectionStateChangeRef.current?.("authenticated"))
runLifecycleCallback("authenticated", onAuthenticatedRef.current)
if (isReconnect) {
runLifecycleCallback("reconnect", () =>
@@ -325,6 +342,8 @@ export function useUserWs(
if (pingIntervalRef.current) { clearInterval(pingIntervalRef.current); pingIntervalRef.current = null }
if (livenessIntervalRef.current) { clearInterval(livenessIntervalRef.current); livenessIntervalRef.current = null }
if (connectTimeoutRef.current !== null) { clearTimeout(connectTimeoutRef.current); connectTimeoutRef.current = null }
+ runLifecycleCallback("connection-state", () =>
+ onConnectionStateChangeRef.current?.(isPageHidden() ? "suspended" : "reconnecting"))
scheduleReconnect(generation)
}
}, [retireSocket, scheduleReconnect])
@@ -337,6 +356,11 @@ export function useUserWs(
void connect()
const resumeConnection = () => {
if (isPageHidden()) {
+ const generation = connectionGenerationRef.current
+ if (authenticatedGenerationRef.current !== generation) {
+ runLifecycleCallback("connection-state", () =>
+ onConnectionStateChangeRef.current?.("suspended"))
+ }
if (reconnectTimerRef.current !== null) {
clearTimeout(reconnectTimerRef.current)
reconnectTimerRef.current = null
@@ -414,5 +438,27 @@ export function useUserWs(
}
}, [])
- return { send }
+ const reconnectNow = useCallback(() => {
+ if (reconnectTimerRef.current !== null) {
+ clearTimeout(reconnectTimerRef.current)
+ reconnectTimerRef.current = null
+ }
+ tokenAbortRef.current?.abort()
+ tokenAbortRef.current = null
+ if (tokenTimeoutRef.current !== null) {
+ clearTimeout(tokenTimeoutRef.current)
+ tokenTimeoutRef.current = null
+ }
+ reconnectDelay.current = WS_RECONNECT_INIT
+ retireSocket()
+ if (isPageHidden()) {
+ connectionGenerationRef.current += 1
+ runLifecycleCallback("connection-state", () =>
+ onConnectionStateChangeRef.current?.("suspended"))
+ return
+ }
+ void connectRef.current?.()
+ }, [retireSocket])
+
+ return { send, reconnectNow }
}
diff --git a/src/web/src/stores/community/ws.test.ts b/src/web/src/stores/community/ws.test.ts
index efdba7aee..91fa1c2d9 100644
--- a/src/web/src/stores/community/ws.test.ts
+++ b/src/web/src/stores/community/ws.test.ts
@@ -13,6 +13,24 @@ beforeEach(() => {
})
describe("useCommunityWsStore", () => {
+ it("publishes connection status, binds retry, and resets both safely", () => {
+ const calls: string[] = []
+ const reconnectNow = () => calls.push("retry")
+ expect(useCommunityWsStore.getState().connectionStatus).toBe("connected")
+
+ useCommunityWsStore.getState().setConnectionStatus("reconnecting")
+ useCommunityWsStore.getState().bindReconnectNow(reconnectNow)
+ expect(useCommunityWsStore.getState().connectionStatus).toBe("reconnecting")
+ useCommunityWsStore.getState().reconnectNow()
+ expect(calls).toEqual(["retry"])
+
+ useCommunityWsStore.getState().setConnectionStatus("failed")
+ useCommunityWsStore.getState().reset()
+ expect(useCommunityWsStore.getState().connectionStatus).toBe("connected")
+ useCommunityWsStore.getState().reconnectNow()
+ expect(calls).toEqual(["retry"])
+ })
+
it("fails closed until the websocket is authenticated and advances epochs on disconnect", () => {
expect(useCommunityWsStore.getState()).toMatchObject({
accessConnected: false,
diff --git a/src/web/src/stores/community/ws.ts b/src/web/src/stores/community/ws.ts
index 9cdc70da5..8ab0aff39 100644
--- a/src/web/src/stores/community/ws.ts
+++ b/src/web/src/stores/community/ws.ts
@@ -55,10 +55,15 @@ export type BotAuditEventEntry = {
}
type UserStatus = { emoji: string | null; text: string | null }
+export type CommunityWsConnectionStatus = "connected" | "reconnecting" | "failed"
+
+const NOOP_RECONNECT = () => undefined
export type CommunityWsStoreState = {
accessEpoch: number
accessConnected: boolean
+ connectionStatus: CommunityWsConnectionStatus
+ reconnectNow: () => void
/**
* Everyone online right now — human or bot. The server pushes
* `community:presence.update` identically for both (see
@@ -116,6 +121,8 @@ export type CommunityWsStoreState = {
resetUserStatuses: () => void
markAccessDisconnected: () => void
markAccessConnected: () => void
+ setConnectionStatus: (status: CommunityWsConnectionStatus) => void
+ bindReconnectNow: (reconnectNow: () => void) => void
pushBotAuditEvent: (event: BotAuditEventEntry) => void
reset: () => void
}
@@ -124,9 +131,12 @@ const initialState = (): Pick<
CommunityWsStoreState,
"onlineUserIds" | "seenMessageIds" | "seenDeliveryOperations" | "userStatuses" | "botAuditEvents"
| "accessEpoch" | "accessConnected"
+ | "connectionStatus" | "reconnectNow"
> => ({
accessEpoch: 0,
accessConnected: false,
+ connectionStatus: "connected",
+ reconnectNow: NOOP_RECONNECT,
onlineUserIds: new Set(),
seenMessageIds: new Set(),
seenDeliveryOperations: new Map(),
@@ -235,6 +245,13 @@ export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => (
markAccessConnected: () => set({ accessConnected: true }),
+ setConnectionStatus: (connectionStatus) => {
+ if (get().connectionStatus === connectionStatus) return
+ set({ connectionStatus })
+ },
+
+ bindReconnectNow: (reconnectNow) => set({ reconnectNow }),
+
pushBotAuditEvent: (event) => {
const current = get().botAuditEvents
const perBot = current.get(event.botId) ?? []