Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(portal): open a rename dialog from the document more menu (#20360)

Arvin Xu251f9cb64777
diff --git a/src/components/RenameModal/index.tsx b/src/components/RenameModal/index.tsx
index c3890279738..f11936f62c1 100644
--- a/src/components/RenameModal/index.tsx
+++ b/src/components/RenameModal/index.tsx
@@ -16,11 +16,12 @@ import { useTranslation } from 'react-i18next';
interface RenameModalContentProps {
defaultValue: string;
description?: string;
+ maxLength?: number;
onSave: (newTitle: string) => void | Promise<void>;
}
const RenameModalContent = memo<RenameModalContentProps>(
- ({ defaultValue, description, onSave }) => {
+ ({ defaultValue, description, maxLength, onSave }) => {
const { t: tCommon } = useTranslation('common');
const { close } = useModalContext();
const [value, setValue] = useState(defaultValue);
@@ -45,6 +46,9 @@ const RenameModalContent = memo<RenameModalContentProps>(
try {
await onSave(next);
close();
+ } catch {
+ // A rejected save keeps the dialog open so the typed title can be
+ // retried; `onSave` owns reporting the failure.
} finally {
setLoading(false);
}
@@ -59,6 +63,7 @@ const RenameModalContent = memo<RenameModalContentProps>(
) : null}
<Input
autoFocus
+ maxLength={maxLength}
ref={inputRef}
value={value}
onChange={(e) => setValue(e.target.value)}
@@ -82,6 +87,7 @@ RenameModalContent.displayName = 'RenameModalContent';
export interface OpenRenameModalProps {
defaultValue: string;
description?: string;
+ maxLength?: number;
onSave: (newTitle: string) => void | Promise<void>;
title?: string;
}
@@ -89,12 +95,18 @@ export interface OpenRenameModalProps {
export const openRenameModal = ({
defaultValue,
description,
+ maxLength,
onSave,
title,
}: OpenRenameModalProps): ModalInstance =>
createModal({
content: (
- <RenameModalContent defaultValue={defaultValue} description={description} onSave={onSave} />
+ <RenameModalContent
+ defaultValue={defaultValue}
+ description={description}
+ maxLength={maxLength}
+ onSave={onSave}
+ />
),
footer: null,
maskClosable: true,
diff --git a/src/features/Portal/Document/Header.tsx b/src/features/Portal/Document/Header.tsx
index dab772f7e66..224753d3177 100644
--- a/src/features/Portal/Document/Header.tsx
+++ b/src/features/Portal/Document/Header.tsx
@@ -4,11 +4,10 @@ import { Flexbox, Icon } from '@lobehub/ui';
import { Skeleton, Text } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { ChevronRight } from 'lucide-react';
-import { type ChangeEvent, memo, useCallback, useEffect, useRef } from 'react';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { usePortalDocumentTitleState } from './titleContext';
-import { TITLE_MAX_LENGTH } from './usePortalDocumentHeader';
const styles = createStaticStyles(({ css }) => ({
root: css`
@@ -19,33 +18,9 @@ const styles = createStaticStyles(({ css }) => ({
color: ${cssVar.colorTextQuaternary};
`,
title: css`
- cursor: text;
font-size: 13px;
font-weight: 600;
`,
- titleInput: css`
- flex: 1;
-
- min-width: 0;
- padding: 0;
- border: none;
-
- font: inherit;
- font-size: 13px;
- font-weight: 600;
- text-align: start;
-
- background: transparent;
-
- /* Keep a token-based focus ring for keyboard users; the native outline
- is suppressed only in favor of this replacement. */
- outline: none;
-
- &:focus-visible {
- border-radius: ${cssVar.borderRadiusSM};
- box-shadow: 0 0 0 2px ${cssVar.colorPrimaryBorder};
- }
- `,
crumbButton: css`
cursor: pointer;
@@ -84,66 +59,15 @@ interface HeaderProps {
const Header = memo<HeaderProps>(({ onOpenDocumentsIndex }) => {
const { t } = useTranslation('file');
- const {
- cancelEdit,
- commitEdit,
- draft,
- editing,
- isLoading,
- metaLocked,
- setDraft,
- startEdit,
- syncIdleDraft,
- titleFallback,
- } = usePortalDocumentTitleState();
-
- const inputRef = useRef<HTMLInputElement>(null);
-
- // Follow the SWR source while idle; never clobber a draft mid-typing.
- useEffect(() => {
- syncIdleDraft(editing);
- }, [editing, syncIdleDraft]);
-
- // Rename from the header's `…` menu flips the same shared edit state, so
- // focus follows the flag rather than the click that started it.
- useEffect(() => {
- if (!editing) return;
- const frame = requestAnimationFrame(() => inputRef.current?.focus());
- return () => cancelAnimationFrame(frame);
- }, [editing]);
-
- const handleTitleKeyDown = useCallback(
- (event: React.KeyboardEvent<HTMLInputElement>) => {
- if (event.key === 'Enter') {
- // blur commits; Escape restores first so the blur writes nothing new.
- event.preventDefault();
- inputRef.current?.blur();
- } else if (event.key === 'Escape') {
- // Cancel BEFORE blurring: blur fires `commitEdit` synchronously with
- // the still-edited draft, so the cancel flag is what turns that commit
- // into a no-op instead of persisting the cancelled title.
- event.preventDefault();
- cancelEdit();
- inputRef.current?.blur();
- }
- },
- [cancelEdit],
- );
+ const { isLoading, savedTitle, titleFallback } = usePortalDocumentTitleState();
if (isLoading) {
return <Skeleton height={16} width={180} />;
}
return (
- // Hug the title so the shared `…` rides right behind it; only an open
- // editor claims the free width to type into.
- <Flexbox
- horizontal
- align={'center'}
- className={styles.root}
- flex={editing ? 1 : '0 1 auto'}
- gap={4}
- >
+ // Hug the title so the shared `…` rides right behind it.
+ <Flexbox horizontal align={'center'} className={styles.root} flex={'0 1 auto'} gap={4}>
{/* Navigable crumb gets a real button (keyboard reachable); a plain
notebook document renders a noninteractive label with no affordance. */}
{onOpenDocumentsIndex ? (
@@ -156,26 +80,14 @@ const Header = memo<HeaderProps>(({ onOpenDocumentsIndex }) => {
</Text>
)}
<Icon className={styles.separator} icon={ChevronRight} size={14} />
- {editing ? (
- <input
- className={styles.titleInput}
- maxLength={TITLE_MAX_LENGTH}
- ref={inputRef}
- value={draft}
- onBlur={commitEdit}
- onChange={(event: ChangeEvent<HTMLInputElement>) => setDraft(event.target.value)}
- onKeyDown={handleTitleKeyDown}
- />
- ) : (
- <Text
- className={styles.title}
- ellipsis={{ tooltip: draft || titleFallback }}
- style={{ minWidth: 0 }}
- onClick={metaLocked ? undefined : startEdit}
- >
- {draft || titleFallback}
- </Text>
- )}
+ {/* Display only — renaming goes through the `…` menu's dialog. */}
+ <Text
+ className={styles.title}
+ ellipsis={{ tooltip: savedTitle || titleFallback }}
+ style={{ minWidth: 0 }}
+ >
+ {savedTitle || titleFallback}
+ </Text>
</Flexbox>
);
});
diff --git a/src/features/Portal/Document/titleContext.tsx b/src/features/Portal/Document/titleContext.tsx
index ef99e0baf90..27898726212 100644
--- a/src/features/Portal/Document/titleContext.tsx
+++ b/src/features/Portal/Document/titleContext.tsx
@@ -9,8 +9,9 @@ type PortalDocumentTitleState = ReturnType<typeof usePortalDocumentTitle>;
const PortalDocumentTitleContext = createContext<PortalDocumentTitleState | null>(null);
/**
- * One title edit session per portal document, shared by the inline title and
- * the header's `…` menu — "Rename" in the menu opens the same inline editor.
+ * One title state per portal document, shared by the header title and the
+ * header's `…` menu — "Rename" in the menu opens a dialog that saves through
+ * the serialized title write.
*/
export const PortalDocumentTitleProvider = ({ children }: PropsWithChildren) => {
const value = usePortalDocumentTitle();
diff --git a/src/features/Portal/Document/useMoreMenu.test.ts b/src/features/Portal/Document/useMoreMenu.test.ts
index c023b5231b8..c1957328f6a 100644
--- a/src/features/Portal/Document/useMoreMenu.test.ts
+++ b/src/features/Portal/Document/useMoreMenu.test.ts
@@ -11,9 +11,10 @@ const mocks = vi.hoisted(() => ({
documentId: 'doc_1' as string | undefined,
isLoading: false,
metaLocked: false,
+ openRenameModal: vi.fn(),
refresh: vi.fn(),
removeDocument: vi.fn(),
- startEdit: vi.fn(),
+ saveTitle: vi.fn(),
toastError: vi.fn(),
toastSuccess: vi.fn(),
url: 'https://app.lobehub.com/agent/agt_1/docs/doc_1' as string | undefined,
@@ -24,6 +25,10 @@ vi.mock('@lobehub/ui/base-ui', () => ({
toast: { error: mocks.toastError, success: mocks.toastSuccess },
}));
+vi.mock('@/components/RenameModal', () => ({
+ openRenameModal: mocks.openRenameModal,
+}));
+
vi.mock('@/services/agentDocument', () => ({
agentDocumentService: { removeDocument: mocks.removeDocument },
}));
@@ -37,11 +42,13 @@ vi.mock('./titleContext', () => ({
usePortalDocumentTitleState: () => ({
isLoading: mocks.isLoading,
metaLocked: mocks.metaLocked,
- startEdit: mocks.startEdit,
+ savedTitle: 'Spring Trail Collection — Launch Brief',
+ saveTitle: mocks.saveTitle,
}),
}));
vi.mock('./usePortalDocumentHeader', () => ({
+ TITLE_MAX_LENGTH: 100,
usePortalDocumentHeaderActions: () => ({
agentDocumentId: mocks.agentDocumentId,
agentId: mocks.agentId,
@@ -73,6 +80,22 @@ describe('useDocumentMoreMenu', () => {
expect(result.current?.delete).toBeTypeOf('function');
});
+ it('renames through a dialog seeded with the saved title', async () => {
+ const { result } = renderHook(() => useDocumentMoreMenu());
+ result.current!.rename!();
+
+ expect(mocks.openRenameModal).toHaveBeenCalledOnce();
+ const options = mocks.openRenameModal.mock.calls[0][0];
+ expect(options).toMatchObject({
+ defaultValue: 'Spring Trail Collection — Launch Brief',
+ maxLength: 100,
+ });
+
+ // Saving goes through the shared serialized title write.
+ await options.onSave('Spring Trail Brief');
+ expect(mocks.saveTitle).toHaveBeenCalledWith('Spring Trail Brief');
+ });
+
it('opens a danger confirmation before removing the document', () => {
const { result } = renderHook(() => useDocumentMoreMenu());
result.current!.delete!();
diff --git a/src/features/Portal/Document/useMoreMenu.ts b/src/features/Portal/Document/useMoreMenu.ts
index bc79d7d2706..f19f0454db1 100644
--- a/src/features/Portal/Document/useMoreMenu.ts
+++ b/src/features/Portal/Document/useMoreMenu.ts
@@ -1,16 +1,17 @@
import { confirmModal, toast } from '@lobehub/ui/base-ui';
import { useTranslation } from 'react-i18next';
+import { openRenameModal } from '@/components/RenameModal';
import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
import { agentDocumentService } from '@/services/agentDocument';
import { useChatStore } from '@/store/chat';
import { usePortalDocumentTitleState } from './titleContext';
-import { usePortalDocumentHeaderActions } from './usePortalDocumentHeader';
+import { TITLE_MAX_LENGTH, usePortalDocumentHeaderActions } from './usePortalDocumentHeader';
export const useDocumentMoreMenu = (): PortalMoreMenuConfig | undefined => {
const { t } = useTranslation(['chat', 'common']);
- const { isLoading, metaLocked, startEdit } = usePortalDocumentTitleState();
+ const { isLoading, metaLocked, savedTitle, saveTitle } = usePortalDocumentTitleState();
const { agentDocumentId, agentId, documentId, refresh, url } = usePortalDocumentHeaderActions();
const closeDocument = useChatStore((s) => s.closeDocument);
@@ -53,6 +54,15 @@ export const useDocumentMoreMenu = (): PortalMoreMenuConfig | undefined => {
copyLink: url,
delete: agentDocumentId ? deleteDocument : undefined,
refresh,
- rename: metaLocked ? undefined : startEdit,
+ // A dialog, like every other portal's rename — flipping the header title
+ // into an input from a menu reads as a stray focused text field.
+ rename: metaLocked
+ ? undefined
+ : () =>
+ openRenameModal({
+ defaultValue: savedTitle,
+ maxLength: TITLE_MAX_LENGTH,
+ onSave: saveTitle,
+ }),
};
};
diff --git a/src/features/Portal/Document/usePortalDocumentHeader.test.ts b/src/features/Portal/Document/usePortalDocumentHeader.test.ts
index 7b63a4ea177..60b3575905c 100644
--- a/src/features/Portal/Document/usePortalDocumentHeader.test.ts
+++ b/src/features/Portal/Document/usePortalDocumentHeader.test.ts
@@ -90,6 +90,9 @@ vi.mock('@/hooks/useAppOrigin', () => ({
useAppOrigin: () => 'https://app.lobehub.com',
}));
+/** Title the SWR cache holds after the most recent optimistic write/rollback. */
+const lastCachedTitle = () => mockMutate.mock.lastCall?.[0]({ title: '' }).title;
+
describe('usePortalDocumentTitle', () => {
beforeEach(() => {
mockDocumentMeta.current = { filename: '开营筹备清单.md', title: '开营筹备清单' };
@@ -100,7 +103,7 @@ describe('usePortalDocumentTitle', () => {
toastError.mockClear();
});
- it('exposes the saved title (title before filename) and unlocks editing', () => {
+ it('exposes the saved title (title before filename) and unlocks renaming', () => {
const { result } = renderHook(() => usePortalDocumentTitle());
expect(result.current.savedTitle).toBe('开营筹备清单');
@@ -108,34 +111,43 @@ describe('usePortalDocumentTitle', () => {
expect(result.current.isLoading).toBe(false);
});
- it('commits a renamed title through the document service', async () => {
+ it('saves a trimmed title through the document service', async () => {
const { result } = renderHook(() => usePortalDocumentTitle());
- act(() => result.current.startEdit());
- act(() => result.current.setDraft('开营筹备清单 V2'));
await act(async () => {
- await result.current.commitEdit();
+ await result.current.saveTitle(' 开营筹备清单 V2 ');
});
expect(mockUpdateDocument).toHaveBeenCalledWith({
id: 'document-1',
title: '开营筹备清单 V2',
});
- expect(result.current.editing).toBe(false);
+ expect(lastCachedTitle()).toBe('开营筹备清单 V2');
+ });
+
+ it('skips the write for an empty or unchanged title', async () => {
+ const { result } = renderHook(() => usePortalDocumentTitle());
+
+ await act(async () => {
+ await result.current.saveTitle(' ');
+ await result.current.saveTitle('开营筹备清单');
+ });
+
+ expect(mockUpdateDocument).not.toHaveBeenCalled();
+ expect(mockMutate).not.toHaveBeenCalled();
});
it('rolls the optimistic title back when the write fails', async () => {
mockUpdateDocument.mockRejectedValueOnce(new Error('network'));
const { result } = renderHook(() => usePortalDocumentTitle());
- act(() => result.current.startEdit());
- act(() => result.current.setDraft('开营筹备清单 V2'));
+ // Rejects after rolling back, so the rename dialog stays open for a retry.
await act(async () => {
- await result.current.commitEdit();
+ await expect(result.current.saveTitle('开营筹备清单 V2')).rejects.toThrow('network');
});
expect(toastError).toHaveBeenCalled();
- expect(result.current.draft).toBe('开营筹备清单');
+ expect(lastCachedTitle()).toBe('开营筹备清单');
});
it('serializes overlapping saves: a stale rejected rename cannot roll back a newer one', async () => {
@@ -150,16 +162,10 @@ describe('usePortalDocumentTitle', () => {
.mockResolvedValueOnce(undefined);
const { result } = renderHook(() => usePortalDocumentTitle());
- // First (slow) rename — its promise never resolves until the stale reject
- // below, so fire it without awaiting.
- act(() => result.current.startEdit());
- act(() => result.current.setDraft('重命名一'));
- void result.current.commitEdit();
-
- // A newer rename lands first (fast server response).
- act(() => result.current.startEdit());
- act(() => result.current.setDraft('重命名二'));
- const secondCommit = result.current.commitEdit();
+ // First (slow) rename — fire it without awaiting.
+ void result.current.saveTitle('重命名一');
+ // A newer rename is submitted while the first is in flight.
+ const secondSave = result.current.saveTitle('重命名二');
await act(async () => {
await Promise.resolve();
await Promise.resolve();
@@ -170,17 +176,18 @@ describe('usePortalDocumentTitle', () => {
expect(mockUpdateDocument).toHaveBeenCalledTimes(1);
expect(mockUpdateDocument).toHaveBeenCalledWith({ id: 'document-1', title: '重命名一' });
- // The older request now REJECTS — it must not touch draft or cache,
- // because a newer save already claimed the latest ticket.
+ // The older request now REJECTS — it must not touch the cache, because a
+ // newer save already claimed the latest ticket.
await act(async () => {
rejectFirst(new Error('late failure'));
await new Promise((resolve) => setTimeout(resolve, 10));
});
await act(async () => {
- await secondCommit;
+ await secondSave;
});
- expect(result.current.draft).toBe('重命名二');
+ expect(mockUpdateDocument).toHaveBeenLastCalledWith({ id: 'document-1', title: '重命名二' });
+ expect(lastCachedTitle()).toBe('重命名二');
expect(toastError).not.toHaveBeenCalled();
});
@@ -196,15 +203,8 @@ describe('usePortalDocumentTitle', () => {
.mockResolvedValueOnce(undefined);
const { result } = renderHook(() => usePortalDocumentTitle());
- // First rename — held in flight by the server mock.
- act(() => result.current.startEdit());
- act(() => result.current.setDraft('重命名一'));
- void result.current.commitEdit();
-
- // Second rename submitted while the first is pending.
- act(() => result.current.startEdit());
- act(() => result.current.setDraft('重命名二'));
- const secondCommit = result.current.commitEdit();
+ void result.current.saveTitle('重命名一');
+ const secondSave = result.current.saveTitle('重命名二');
await act(async () => {
await Promise.resolve();
await Promise.resolve();
@@ -215,22 +215,19 @@ describe('usePortalDocumentTitle', () => {
await act(async () => {
releaseFirst(undefined);
- await secondCommit;
+ await secondSave;
});
// The second write fires only after the first settles, in submit order.
expect(mockUpdateDocument).toHaveBeenCalledTimes(2);
expect(mockUpdateDocument).toHaveBeenLastCalledWith({ id: 'document-1', title: '重命名二' });
- expect(result.current.draft).toBe('重命名二');
});
it('revalidates the agent-document list after a successful rename', async () => {
const { result } = renderHook(() => usePortalDocumentTitle());
- act(() => result.current.startEdit());
- act(() => result.current.setDraft('开营筹备清单 V2'));
await act(async () => {
- await result.current.commitEdit();
+ await result.current.saveTitle('开营筹备清单 V2');
});
expect(mockInvalidate).toHaveBeenCalledWith(
@@ -238,69 +235,7 @@ describe('usePortalDocumentTitle', () => {
);
});
- it('does not persist a cancelled title when Escape triggers the blur commit', async () => {
- const { result } = renderHook(() => usePortalDocumentTitle());
-
- act(() => result.current.startEdit());
- act(() => result.current.setDraft('被取消的名字'));
-
- // Escape path: cancelEdit runs first, then the input blur fires
- // `commitEdit` synchronously with the still-edited draft.
- act(() => result.current.cancelEdit());
- await act(async () => {
- await result.current.commitEdit();
- });
-
- expect(mockUpdateDocument).not.toHaveBeenCalled();
- expect(result.current.draft).toBe('开营筹备清单');
- expect(result.current.editing).toBe(false);
- });
-
- it('re-arms the cancel flag so the next real commit still writes', async () => {
- const { result } = renderHook(() => usePortalDocumentTitle());
-
- // Cancel one edit...
- act(() => result.current.startEdit());
- act(() => result.current.setDraft('被取消的名字'));
- act(() => result.current.cancelEdit());
- await act(async () => {
- await result.current.commitEdit();
- });
- expect(mockUpdateDocument).not.toHaveBeenCalled();
-
- // ...then commit a fresh rename normally.
- act(() => result.current.startEdit());
- act(() => result.current.setDraft('开营筹备清单 V2'));
- await act(async () => {
- await result.current.commitEdit();
- });
-
- expect(mockUpdateDocument).toHaveBeenCalledWith({
- id: 'document-1',
- title: '开营筹备清单 V2',
- });
- });
-
- it('clears a dangling cancel when a new edit session starts', async () => {
- const { result } = renderHook(() => usePortalDocumentTitle());
-
- // Cancel without the follow-up blur commit (e.g. input unmounted first).
- act(() => result.current.startEdit());
- act(() => result.current.cancelEdit());
-
- act(() => result.current.startEdit());
- act(() => result.current.setDraft('开营筹备清单 V2'));
- await act(async () => {
- await result.current.commitEdit();
- });
-
- expect(mockUpdateDocument).toHaveBeenCalledWith({
- id: 'document-1',
- title: '开营筹备清单 V2',
- });
- });
-
- it('locks meta for a managed skill index (rename must not rewrite SKILL.md)', () => {
+ it('locks meta for a managed skill index (rename must not rewrite SKILL.md)', async () => {
mockDocumentMeta.current = {
content: '---\nname: my-skill\n---\nbody',
fileType: 'skills/index',
@@ -311,20 +246,19 @@ describe('usePortalDocumentTitle', () => {
const { result } = renderHook(() => usePortalDocumentTitle());
expect(result.current.metaLocked).toBe(true);
- act(() => result.current.startEdit());
- expect(result.current.editing).toBe(false);
+ await act(async () => {
+ await result.current.saveTitle('renamed');
+ });
expect(mockUpdateDocument).not.toHaveBeenCalled();
});
- it('exposes the editor (not loading) for a loaded empty-title document', () => {
+ it('is not loading for a loaded empty-title document', () => {
mockDocumentMeta.current = { filename: '', title: '' };
const { result } = renderHook(() => usePortalDocumentTitle());
expect(result.current.isLoading).toBe(false);
expect(result.current.savedTitle).toBe('');
- act(() => result.current.startEdit());
- expect(result.current.editing).toBe(true);
});
});
diff --git a/src/features/Portal/Document/usePortalDocumentHeader.ts b/src/features/Portal/Document/usePortalDocumentHeader.ts
index a2482f5ef4c..484f069e92a 100644
--- a/src/features/Portal/Document/usePortalDocumentHeader.ts
+++ b/src/features/Portal/Document/usePortalDocumentHeader.ts
@@ -1,7 +1,7 @@
'use client';
import { toast } from '@lobehub/ui/base-ui';
-import { useCallback, useMemo, useRef, useState } from 'react';
+import { useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
@@ -22,12 +22,9 @@ import { useResolvedAgentDocumentId, useResolvedDocumentId } from './documentVie
export const TITLE_MAX_LENGTH = 100;
/**
- * Title state + actions for the portal document header: the saved title
- * (title › filename), the loading flag, and an edit/commit cycle that
- * persists through the document service.
- *
- * `syncIdleDraft` is called from a `useEffect` keyed on the editing flag —
- * the hook stays headless; the component decides when to resync.
+ * Title state + rename action for the portal document header: the saved title
+ * (title › filename), the loading flag, the meta lock, and a serialized title
+ * write used by the `…` menu's rename dialog.
*/
export const usePortalDocumentTitle = () => {
const { t } = useTranslation(['chat', 'common']);
@@ -57,109 +54,69 @@ export const usePortalDocumentTitle = () => {
const isSkillIndex = !!document && isSkillMarkdownDocument(document);
const metaLocked = isReadonly || isSkillIndex;
- const [draft, setDraft] = useState(savedTitle);
- const [editing, setEditing] = useState(false);
// Serializes title writes end-to-end. Two layers:
// 1. `saveChain` queues the SERVER calls — updateDocument mutations run
// in submit order, so a slow first request can never land after (and
// overwrite) a newer rename.
// 2. `saveTicketRef` gates the CLIENT-side settlement — only the newest
- // commit may touch the draft/SWR cache, so a rejected older request
- // cannot roll back a newer intent.
+ // save may touch the SWR cache, so a rejected older request cannot roll
+ // back a newer intent.
const saveChain = useSingleton(() => ({ current: Promise.resolve() as Promise<unknown> }));
const saveTicketRef = useRef(0);
- // Follow the SWR source while idle; never clobber a draft mid-typing.
- const syncIdleDraft = useCallback(
- (isEditing: boolean) => {
- if (!isEditing) setDraft(savedTitle);
- },
- [savedTitle],
- );
+ const saveTitle = useCallback(
+ async (title: string) => {
+ const nextTitle = title.trim();
+ // Empty or unchanged titles are not written.
+ if (metaLocked || !nextTitle || nextTitle === savedTitle || !documentId) return;
+
+ // Claim the newest save; only this ticket may settle the client state.
+ const ticket = ++saveTicketRef.current;
+ const previousTitle = savedTitle;
- // Marks the in-progress edit as cancelled. Escape calls this BEFORE blurring
- // the input: the blur that follows still fires `commitEdit`, but the flag
- // makes that commit a no-op restore instead of persisting the edited draft
- // the user just threw away.
- const cancelEditRef = useRef(false);
-
- const startEdit = useCallback(() => {
- if (metaLocked) return;
- // A fresh edit session never inherits a cancel whose blur commit never fired.
- cancelEditRef.current = false;
- setDraft(savedTitle);
- setEditing(true);
- }, [metaLocked, savedTitle]);
-
- const cancelEdit = useCallback(() => {
- cancelEditRef.current = true;
- setDraft(savedTitle);
- setEditing(false);
- }, [savedTitle]);
-
- const commitEdit = useCallback(async () => {
- // A cancelled edit restores, it never writes — even though the blur event
- // hands us the still-edited draft.
- if (cancelEditRef.current) {
- cancelEditRef.current = false;
- return;
- }
- const nextTitle = draft.trim();
- // Empty or unchanged drafts fall back to the saved title — no write.
- if (!nextTitle || nextTitle === savedTitle || !documentId) {
- setDraft(savedTitle);
- setEditing(false);
- return;
- }
-
- // Claim the newest save; only this ticket may settle the client state.
- const ticket = ++saveTicketRef.current;
- setEditing(false);
- setDraft(nextTitle);
-
- // Optimistic update, then reconcile with the server response.
- mutateDocument((prev) => (prev ? { ...prev, title: nextTitle } : prev), { revalidate: false });
-
- // Queue the server write behind any in-flight rename so the server sees
- // the titles in the order the user submitted them — a slow first request
- // can no longer land last and overwrite the newer title.
- const write = saveChain.current
- .catch(() => undefined)
- .then(() =>
- documentService.updateDocument({ id: documentId, title: nextTitle }).then((result) => {
- if (ticket !== saveTicketRef.current) return result;
- // Revalidate the caches other surfaces read titles from
- // (working-sidebar tree, standalone document page read
- // `agent:documentsList`), mirroring the full-page editor's
- // post-rename list refresh.
- void invalidateDocumentMutation({ agentId: agentId ?? undefined, documentId });
- return result;
- }),
- );
- saveChain.current = write;
- try {
- await write;
- } catch {
- if (ticket !== saveTicketRef.current) return;
- toast.error(t('operationFailed', { ns: 'common' }));
- setDraft(savedTitle);
- mutateDocument((prev) => (prev ? { ...prev, title: savedTitle } : prev), {
+ // Optimistic update, then reconcile with the server response.
+ mutateDocument((prev) => (prev ? { ...prev, title: nextTitle } : prev), {
revalidate: false,
});
- }
- }, [agentId, draft, documentId, mutateDocument, savedTitle, t]);
+
+ // Queue the server write behind any in-flight rename so the server sees
+ // the titles in the order the user submitted them — a slow first request
+ // can no longer land last and overwrite the newer title.
+ const write = saveChain.current
+ .catch(() => undefined)
+ .then(() =>
+ documentService.updateDocument({ id: documentId, title: nextTitle }).then((result) => {
+ if (ticket !== saveTicketRef.current) return result;
+ // Revalidate the caches other surfaces read titles from
+ // (working-sidebar tree, standalone document page read
+ // `agent:documentsList`), mirroring the full-page editor's
+ // post-rename list refresh.
+ void invalidateDocumentMutation({ agentId: agentId ?? undefined, documentId });
+ return result;
+ }),
+ );
+ saveChain.current = write;
+ try {
+ await write;
+ } catch (error) {
+ if (ticket !== saveTicketRef.current) return;
+ toast.error(t('operationFailed', { ns: 'common' }));
+ mutateDocument((prev) => (prev ? { ...prev, title: previousTitle } : prev), {
+ revalidate: false,
+ });
+ // Reject so the rename dialog stays open with the typed title for a
+ // retry instead of closing as if the write had landed.
+ throw error;
+ }
+ },
+ [agentId, documentId, metaLocked, mutateDocument, savedTitle, saveChain, t],
+ );
return {
- cancelEdit,
- commitEdit,
- draft,
- editing,
isLoading,
metaLocked,
savedTitle,
- setDraft,
- startEdit,
- syncIdleDraft,
+ saveTitle,
titleFallback: t('agentDocument.portal.titlePlaceholder', { ns: 'chat' }),
};
};