Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): harden invites, join presence, and text previews (#481)

Gustavo Ye34c7cce8b5f3
diff --git a/src/web/src/components/community/social/invite-dialog.test.ts b/src/web/src/components/community/social/invite-dialog.test.ts
new file mode 100644
index 000000000..f61e40d10
--- /dev/null
+++ b/src/web/src/components/community/social/invite-dialog.test.ts
@@ -0,0 +1,180 @@
+import { createElement } from "react"
+import { renderToStaticMarkup } from "react-dom/server"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import type { Friend } from "@/lib/community/models/people"
+
+const { toastSpy } = vi.hoisted(() => ({ toastSpy: vi.fn() }))
+
+vi.mock("sonner", () => ({ toast: toastSpy }))
+
+import { InviteFriendRow, runInviteFriend } from "./invite-dialog"
+
+const friend: Friend = {
+ id: "friend_1",
+ userId: "user_1",
+ name: "Alice",
+ discriminator: "0001",
+ avatar: "A",
+ status: "online",
+ sub: "@Alice#0001",
+}
+
+function renderRow({
+ tokenReady = true,
+ inviting = false,
+ invited = false,
+}: {
+ tokenReady?: boolean
+ inviting?: boolean
+ invited?: boolean
+} = {}) {
+ return renderToStaticMarkup(
+ createElement(InviteFriendRow, {
+ friend,
+ tokenReady,
+ inviting,
+ invited,
+ onInvite: () => {},
+ }),
+ )
+}
+
+function hasDisabledButton(html: string) {
+ return /<button[^>]*\sdisabled(?:=""|>)/.test(html)
+}
+
+function trackingSetter() {
+ let current = new Set<string>()
+ const snapshots: string[][] = []
+ const setter = (next: Set<string> | ((value: Set<string>) => Set<string>)) => {
+ current = typeof next === "function" ? next(current) : next
+ snapshots.push([...current].sort())
+ }
+ return {
+ setter: setter as never,
+ snapshots,
+ current: () => [...current].sort(),
+ }
+}
+
+function deferred() {
+ let resolve!: () => void
+ const promise = new Promise<void>((done) => {
+ resolve = done
+ })
+ return { promise, resolve }
+}
+
+describe("InviteFriendRow", () => {
+ it("shows Invite while idle", () => {
+ const html = renderRow()
+ expect(html).toContain(">Invite<")
+ expect(html).not.toContain("animate-spin")
+ expect(hasDisabledButton(html)).toBe(false)
+ })
+
+ it("shows a spinner and disables only the in-flight row", () => {
+ const html = renderRow({ inviting: true })
+ expect(html).toContain("Sending invite")
+ expect(html).toContain("animate-spin")
+ expect(hasDisabledButton(html)).toBe(true)
+ expect(html).not.toContain(">Invite<")
+ })
+
+ it("shows Invited and stays disabled after success", () => {
+ const html = renderRow({ invited: true })
+ expect(html).toContain(">Invited<")
+ expect(hasDisabledButton(html)).toBe(true)
+ })
+})
+
+describe("runInviteFriend", () => {
+ beforeEach(() => {
+ toastSpy.mockClear()
+ })
+
+ it("covers the complete success lifecycle", async () => {
+ const inFlight = new Set<string>()
+ const state = trackingSetter()
+ const onInvited = vi.fn()
+
+ await expect(
+ runInviteFriend("user_1", inFlight, async () => {}, onInvited, state.setter),
+ ).resolves.toBe(true)
+
+ expect(state.snapshots).toEqual([["user_1"], []])
+ expect(onInvited).toHaveBeenCalledWith("user_1")
+ expect(toastSpy).not.toHaveBeenCalled()
+ })
+
+ it("clears the row and allows retry after failure", async () => {
+ const inFlight = new Set<string>()
+ const state = trackingSetter()
+ const sendInvite = vi.fn()
+ .mockRejectedValueOnce(new Error("network down"))
+ .mockResolvedValueOnce(undefined)
+
+ await expect(
+ runInviteFriend("user_1", inFlight, sendInvite, vi.fn(), state.setter),
+ ).resolves.toBe(false)
+ expect(inFlight).not.toContain("user_1")
+ expect(state.current()).toEqual([])
+ expect(toastSpy).toHaveBeenCalledWith("network down")
+
+ await expect(
+ runInviteFriend("user_1", inFlight, sendInvite, vi.fn(), state.setter),
+ ).resolves.toBe(true)
+ expect(sendInvite).toHaveBeenCalledTimes(2)
+ })
+
+ it("collapses rapid duplicate activation into one send chain", async () => {
+ const gate = deferred()
+ const inFlight = new Set<string>()
+ const state = trackingSetter()
+ const sendInvite = vi.fn(() => gate.promise)
+ const onInvited = vi.fn()
+
+ const first = runInviteFriend(
+ "user_1",
+ inFlight,
+ sendInvite,
+ onInvited,
+ state.setter,
+ )
+ const duplicate = runInviteFriend(
+ "user_1",
+ inFlight,
+ sendInvite,
+ onInvited,
+ state.setter,
+ )
+
+ await expect(duplicate).resolves.toBe(false)
+ expect(sendInvite).toHaveBeenCalledTimes(1)
+ gate.resolve()
+ await expect(first).resolves.toBe(true)
+ expect(onInvited).toHaveBeenCalledTimes(1)
+ })
+
+ it("keeps different friend rows independent", async () => {
+ const firstGate = deferred()
+ const inFlight = new Set<string>()
+ const state = trackingSetter()
+ const first = runInviteFriend(
+ "user_1",
+ inFlight,
+ () => firstGate.promise,
+ vi.fn(),
+ state.setter,
+ )
+
+ await expect(
+ runInviteFriend("user_2", inFlight, async () => {}, vi.fn(), state.setter),
+ ).resolves.toBe(true)
+ expect(inFlight).toEqual(new Set(["user_1"]))
+
+ firstGate.resolve()
+ await first
+ expect(inFlight).toEqual(new Set())
+ })
+})
diff --git a/src/web/src/components/community/social/invite-dialog.tsx b/src/web/src/components/community/social/invite-dialog.tsx
index 52924c872..c81792491 100644
--- a/src/web/src/components/community/social/invite-dialog.tsx
+++ b/src/web/src/components/community/social/invite-dialog.tsx
@@ -1,7 +1,8 @@
"use client"
-import { useEffect, useMemo, useState } from "react"
-import { Search } from "lucide-react"
+import type React from "react"
+import { useEffect, useMemo, useRef, useState } from "react"
+import { Loader2, Search } from "lucide-react"
import { toast } from "sonner"
import { Dialog, DialogContent } from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
@@ -25,6 +26,84 @@ function inviteUrl(token: string) {
return `${INVITE_ORIGIN}/c/invite/${token}`
}
+export function InviteFriendRow({
+ friend,
+ tokenReady,
+ inviting,
+ invited,
+ onInvite,
+}: {
+ friend: Friend
+ tokenReady: boolean
+ inviting: boolean
+ invited: boolean
+ onInvite: (friend: Friend) => void
+}) {
+ return (
+ <div className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent/40">
+ <Avatar
+ label={friend.avatar || friend.name}
+ seed={friend.userId}
+ size={32}
+ presence={friend.status}
+ ringColor="var(--popover)"
+ />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-sm font-medium">{friend.name}</div>
+ {hasStatus(friend.statusEmoji, friend.statusText) && (
+ <div className="truncate text-xs text-muted-foreground">
+ {friend.statusEmoji} {friend.statusText}
+ </div>
+ )}
+ </div>
+ <Button
+ size="sm"
+ variant={invited ? "secondary" : "default"}
+ disabled={!tokenReady || inviting || invited || !friend.userId}
+ onClick={() => onInvite(friend)}
+ >
+ {inviting ? (
+ <Loader2 aria-label="Sending invite" className="size-4 animate-spin" />
+ ) : invited ? (
+ "Invited"
+ ) : (
+ "Invite"
+ )}
+ </Button>
+ </div>
+ )
+}
+
+/**
+ * Own one friend's complete invite lifecycle. The mutable set is updated
+ * synchronously before React rerenders, so two rapid activations cannot start
+ * duplicate DM/message chains. Other user ids remain independent.
+ */
+export async function runInviteFriend(
+ userId: string,
+ inFlightUserIds: Set<string>,
+ sendInvite: () => Promise<void>,
+ onInvited: (userId: string) => void,
+ setInvitingUserIds: React.Dispatch<React.SetStateAction<Set<string>>>,
+): Promise<boolean> {
+ if (inFlightUserIds.has(userId)) return false
+
+ inFlightUserIds.add(userId)
+ setInvitingUserIds(new Set(inFlightUserIds))
+ try {
+ await sendInvite()
+ onInvited(userId)
+ return true
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : "Couldn't send invite"
+ toast(msg)
+ return false
+ } finally {
+ inFlightUserIds.delete(userId)
+ setInvitingUserIds(new Set(inFlightUserIds))
+ }
+}
+
/**
* Invite dialog: friends list at the top (each with an "Invite"
* button that sends the invite URL as a DM), plus a copyable link at the
@@ -57,6 +136,8 @@ export function InviteDialog({
const [token, setToken] = useState<string | null>(null)
const [resolveError, setResolveError] = useState<string | null>(null)
const [invitedUserIds, setInvitedUserIds] = useState<Set<string>>(new Set())
+ const [invitingUserIds, setInvitingUserIds] = useState<Set<string>>(new Set())
+ const inFlightUserIdsRef = useRef<Set<string>>(new Set())
const [query, setQuery] = useState("")
// Resolve on open. Only depends on `open` + `token` — resolveOrCreate is a
@@ -106,29 +187,34 @@ export function InviteDialog({
const inviteFriend = async (friend: Friend) => {
if (!token || !friend.userId) return
- try {
- const { conversation } = await createOrGetDm.mutateAsync({ userId: friend.userId })
- const receipt = acceptDmMessage({
- dmId: conversation.id,
- content: inviteUrl(token),
- author: {
- id: currentUser.id,
- name: currentUser.name,
- avatar: currentUser.avatar,
- },
- })
- if (!receipt.accepted) throw new Error("Couldn't send invite")
- const committed = await receipt.committed
- if (!committed.ok) throw committed.error
- setInvitedUserIds((prev) => {
- const next = new Set(prev)
- next.add(friend.userId!)
- return next
- })
- } catch (err) {
- const msg = err instanceof Error ? err.message : "Couldn't send invite"
- toast(msg)
- }
+ const userId = friend.userId
+ await runInviteFriend(
+ userId,
+ inFlightUserIdsRef.current,
+ async () => {
+ const { conversation } = await createOrGetDm.mutateAsync({ userId })
+ const receipt = acceptDmMessage({
+ dmId: conversation.id,
+ content: inviteUrl(token),
+ author: {
+ id: currentUser.id,
+ name: currentUser.name,
+ avatar: currentUser.avatar,
+ },
+ })
+ if (!receipt.accepted) throw new Error("Couldn't send invite")
+ const committed = await receipt.committed
+ if (!committed.ok) throw committed.error
+ },
+ (invitedUserId) => {
+ setInvitedUserIds((prev) => {
+ const next = new Set(prev)
+ next.add(invitedUserId)
+ return next
+ })
+ },
+ setInvitingUserIds,
+ )
}
const copyLink = async () => {
@@ -182,27 +268,16 @@ export function InviteDialog({
) : (
eligibleFriends.map((f) => {
const invited = f.userId ? invitedUserIds.has(f.userId) : false
+ const inviting = f.userId ? invitingUserIds.has(f.userId) : false
return (
- <div
+ <InviteFriendRow
key={f.id}
- className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent/40"
- >
- <Avatar label={f.avatar || f.name} seed={f.userId} size={32} presence={f.status} ringColor="var(--popover)" />
- <div className="min-w-0 flex-1">
- <div className="truncate text-sm font-medium">{f.name}</div>
- {hasStatus(f.statusEmoji, f.statusText) && (
- <div className="truncate text-xs text-muted-foreground">{f.statusEmoji} {f.statusText}</div>
- )}
- </div>
- <Button
- size="sm"
- variant={invited ? "secondary" : "default"}
- disabled={!token || invited || !f.userId}
- onClick={() => inviteFriend(f)}
- >
- {invited ? "Invited" : "Invite"}
- </Button>
- </div>
+ friend={f}
+ tokenReady={Boolean(token)}
+ inviting={inviting}
+ invited={invited}
+ onInvite={(candidate) => void inviteFriend(candidate)}
+ />
)
})
)}
diff --git a/src/web/src/hooks/community/community-ws/membership-events.test.ts b/src/web/src/hooks/community/community-ws/membership-events.test.ts
index f505c3ef8..9db655552 100644
--- a/src/web/src/hooks/community/community-ws/membership-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/membership-events.test.ts
@@ -1,6 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { QueryObserver } from "@tanstack/react-query"
import type { CommunityMemberJoin, CommunityMemberLeave, CommunityMemberUpdate } from "@alook/shared"
import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
+import { useCommunityWsStore } from "@/stores/community/ws"
+import { resolveRowPresence } from "@/lib/community/presence"
+import type { PresenceResponse } from "@/hooks/community/use-server-panels"
import { communityKeys } from "@/lib/query-keys"
import {
subscribeMemberOverlayEvents,
@@ -73,6 +77,84 @@ describe("useCommunityWs — member events", () => {
expect(cache?.pages[0].total).toBe(1)
})
+ it("exact-refetches only the joined server's active presence seed", async () => {
+ await mountHook()
+ const affectedKey = communityKeys.presence("srv_1")
+ const otherKey = communityKeys.presence("srv_2")
+ let online: string[] = []
+ const affectedQuery = vi.fn(async (): Promise<PresenceResponse> => ({ online }))
+ const otherQuery = vi.fn(async (): Promise<PresenceResponse> => ({
+ online: ["u_other"],
+ }))
+
+ await capturedQueryClient.fetchQuery({ queryKey: affectedKey, queryFn: affectedQuery })
+ await capturedQueryClient.fetchQuery({ queryKey: otherKey, queryFn: otherQuery })
+ const observer = new QueryObserver(capturedQueryClient, {
+ queryKey: affectedKey,
+ queryFn: affectedQuery,
+ staleTime: Infinity,
+ })
+ const unsubscribe = observer.subscribe(() => undefined)
+ const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ online = ["u_online"]
+
+ capturedOnMessage!({
+ type: "community:member.join",
+ serverId: "srv_1",
+ member: {
+ id: "mem_online",
+ userId: "u_online",
+ name: "Online member",
+ discriminator: "0001",
+ role: "member",
+ joinedAt: "2026-08-17T00:00:00.000Z",
+ },
+ } satisfies CommunityMemberJoin)
+
+ expect(invalidateSpy).toHaveBeenCalledWith({
+ queryKey: affectedKey,
+ exact: true,
+ refetchType: "active",
+ })
+ expect(invalidateSpy).not.toHaveBeenCalledWith(
+ expect.objectContaining({ queryKey: otherKey }),
+ )
+ await vi.waitFor(() => {
+ expect(capturedQueryClient.getQueryData(affectedKey)).toEqual({
+ online: ["u_online"],
+ })
+ })
+
+ capturedOnMessage!({
+ type: "community:member.join",
+ serverId: "srv_1",
+ member: {
+ id: "mem_offline",
+ userId: "u_offline",
+ name: "Offline member",
+ discriminator: "0002",
+ role: "member",
+ joinedAt: "2026-08-17T00:01:00.000Z",
+ },
+ } satisfies CommunityMemberJoin)
+
+ await vi.waitFor(() => {
+ expect(affectedQuery).toHaveBeenCalledTimes(3)
+ })
+ const refreshedSeed = capturedQueryClient.getQueryData<PresenceResponse>(affectedKey)
+ expect(refreshedSeed).toEqual({ online: ["u_online"] })
+ if (!refreshedSeed) throw new Error("missing refreshed presence seed")
+ useCommunityWsStore.getState().hydratePresence(refreshedSeed.online)
+ const onlineUserIds = useCommunityWsStore.getState().onlineUserIds
+ expect(resolveRowPresence({ userId: "u_online" }, onlineUserIds)).toBe("online")
+ expect(resolveRowPresence({ userId: "u_offline" }, onlineUserIds)).toBe("offline")
+ expect(otherQuery).toHaveBeenCalledTimes(1)
+ expect(capturedQueryClient.getQueryData(otherKey)).toEqual({
+ online: ["u_other"],
+ })
+ unsubscribe()
+ })
+
it("refreshes rail and server detail only when the joining member is the viewer", async () => {
await mountHook({ viewerUserId: "u_me" })
const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
diff --git a/src/web/src/hooks/community/community-ws/membership-events.ts b/src/web/src/hooks/community/community-ws/membership-events.ts
index 65a763099..09ee9bd3c 100644
--- a/src/web/src/hooks/community/community-ws/membership-events.ts
+++ b/src/web/src/hooks/community/community-ws/membership-events.ts
@@ -122,6 +122,14 @@ export function handleMemberJoin(
(cache) => patchCacheJoin(cache, event),
)
dispatchMemberOverlayEvent({ type: "refresh", serverId: event.serverId })
+ // MEMBER_JOIN intentionally carries identity, not presence. Refresh the
+ // affected server's authoritative presence seed so a newly rendered member
+ // does not inherit the offline fallback until the next presence frame.
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.presence(event.serverId),
+ exact: true,
+ refetchType: "active",
+ })
if (event.member.userId === viewerUserIdRef.current) {
void queryClient.invalidateQueries({
queryKey: communityKeys.channelRefDirectory(),
diff --git a/src/web/src/lib/community/attachment-presentation.test.ts b/src/web/src/lib/community/attachment-presentation.test.ts
index b92391a0b..6de82cfcd 100644
--- a/src/web/src/lib/community/attachment-presentation.test.ts
+++ b/src/web/src/lib/community/attachment-presentation.test.ts
@@ -95,9 +95,29 @@ describe("resolveAttachmentPresentation", () => {
.toEqual(presentation("text", "text"))
})
+ it.each([
+ ["README.md", "text/plain", presentation("text", "markdown")],
+ ["notes.txt", "text/plain; charset=utf-8", presentation("text", "text")],
+ ["source.ts", "text/plain", presentation("code", "code", "typescript")],
+ ["Dockerfile", "text/plain", presentation("code", "code", "dockerfile")],
+ ])("uses a known text/code filename to refine weak MIME: %s", (filename, contentType, expected) => {
+ expect(resolveAttachmentPresentation(filename, contentType)).toEqual(expected)
+ })
+
+ it.each([
+ ["archive.zip", "text/plain"],
+ ["photo.png", "text/plain"],
+ ["report.pdf", "text/plain"],
+ ])("does not let weak MIME promote a non-text extension: %s", (filename, contentType) => {
+ expect(resolveAttachmentPresentation(filename, contentType))
+ .toEqual(presentation("text", "text"))
+ })
+
it("does not let a misleading filename override a specific MIME", () => {
expect(resolveAttachmentPresentation("payload.html", "application/pdf"))
.toEqual(presentation("pdf", null))
+ expect(resolveAttachmentPresentation("payload.md", "application/pdf"))
+ .toEqual(presentation("pdf", null))
expect(resolveAttachmentPresentation("payload.ts", "application/x-custom"))
.toEqual(presentation("unknown", null))
})
diff --git a/src/web/src/lib/community/attachment-presentation.ts b/src/web/src/lib/community/attachment-presentation.ts
index 2f1b30802..dbac83b57 100644
--- a/src/web/src/lib/community/attachment-presentation.ts
+++ b/src/web/src/lib/community/attachment-presentation.ts
@@ -225,21 +225,34 @@ function filenameParts(filename: string): { basename: string; extension: string
return { basename, extension: dot > -1 ? basename.slice(dot + 1) : "" }
}
+function filenamePresentation(filename: string): AttachmentPresentation | undefined {
+ const { basename, extension } = filenameParts(filename)
+ return BASENAME_PRESENTATIONS[basename] ?? EXTENSION_PRESENTATIONS[extension]
+}
+
export function resolveAttachmentPresentation(
filename: string,
contentType?: string | null,
): AttachmentPresentation {
const normalizedType = contentType?.split(";", 1)[0]?.trim().toLowerCase() ?? ""
+ const fromFilename = filenamePresentation(filename)
+ // Browsers and operating systems commonly report Markdown and source files
+ // as text/plain. Let a known filename refine that weak signal only within
+ // the text/code preview family; it must never promote a misleading archive,
+ // media, or document extension over the supplied MIME.
+ if (
+ normalizedType === "text/plain"
+ && (fromFilename?.category === "text" || fromFilename?.category === "code")
+ ) {
+ return fromFilename
+ }
if (!GENERIC_CONTENT_TYPES.has(normalizedType)) {
for (const { matches, presentation } of MIME_PRESENTATIONS) {
if (matches(normalizedType)) return presentation
}
return { category: "unknown", previewKind: null, shikiLanguage: null }
}
- const { basename, extension } = filenameParts(filename)
- return BASENAME_PRESENTATIONS[basename]
- ?? EXTENSION_PRESENTATIONS[extension]
- ?? { category: "unknown", previewKind: null, shikiLanguage: null }
+ return fromFilename ?? { category: "unknown", previewKind: null, shikiLanguage: null }
}
export function resolveMediaContentType(