Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(web): reconcile channel rename caches (#596)
Genere193165d8375
diff --git a/src/web/src/app/api/community/channels/[id]/route.test.ts b/src/web/src/app/api/community/channels/[id]/route.test.tsindex 6bb963cba..13887dd19 100644--- a/src/web/src/app/api/community/channels/[id]/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/route.test.ts@@ -238,6 +238,7 @@ describe("PATCH /channels/[id] — permission gate", () => {const res = await PATCH(patchReq({ name: "General Chat" }), ctx)expect(res.status).toBe(200)expect(mockUpdateChannel).toHaveBeenCalledWith(expect.anything(), "c1", { name: "General-Chat" })+ await expect(res.json()).resolves.toEqual({ id: "c1", name: "General-Chat" })})it("returns 400 (and never calls updateChannel) when the renamed name is all disallowed characters", async () => {diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsxindex d52260304..a9272ee05 100644--- a/src/web/src/app/c/channels/layout.tsx+++ b/src/web/src/app/c/channels/layout.tsx@@ -4,7 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } froimport { useParams, usePathname, useRouter, useSearchParams } from "next/navigation"import { useQueryClient } from "@tanstack/react-query"import { toast } from "sonner"-import { apiFetch, toastApiError } from "@/lib/api/client"+import { toastApiError } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import { markSwitch } from "@/lib/perf/switch-mark"import { Dialog, DialogContent } from "@/components/ui/dialog"@@ -55,6 +55,7 @@ import {} from "@/hooks/community/use-notification-settings"import {useCreateChannel,+ useRenameChannel,useDeleteChannel,useMoveChannel,useCreateCategory,@@ -150,6 +151,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {// Mutationsconst createChannelMut = useCreateChannel()+ const renameChannelMut = useRenameChannel()const deleteChannelMut = useDeleteChannel()const moveChannelMut = useMoveChannel()const createCategoryMut = useCreateCategory()@@ -389,20 +391,12 @@ export default function ServerLayout({ children }: { children: ReactNode }) {{ onError: (e) => toastApiError(e, "Failed to create category") },)}, [createCategoryMut, serverId])- const onRenameChannel = useCallback(async (channelId: string, name: string) => {- try {- await apiFetch(`/api/community/channels/${channelId}`, {- method: "PATCH",- body: JSON.stringify({ name }),- })- void queryClient.invalidateQueries({- queryKey: communityKeys.channelRefDirectory(),- exact: true,- })- } catch (e) {- toastApiError(e, "Failed to rename channel")- }- }, [queryClient])+ const onRenameChannel = useCallback((channelId: string, name: string) => {+ renameChannelMut.mutate(+ { serverId, channelId, name },+ { onError: (e) => toastApiError(e, "Failed to rename channel") },+ )+ }, [renameChannelMut, serverId])const onDeleteChannelInSidebar = useCallback((channelId: string) => {deleteChannelMut.mutate({ serverId, channelId }, { onError: (e) => toastApiError(e, "Failed to delete channel") })}, [deleteChannelMut, serverId])diff --git a/src/web/src/components/community/channels/channel-sidebar.tsx b/src/web/src/components/community/channels/channel-sidebar.tsxindex c038a2610..c5f89c71c 100644--- a/src/web/src/components/community/channels/channel-sidebar.tsx+++ b/src/web/src/components/community/channels/channel-sidebar.tsx@@ -90,7 +90,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({activeThreadId?: string | nullonSelectForumThread?: (parentId: string, id: string) => void}) {- const { collapsed, catOrder, order, catNames, catPrivate, catPending, toggleCat, removeChannel, renameChannel, renameCategory, onDragOver, onDragEnd: treeDragEnd } = tree+ const { collapsed, catOrder, order, catNames, catPrivate, catPending, toggleCat, removeChannel, renameCategory, onDragOver, onDragEnd: treeDragEnd } = tree// Category the dragged channel started in — captured at drag start, because// `onDragOver` mutates `order` mid-drag so by drop time it already reflects// the destination.@@ -401,7 +401,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({category={catNames[dialog.categoryId] ?? ""}initial={{ name: dialog.name, type: dialog.type }}onClose={() => setDialog(null)}- onCreate={({ name }) => { renameChannel(dialog.id, name); onRenameChannel?.(dialog.id, name) }}+ onCreate={({ name }) => { onRenameChannel?.(dialog.id, name) }}/>)}{dialog?.kind === "create-category" && (diff --git a/src/web/src/components/community/channels/use-channel-tree.test.ts b/src/web/src/components/community/channels/use-channel-tree.test.tsindex 0b8ee7a4d..d149bc8c7 100644--- a/src/web/src/components/community/channels/use-channel-tree.test.ts+++ b/src/web/src/components/community/channels/use-channel-tree.test.ts@@ -1,6 +1,7 @@import React from "react"import TestRenderer, { act } from "react-test-renderer"import { describe, it, expect } from "vitest"+import { readFileSync } from "node:fs"import {catId,catOf,@@ -191,13 +192,20 @@ describe("mergeChannelMetadata", () => {expect(result.next.cat_A.find((c) => c.id === "a1")).toBe(order.cat_A[0])})- it("picks up a channel rename while ids are unchanged", () => {- const result = mergeChannelMetadata(order, [- cat("cat_A", [ch("a1"), { ...ch("a2"), name: "renamed" }]),+ it("follows optimistic, normalized, and rollback names while ids and order stay unchanged", () => {+ const incoming = (name: string) => [+ cat("cat_A", [ch("a1"), { ...ch("a2"), name }]),cat("cat_B", [ch("b1"), ch("b2"), ch("b3")]),- ])- expect(result.changed).toBe(true)- expect(result.next.cat_A.find((c) => c.id === "a2")?.name).toBe("renamed")+ ]+ const optimistic = mergeChannelMetadata(order, incoming("General Chat"))+ const normalized = mergeChannelMetadata(optimistic.next, incoming("General-Chat"))+ const rolledBack = mergeChannelMetadata(optimistic.next, incoming("a2"))++ expect(optimistic.next.cat_A.find((c) => c.id === "a2")?.name).toBe("General Chat")+ expect(normalized.next.cat_A.find((c) => c.id === "a2")?.name).toBe("General-Chat")+ expect(rolledBack.next.cat_A.find((c) => c.id === "a2")?.name).toBe("a2")+ expect(normalized.next.cat_A.map((channel) => channel.id)).toEqual(["a1", "a2"])+ expect(normalized.next.cat_B.map((channel) => channel.id)).toEqual(["b1", "b2", "b3"])})it("preserves category/channel order — only rewrites the changed field", () => {@@ -236,3 +244,19 @@ describe("mergeChannelMetadata", () => {expect(row?.unread).toBe(true)})})++describe("ChannelSidebar rename ownership", () => {+ it("submits through the external mutation without eagerly mutating the local tree", () => {+ const source = readFileSync(new URL("./channel-sidebar.tsx", import.meta.url), "utf8")+ expect(source).toContain("onCreate={({ name }) => { onRenameChannel?.(dialog.id, name) }}")+ expect(source).not.toContain("renameChannel(dialog.id, name)")+ })++ it("keeps title, same-server refs, and member UI on reconciled server detail", () => {+ const source = readFileSync(new URL("./channel-route.tsx", import.meta.url), "utf8")+ expect(source).toContain("topLevelName: channelInServer?.name")+ expect(source).toContain(".map((channel) => toChannelRefCandidate(currentServer, channel))")+ expect(source).toContain("useChannelMemberViewModel({")+ expect(source).toContain("channelName,\n currentServer,")+ })+})diff --git a/src/web/src/components/community/messages/use-composer-controller.test.ts b/src/web/src/components/community/messages/use-composer-controller.test.tsindex b8a495e3a..67777148d 100644--- a/src/web/src/components/community/messages/use-composer-controller.test.ts+++ b/src/web/src/components/community/messages/use-composer-controller.test.ts@@ -74,6 +74,12 @@ type TestEditor = {isEmpty: booleangetText: ReturnType<typeof vi.fn>getJSON: ReturnType<typeof vi.fn>+ state: {+ tr: object+ }+ view: {+ dispatch: ReturnType<typeof vi.fn>+ }commands: {clearContent: ReturnType<typeof vi.fn>focus: ReturnType<typeof vi.fn>@@ -96,6 +102,8 @@ describe("useComposerController", () => {let clearContent: ReturnType<typeof vi.fn>let focus: ReturnType<typeof vi.fn>let setContent: ReturnType<typeof vi.fn>+ let dispatch: ReturnType<typeof vi.fn>+ let transaction: objectlet chainFocus: ReturnType<typeof vi.fn>let insertContent: ReturnType<typeof vi.fn>let run: ReturnType<typeof vi.fn>@@ -114,6 +122,8 @@ describe("useComposerController", () => {clearContent = vi.fn()focus = vi.fn()setContent = vi.fn()+ dispatch = vi.fn()+ transaction = {}run = vi.fn()insertContent = vi.fn(() => ({ run }))chainFocus = vi.fn(() => ({ insertContent }))@@ -129,6 +139,8 @@ describe("useComposerController", () => {isEmpty: false,getText: vi.fn(() => " hello @everyone "),getJSON: vi.fn(() => ({ type: "doc" })),+ state: { tr: transaction },+ view: { dispatch },commands: {clearContent,focus,@@ -498,6 +510,69 @@ describe("useComposerController", () => {expect(mocks.placeholderConfigure).toHaveBeenCalledTimes(2)})+ it("updates the live placeholder without replacing or resetting the editor", async () => {+ const props = acceptedProps(() => true)+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(createElement(Harness, props))+ })+ const firstEditor = renderer.root.findByType("controller-probe").props.view+ .editor+ const livePlaceholder = mocks.placeholderConfigure.mock.calls[0]?.[0]+ .placeholder as () => string+ expect(livePlaceholder()).toBe("Message /general")+ expect(dispatch).not.toHaveBeenCalled()++ await act(async () => {+ renderer.update(+ createElement(Harness, { ...props, channel: "renamed-channel" }),+ )+ })+ expect(renderer.root.findByType("controller-probe").props.view.editor).toBe(+ firstEditor,+ )+ expect(livePlaceholder()).toBe("Message /renamed-channel")+ expect(dispatch).toHaveBeenCalledTimes(1)+ expect(dispatch).toHaveBeenLastCalledWith(transaction)++ await act(async () => {+ renderer.update(+ createElement(Harness, {+ ...props,+ channel: "another-channel",+ placeholder: "Custom composer prompt",+ }),+ )+ })+ expect(livePlaceholder()).toBe("Custom composer prompt")+ expect(dispatch).toHaveBeenCalledTimes(2)++ await act(async () => {+ renderer.update(+ createElement(Harness, {+ ...props,+ channel: "final-channel",+ placeholder: "Custom composer prompt",+ }),+ )+ })+ expect(livePlaceholder()).toBe("Custom composer prompt")+ expect(dispatch).toHaveBeenCalledTimes(2)++ await act(async () => {+ renderer.update(+ createElement(Harness, { ...props, channel: "final-channel" }),+ )+ })+ expect(livePlaceholder()).toBe("Message /final-channel")+ expect(dispatch).toHaveBeenCalledTimes(3)+ expect(clearContent).not.toHaveBeenCalled()+ expect(setContent).not.toHaveBeenCalled()+ expect(focus).not.toHaveBeenCalled()+ expect(mocks.clearDraft).not.toHaveBeenCalled()+ expect(mocks.writeDraft).not.toHaveBeenCalled()+ })+it("restores valid JSON without typing, dirty, or draft-write side effects", async () => {const doc = { type: "doc", content: [{ type: "paragraph" }] }const onTyping = vi.fn()diff --git a/src/web/src/components/community/messages/use-composer-controller.ts b/src/web/src/components/community/messages/use-composer-controller.tsindex 3d1b96a41..80396cfdd 100644--- a/src/web/src/components/community/messages/use-composer-controller.ts+++ b/src/web/src/components/community/messages/use-composer-controller.ts@@ -1,4 +1,5 @@import {+ useCallback,useEffect,useImperativeHandle,useLayoutEffect,@@ -100,6 +101,11 @@ export function useComposerController([],)const restoringDraftRef = useRef(false)+ const resolvedPlaceholder =+ placeholder ??+ (context === "channel" ? `Message /${channel}` : `Message ${channel}`)+ const placeholderRef = useRef(resolvedPlaceholder)+ const resolvePlaceholder = useCallback(() => placeholderRef.current, [])const suggestions = useComposerSuggestions({members,@@ -135,10 +141,9 @@ export function useComposerController(listItem: false,listKeymap: false,}),+ // eslint-disable-next-line react-hooks/refsPlaceholder.configure({- placeholder:- placeholder ??- (context === "channel" ? `Message /${channel}` : `Message ${channel}`),+ placeholder: resolvePlaceholder,}),suggestions.mentionExtension,suggestions.channelRefExtension,@@ -221,6 +226,13 @@ export function useComposerController(},})+ useLayoutEffect(() => {+ if (placeholderRef.current === resolvedPlaceholder) return+ placeholderRef.current = resolvedPlaceholder+ if (!editor) return+ editor.view?.dispatch(editor.state.tr)+ }, [editor, resolvedPlaceholder])+useEffect(() => {if (!editor || isForumThreadBody || !draftKey) returnconst doc = readComposerDraft(draftKey)diff --git a/src/web/src/hooks/community/mutations/channels.test.ts b/src/web/src/hooks/community/mutations/channels.test.tsindex 29bd30f9b..741bfc4c2 100644--- a/src/web/src/hooks/community/mutations/channels.test.ts+++ b/src/web/src/hooks/community/mutations/channels.test.ts@@ -67,6 +67,140 @@ beforeEach(() => {capturedQc = new QueryClient()})+describe("useRenameChannel", () => {+ type CachedChannel = { id: string; name: string; active: boolean; unread: boolean }+ type CachedCategory = { id: string; name: string; channels: CachedChannel[] }+ const originalServer = () => ({+ id: "s1",+ name: "Studio",+ discriminator: "0042",+ description: "",+ icon: null,+ ownerId: "u1",+ categories: [{+ id: "cat_1",+ name: "Channels",+ channels: [+ { id: "c1", name: "general", active: true, unread: false },+ { id: "c2", name: "random", active: false, unread: true },+ ],+ }],+ })+ const originalDirectory = () => [{+ id: "s1",+ name: "Studio",+ discriminator: "0042",+ channels: [+ { id: "c1", name: "general" },+ { id: "c2", name: "random" },+ ],+ }, {+ id: "s2",+ name: "Elsewhere",+ discriminator: "0100",+ channels: [{ id: "c3", name: "other" }],+ }]+ const seed = () => {+ capturedQc.setQueryData(communityKeys.server("s1"), originalServer())+ capturedQc.setQueryData(communityKeys.channelRefDirectory(), originalDirectory())+ }+ const serverChannels = () =>+ capturedQc.getQueryData<{ categories: CachedCategory[] }>(communityKeys.server("s1"))!+ .categories.flatMap((category) => category.channels)+ const directory = () =>+ capturedQc.getQueryData<ReturnType<typeof originalDirectory>>(communityKeys.channelRefDirectory())!++ it("cancels both exact queries before optimistically patching both caches", async () => {+ seed()+ apiFetchMock.mockResolvedValueOnce({ id: "c1", name: "General-Chat" })+ const mod = await load()+ mod.useRenameChannel()+ const cancelSpy = vi.spyOn(capturedQc, "cancelQueries")++ await capturedConfig!.onMutate!({ serverId: "s1", channelId: "c1", name: " General Chat " })++ expect(cancelSpy).toHaveBeenCalledWith({+ queryKey: communityKeys.server("s1"),+ exact: true,+ })+ expect(cancelSpy).toHaveBeenCalledWith({+ queryKey: communityKeys.channelRefDirectory(),+ exact: true,+ })+ expect(serverChannels().map((channel) => channel.name)).toEqual(["General Chat", "random"])+ expect(directory()[0].channels.map((channel) => channel.name)).toEqual(["General Chat", "random"])+ expect(directory()[1]).toEqual(originalDirectory()[1])+ })++ it("reconciles both caches to the PATCH response's normalized name", async () => {+ seed()+ apiFetchMock.mockResolvedValueOnce({ id: "c1", name: "General-Chat" })+ const mod = await load()+ mod.useRenameChannel()++ await runMutation({ serverId: "s1", channelId: "c1", name: "General Chat" })++ expect(apiFetchMock).toHaveBeenCalledWith(+ "/api/community/channels/c1",+ { method: "PATCH", body: JSON.stringify({ name: "General Chat" }) },+ )+ expect(serverChannels().find((channel) => channel.id === "c1")?.name).toBe("General-Chat")+ expect(directory()[0].channels.find((channel) => channel.id === "c1")?.name).toBe("General-Chat")+ })++ it("restores both snapshots on failure without optimistic residue", async () => {+ seed()+ apiFetchMock.mockRejectedValueOnce(new Error("duplicate"))+ const mod = await load()+ mod.useRenameChannel()++ await runMutation({ serverId: "s1", channelId: "c1", name: "Taken Name" }).catch(() => {})++ expect(serverChannels().find((channel) => channel.id === "c1")?.name).toBe("general")+ expect(directory()[0].channels.find((channel) => channel.id === "c1")?.name).toBe("general")+ })++ it.each(["success", "error"] as const)(+ "invalidates exact server detail and ref directory after %s",+ async (outcome) => {+ seed()+ if (outcome === "success") {+ apiFetchMock.mockResolvedValueOnce({ id: "c1", name: "renamed" })+ } else {+ apiFetchMock.mockRejectedValueOnce(new Error("boom"))+ }+ const mod = await load()+ mod.useRenameChannel()+ const invalidateSpy = vi.spyOn(capturedQc, "invalidateQueries")++ await runMutation({ serverId: "s1", channelId: "c1", name: "renamed" }).catch(() => {})++ expect(invalidateSpy).toHaveBeenCalledWith({+ queryKey: communityKeys.server("s1"),+ exact: true,+ })+ expect(invalidateSpy).toHaveBeenCalledWith({+ queryKey: communityKeys.channelRefDirectory(),+ exact: true,+ })+ },+ )++ it("leaves present caches unchanged when the channel is missing", async () => {+ seed()+ apiFetchMock.mockResolvedValueOnce({ id: "missing", name: "renamed" })+ const beforeServer = capturedQc.getQueryData(communityKeys.server("s1"))+ const beforeDirectory = capturedQc.getQueryData(communityKeys.channelRefDirectory())+ const mod = await load()+ mod.useRenameChannel()++ await runMutation({ serverId: "s1", channelId: "missing", name: "renamed" })++ expect(capturedQc.getQueryData(communityKeys.server("s1"))).toBe(beforeServer)+ expect(capturedQc.getQueryData(communityKeys.channelRefDirectory())).toBe(beforeDirectory)+ })+})+describe("useMoveChannel", () => {it("PATCHes the channel with the new categoryId and invalidates the server tree", async () => {apiFetchMock.mockResolvedValueOnce(undefined)diff --git a/src/web/src/hooks/community/mutations/channels.ts b/src/web/src/hooks/community/mutations/channels.tsindex 8482633d2..10bbc472a 100644--- a/src/web/src/hooks/community/mutations/channels.ts+++ b/src/web/src/hooks/community/mutations/channels.ts@@ -4,6 +4,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query"import { nanoid } from "nanoid"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"+import type { ChannelRefDirectory } from "@/lib/community/channel-ref"import type { ServerDetail } from "@/hooks/community/use-servers"import { UNCATEGORIZED_CATEGORY_ID, type ChannelType } from "@alook/shared"@@ -147,6 +148,113 @@ export type MoveChannelArgs = {categoryId: string | null}+export type RenameChannelArgs = {+ serverId: string+ channelId: string+ name: string+}+export type RenameChannelResult = { id: string; name: string }++type RenameChannelCtx = {+ serverSnapshot?: ServerDetail+ directorySnapshot?: ChannelRefDirectory+}++function renameServerDetailChannel(+ detail: ServerDetail | undefined,+ channelId: string,+ name: string,+): ServerDetail | undefined {+ if (!detail) return detail+ let changed = false+ const categories = detail.categories.map((category) => {+ let categoryChanged = false+ const channels = category.channels.map((channel) => {+ if (channel.id !== channelId || channel.name === name) return channel+ categoryChanged = true+ changed = true+ return { ...channel, name }+ })+ return categoryChanged ? { ...category, channels } : category+ })+ return changed ? { ...detail, categories } : detail+}++function renameDirectoryChannel(+ directory: ChannelRefDirectory | undefined,+ serverId: string,+ channelId: string,+ name: string,+): ChannelRefDirectory | undefined {+ if (!directory) return directory+ let changed = false+ const next = directory.map((server) => {+ if (server.id !== serverId) return server+ let serverChanged = false+ const channels = server.channels.map((channel) => {+ if (channel.id !== channelId || channel.name === name) return channel+ serverChanged = true+ changed = true+ return { ...channel, name }+ })+ return serverChanged ? { ...server, channels } : server+ })+ return changed ? next : directory+}++export function useRenameChannel() {+ const queryClient = useQueryClient()+ return useMutation<RenameChannelResult, Error, RenameChannelArgs, RenameChannelCtx>({+ mutationFn: async ({ channelId, name }) => {+ return apiFetch<RenameChannelResult>(`/api/community/channels/${channelId}`, {+ method: "PATCH",+ body: JSON.stringify({ name }),+ })+ },+ onMutate: async (args) => {+ const serverKey = communityKeys.server(args.serverId)+ const directoryKey = communityKeys.channelRefDirectory()+ await Promise.all([+ queryClient.cancelQueries({ queryKey: serverKey, exact: true }),+ queryClient.cancelQueries({ queryKey: directoryKey, exact: true }),+ ])+ const serverSnapshot = queryClient.getQueryData<ServerDetail>(serverKey)+ const directorySnapshot = queryClient.getQueryData<ChannelRefDirectory>(directoryKey)+ const optimisticName = args.name.trim()+ queryClient.setQueryData<ServerDetail>(serverKey, (prev) =>+ renameServerDetailChannel(prev, args.channelId, optimisticName),+ )+ queryClient.setQueryData<ChannelRefDirectory>(directoryKey, (prev) =>+ renameDirectoryChannel(prev, args.serverId, args.channelId, optimisticName),+ )+ return { serverSnapshot, directorySnapshot }+ },+ onSuccess: (data, args) => {+ queryClient.setQueryData<ServerDetail>(communityKeys.server(args.serverId), (prev) =>+ renameServerDetailChannel(prev, args.channelId, data.name),+ )+ queryClient.setQueryData<ChannelRefDirectory>(communityKeys.channelRefDirectory(), (prev) =>+ renameDirectoryChannel(prev, args.serverId, args.channelId, data.name),+ )+ },+ onError: (_err, args, ctx) => {+ if (ctx?.serverSnapshot) {+ queryClient.setQueryData(communityKeys.server(args.serverId), ctx.serverSnapshot)+ }+ if (ctx?.directorySnapshot) {+ queryClient.setQueryData(communityKeys.channelRefDirectory(), ctx.directorySnapshot)+ }+ },+ onSettled: (_data, _err, args) => {+ void queryClient.invalidateQueries({+ queryKey: communityKeys.server(args.serverId),+ exact: true,+ })+ invalidateChannelRefDirectory(queryClient)+ },+ })+}+/*** Move a channel to another category (or to uncategorized with `null`). The* backend (`channels/[id]` PATCH) is admin-only and rejects a move that would