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.

✨ feat(channel): send Channel messages optimistically (#22325)

AmAzing-b9b98ab768d6
diff --git a/locales/en-US/channel.json b/locales/en-US/channel.json
index 13aa64b7565..9b5c8b18e79 100644
--- a/locales/en-US/channel.json
+++ b/locales/en-US/channel.json
@@ -122,6 +122,10 @@
"openAgentNamed": "Open {{name}}",
"openThread": "Open thread",
"otherAgents": "Other Agents",
+ "outgoing.discard": "Delete",
+ "outgoing.failed": "Not sent",
+ "outgoing.retry": "Retry",
+ "outgoing.sending": "Sending…",
"people.empty": "All available workspace members have joined",
"people.noMatches": "No matching workspace members",
"people.noOthers": "No one else is in this workspace yet",
@@ -142,11 +146,8 @@
"renameFailed": "Could not rename the channel. Try again.",
"renameForbidden": "Only the channel owner or an administrator can rename this channel.",
"reply.action": "Reply",
- "reply.agentHint": "Continue in a thread with this Agent and any Agents you @mention.",
"reply.attachment": "Attachment",
"reply.cancel": "Cancel reply",
- "reply.personHint": "Quote only. No Agent will be triggered.",
- "reply.threadHint": "Continue in this thread. Agents you @mention will also join.",
"reply.to": "Replying to {{name}}",
"reply.unavailable": "Original message unavailable",
"reply.viewOriginal": "View original message",
diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.json
index 6054e14ac58..a7c938c927a 100644
--- a/locales/zh-CN/channel.json
+++ b/locales/zh-CN/channel.json
@@ -122,6 +122,10 @@
"openAgentNamed": "打开 {{name}}",
"openThread": "打开线程",
"otherAgents": "其他 Agent",
+ "outgoing.discard": "删除",
+ "outgoing.failed": "未发送",
+ "outgoing.retry": "重试",
+ "outgoing.sending": "发送中…",
"people.empty": "所有可添加的工作区成员均已加入",
"people.noMatches": "没有匹配的工作区成员",
"people.noOthers": "工作区里还没有其他成员",
@@ -142,11 +146,8 @@
"renameFailed": "频道没有改名成功,请重试。",
"renameForbidden": "只有频道所有者或管理员可以重命名频道。",
"reply.action": "回复",
- "reply.agentHint": "发送后在线程中交流,额外 @ 的 Agent 也会加入。",
"reply.attachment": "附件消息",
"reply.cancel": "取消回复",
- "reply.personHint": "仅引用消息,不触发 Agent。",
- "reply.threadHint": "继续在当前线程交流,额外 @ 的 Agent 也会加入。",
"reply.to": "回复 {{name}}",
"reply.unavailable": "原消息已不可用",
"reply.viewOriginal": "查看原消息",
diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.ts
index acf09144c79..7f547afec28 100644
--- a/packages/locales/src/default/channel.ts
+++ b/packages/locales/src/default/channel.ts
@@ -91,6 +91,10 @@ export default {
'actionFailed': 'Something went wrong. Try again.',
'send': 'Send',
'sendFailed': 'Message was not sent. Your draft is preserved; try again.',
+ 'outgoing.discard': 'Delete',
+ 'outgoing.failed': 'Not sent',
+ 'outgoing.retry': 'Retry',
+ 'outgoing.sending': 'Sending…',
'composer': 'Message #{{name}}',
'directComposer': 'Message {{name}}',
'threadComposer': 'Reply in thread',
@@ -200,7 +204,4 @@ export default {
'reply.attachment': 'Attachment',
'reply.viewOriginal': 'View original message',
'reply.unavailable': 'Original message unavailable',
- 'reply.personHint': 'Quote only. No Agent will be triggered.',
- 'reply.agentHint': 'Continue in a thread with this Agent and any Agents you @mention.',
- 'reply.threadHint': 'Continue in this thread. Agents you @mention will also join.',
};
diff --git a/src/features/Channels/ChannelConversation.tsx b/src/features/Channels/ChannelConversation.tsx
index eb690c18419..0a0f61c09bb 100644
--- a/src/features/Channels/ChannelConversation.tsx
+++ b/src/features/Channels/ChannelConversation.tsx
@@ -11,9 +11,10 @@ import { ChannelConversationSkeleton } from '@/components/Skeleton/Channel';
import { delayed } from '@/components/Skeleton/Delayed';
import { createStore, Provider } from '@/features/Conversation/store';
import WideScreenContainer from '@/features/WideScreenContainer';
-import { useActiveLocation } from '@/hooks/useActiveLocation';
import { cacheScope } from '@/libs/replica';
import { channelActions, channelSelectors, useChannelStore } from '@/store/channel';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
import { ArchivedNotice } from './ArchivedNotice';
import { visibleChannelDetail } from './channelAccess';
@@ -21,12 +22,16 @@ import { ChannelMessage, ThreadRootMessage } from './ChannelMessage';
import { Composer } from './Composer';
import { JoinEventLine } from './JoinEventLine';
import { channelJoinEvents, channelTimeline } from './joinEvents';
+import { isCurrentUserMember } from './memberName';
import { channelTimeFormatters, presentChannelTimeline } from './messagePresentation';
+import { presentOutgoingMessage, timelineTail } from './outgoing';
+import { OutgoingStatus } from './OutgoingStatus';
import { ReplyActivity } from './ReplyActivity';
import { styles } from './styles';
import type { ChannelThreadDraft } from './threadDraft';
import { useChannelEvents } from './useChannelEvents';
import { channelDraftKey } from './useComposerDraft';
+import { useFollowSent } from './useFollowSent';
import { type ChannelReplyTarget, useReplyTarget } from './useReplyTarget';
interface ChannelConversationProps {
@@ -51,17 +56,7 @@ const Timeline = ({
const reply = useReplyTarget(channelDraftKey(channelId, threadId));
const [jumpTarget, setJumpTarget] = useState<ChannelReplyTarget | null>(null);
const [highlighted, setHighlighted] = useState<string | null>(null);
- const sending = useRef(false);
- const mounted = useRef(false);
- const location = useActiveLocation();
- const currentLocation = useRef(location);
- currentLocation.current = location;
- useEffect(() => {
- mounted.current = true;
- return () => {
- mounted.current = false;
- };
- }, []);
+ const followSent = useFollowSent(threadId, onOpenThread);
useEffect(() => {
if (!highlighted) return;
const timer = setTimeout(() => setHighlighted(null), 1600);
@@ -71,9 +66,22 @@ const Timeline = ({
const sync = channelActions.useFetchDetail(params);
const cached = useChannelStore(channelSelectors.detail(params));
const detail = visibleChannelDetail(cached, sync.error);
+ const scope = cacheScope.use();
+ useEffect(() => channelActions.restoreOutbox(scope), [scope]);
+ const userId = useUserStore(userProfileSelectors.userId);
+ const queued = useChannelStore(channelSelectors.outgoing(channelId, threadId));
+ // Sent from this tab and not on a loaded page yet; they follow the latest page only.
+ const outgoing = useMemo(() => {
+ if (!detail || before !== undefined) return [];
+ const member = detail.members.find((entry) => isCurrentUserMember(entry, userId));
+ return queued
+ .filter((entry) => entry.scope === scope)
+ .map((entry) => ({ entry, message: presentOutgoingMessage(entry, { member, userId }) }));
+ }, [before, detail, queued, scope, userId]);
+ const outgoingById = new Map(outgoing.map((item) => [item.message.id, item.entry]));
const feedRef = useRef<HTMLDivElement>(null);
const followLatest = useRef(true);
- const lastMessageId = detail?.messages.at(-1)?.id;
+ const feedTail = timelineTail(detail?.messages, outgoing);
const sequence = detail?.channel.sequence;
useChannelEvents(params);
const jumpToMessage = (target: ChannelReplyTarget) => {
@@ -94,7 +102,7 @@ const Timeline = ({
useEffect(() => {
const feed = feedRef.current;
if (feed && followLatest.current && before === undefined) feed.scrollTop = feed.scrollHeight;
- }, [lastMessageId, before]);
+ }, [feedTail, before]);
useEffect(() => {
if (threadId || sequence === undefined || before !== undefined) return;
@@ -105,16 +113,16 @@ const Timeline = ({
const activeMembers = detail?.members.filter((member) => member.status === 'active') ?? [];
const thread = threadId ? detail?.threads.find((entry) => entry.id === threadId) : undefined;
- const selectReply = (message: ChannelPublicMessage) => {
- if (!sending.current) reply.select(message);
- };
+ const selectReply = (message: ChannelPublicMessage) => reply.select(message);
const channelArchived = detail?.channel.status === 'archived';
const direct = !!detail?.channel.agentId;
// Join lines belong to the main conversation; a thread starts from its root message. A direct
// conversation reads like a chat with its Agent, so it has no "invited" lines at all.
const timeline = detail
? channelTimeline(
- detail.messages,
+ outgoing.length
+ ? [...detail.messages, ...outgoing.map((item) => item.message)]
+ : detail.messages,
threadId || direct ? [] : channelJoinEvents(detail.members),
!detail.hasMore && before === undefined,
)
@@ -211,6 +219,23 @@ const Timeline = ({
)}
{item.kind === 'event' ? (
<JoinEventLine event={item.event} />
+ ) : outgoingById.has(item.message.id) ? (
+ <ChannelMessage
+ continuation={continuation}
+ message={item.message}
+ threadId={threadId}
+ delivery={
+ <OutgoingStatus
+ message={outgoingById.get(item.message.id)!}
+ onRetry={(failed) => followSent(channelActions.retrySend(failed))}
+ />
+ }
+ detail={{
+ ...detail,
+ attachments: outgoingById.get(item.message.id)!.attachments,
+ }}
+ onJumpToMessage={jumpToMessage}
+ />
) : (
<ChannelMessage
continuation={continuation}
@@ -240,42 +265,18 @@ const Timeline = ({
key={channelDraftKey(channelId, threadId)}
members={activeMembers}
replyTarget={reply.target}
- threadId={threadId}
placeholder={
threadId
? t('threadComposer')
: t(direct ? 'directComposer' : 'composer', { name: detail.channel.title })
}
onCancelReply={() => reply.clear()}
- onSend={async (content, mentions, requestKey, fileIds, replyToId) => {
- const sentReply = reply.snapshot();
- const sentLocation = currentLocation.current;
- const sentScope = cacheScope.get();
- sending.current = true;
- try {
- followLatest.current = true;
- const message = await channelActions.send({
- channelId,
- content,
- fileIds,
- mentions,
- requestKey,
- replyToId,
- threadId,
- });
- reply.clear(sentReply);
- if (
- mounted.current &&
- sentScope === cacheScope.get() &&
- sentLocation.pathname === currentLocation.current.pathname &&
- sentLocation.search === currentLocation.current.search
- ) {
- setBefore(undefined);
- if (!threadId && message.threadId) onOpenThread?.(message.threadId, false);
- }
- } finally {
- sending.current = false;
- }
+ onQueue={(message) => {
+ // A reply picked while outsiders were being invited stays for the next message.
+ if (reply.snapshot().target?.id === message.replyToId) reply.clear();
+ followLatest.current = true;
+ setBefore(undefined);
+ followSent(channelActions.queueSend({ ...message, channelId, threadId }));
}}
/>
)}
diff --git a/src/features/Channels/ChannelMessage.tsx b/src/features/Channels/ChannelMessage.tsx
index 51dd68fa1fb..dd784621559 100644
--- a/src/features/Channels/ChannelMessage.tsx
+++ b/src/features/Channels/ChannelMessage.tsx
@@ -42,6 +42,7 @@ const MessageText = ({ content, names }: { content: string; names: string[] }) =
};
export const ChannelMessage = ({
+ delivery,
detail,
continuation = false,
message,
@@ -54,6 +55,8 @@ export const ChannelMessage = ({
onJumpToMessage,
}: {
continuation?: boolean;
+ /** For a message the server has not confirmed: its send status, in place of routing. */
+ delivery?: ReactNode;
detail: ChannelDetail;
isRoot?: boolean;
highlighted?: boolean;
@@ -118,7 +121,6 @@ export const ChannelMessage = ({
showTitle
agentId={message.author.type === 'agent' ? message.author.id : undefined}
avatarProps={{ size: 36 }}
- belowMessage={isRequest ? <MessageRoutingStatus message={message} /> : undefined}
gap={4}
id={message.id}
paddingBlock={compact ? 2 : 8}
@@ -141,6 +143,9 @@ export const ChannelMessage = ({
avatar: authorAvatar(message.author),
title: message.author.name || t('deletedMember'),
}}
+ belowMessage={
+ delivery ?? (isRequest ? <MessageRoutingStatus message={message} /> : undefined)
+ }
customAvatarRender={(_, avatar) => (
<Flexbox {...stylex.props(styles.messageAvatar)}>
{isOwnMessage ? <UserAvatar size={36} /> : avatar}
@@ -183,7 +188,7 @@ export const ChannelMessage = ({
titleAddon={
<>
{timestamp}
- {isRequest && <MessageFailureMark detail={detail} message={message} />}
+ {isRequest && !delivery && <MessageFailureMark detail={detail} message={message} />}
</>
}
/>
diff --git a/src/features/Channels/Composer.tsx b/src/features/Channels/Composer.tsx
index 17d3ece1096..48a170aa3cf 100644
--- a/src/features/Channels/Composer.tsx
+++ b/src/features/Channels/Composer.tsx
@@ -26,6 +26,7 @@ import { useEnterToSend } from '@/hooks/useEnterToSend';
import { usePermission } from '@/hooks/usePermission';
import { useSingleton } from '@/hooks/useSingleton';
import { cacheScope } from '@/libs/replica';
+import type { ChannelQueuedSendInput } from '@/store/channel';
import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
@@ -46,6 +47,32 @@ import { useComposerDraft } from './useComposerDraft';
import { useMentionInvites } from './useMentionInvites';
import type { ChannelReplyTarget } from './useReplyTarget';
+export type ChannelComposerMessage = Omit<ChannelQueuedSendInput, 'channelId' | 'threadId'>;
+
+export type ChannelComposerSend = (
+ content: string,
+ mentions: string[],
+ requestKey: string,
+ fileIds?: string[],
+ replyToId?: string,
+) => Promise<void>;
+
+/** Exactly one way to hand a message over. */
+type ComposerDelivery =
+ | {
+ /**
+ * Hands the message over without waiting and clears the input at once; the timeline
+ * shows whether it sent.
+ */
+ onQueue: (message: ChannelComposerMessage) => void;
+ onSend?: never;
+ }
+ | {
+ onQueue?: never;
+ /** Waits for the server, keeping the input until the message is stored. */
+ onSend: ChannelComposerSend;
+ };
+
const plugins = [ReactCodePlugin, ReactListPlugin, ReactLinkHighlightPlugin, ReactMentionPlugin];
/** A flat filled bar, like an IM message box, instead of the chat page's raised card. */
@@ -61,11 +88,11 @@ export function Composer({
channel,
draftKey,
members,
+ onQueue,
onSend,
placeholder,
replyTarget,
onCancelReply,
- threadId,
}: {
/** Who is replying right now; shown on the line above the input. */
activity?: ReactNode;
@@ -77,15 +104,7 @@ export function Composer({
placeholder: string;
replyTarget?: ChannelReplyTarget | null;
onCancelReply?: () => void;
- threadId?: string | null;
- onSend: (
- content: string,
- mentions: string[],
- requestKey: string,
- fileIds?: string[],
- replyToId?: string,
- ) => Promise<void>;
-}) {
+} & ComposerDelivery) {
const { t } = useTranslation('channel');
const workspaceId = useActiveWorkspaceId();
const editor = useEditor();
@@ -120,29 +139,58 @@ export function Composer({
const value = String(editor.getDocument('markdown') || '').trim();
const fileIds = attachments.readyFileIds();
if (sending.current || !fileIds || (!value && !fileIds.length)) return;
+ const document = editor.getDocument('json');
+ const outsiders = channelMentionInvites(document);
sending.current = true;
- setBusy(true);
+ // A queued message leaves the input at once; only inviting someone new waits first.
+ if (!onQueue || outsiders.length) setBusy(true);
setError('');
invites.clearError();
const sentRevision = draft.snapshot();
- const document = editor.getDocument('json');
+ const clearInput = () => {
+ editor.cleanDocument();
+ draft.clear(sentRevision);
+ attachments.clear();
+ setContent('');
+ };
try {
// Mentioned outsiders join first, so the message can address them as members.
- const invited = await invites.resolve(channelMentionInvites(document));
+ const invited = await invites.resolve(outsiders);
if (!invited) return;
const mentions = [...new Set([...channelMentionIds(document, memberIds), ...invited])];
+ if (onQueue) {
+ onQueue({
+ attachments: attachments.items.flatMap((item) =>
+ item.fileId && item.fileUrl
+ ? [
+ {
+ fileType: item.file.type,
+ id: item.fileId,
+ name: item.file.name,
+ size: item.file.size,
+ url: item.fileUrl,
+ },
+ ]
+ : [],
+ ),
+ content: value,
+ fileIds,
+ mentions,
+ replyTo: replyTarget ?? undefined,
+ replyToId: replyTarget?.id,
+ });
+ clearInput();
+ return;
+ }
const requestKey = requests.get(`${cacheScope.get()}:${draftKey}`, {
content: value,
fileIds,
mentions,
replyToId: replyTarget?.id,
});
- await onSend(value, mentions, requestKey, fileIds, replyTarget?.id);
+ await onSend?.(value, mentions, requestKey, fileIds, replyTarget?.id);
requests.complete(requestKey);
- editor.cleanDocument();
- draft.clear(sentRevision);
- attachments.clear();
- setContent('');
+ clearInput();
} catch (cause) {
console.error('Failed to send Channel message', cause);
setError(t('sendFailed'));
@@ -198,15 +246,6 @@ export function Composer({
{' · '}
{replyTarget.content || t('reply.attachment')}
</Text>
- <Text fontSize={12} type="secondary">
- {t(
- replyTarget.author.type === 'user'
- ? 'reply.personHint'
- : threadId
- ? 'reply.threadHint'
- : 'reply.agentHint',
- )}
- </Text>
</Flexbox>
<ActionIcon
aria-label={t('reply.cancel')}
diff --git a/src/features/Channels/DraftThreadConversation.tsx b/src/features/Channels/DraftThreadConversation.tsx
index 5542a72d5f2..c7bdfbccccc 100644
--- a/src/features/Channels/DraftThreadConversation.tsx
+++ b/src/features/Channels/DraftThreadConversation.tsx
@@ -1,7 +1,6 @@
import type { ChannelDetail } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
import * as stylex from '@stylexjs/stylex';
-import type { ComponentProps } from 'react';
import { useTranslation } from 'react-i18next';
import { createStore, Provider } from '@/features/Conversation/store';
@@ -9,7 +8,7 @@ import WideScreenContainer from '@/features/WideScreenContainer';
import { ArchivedNotice } from './ArchivedNotice';
import { ThreadRootMessage } from './ChannelMessage';
-import { Composer } from './Composer';
+import { type ChannelComposerSend, Composer } from './Composer';
import { styles } from './styles';
import type { ChannelThreadDraft } from './threadDraft';
import { channelDraftKey } from './useComposerDraft';
@@ -22,7 +21,7 @@ export function DraftThreadConversation({
}: {
detail: ChannelDetail;
draft: ChannelThreadDraft;
- onSend: ComponentProps<typeof Composer>['onSend'];
+ onSend: ChannelComposerSend;
}) {
const { t } = useTranslation('channel');
return (
diff --git a/src/features/Channels/OutgoingStatus.tsx b/src/features/Channels/OutgoingStatus.tsx
new file mode 100644
index 00000000000..ddcfe6b2957
--- /dev/null
+++ b/src/features/Channels/OutgoingStatus.tsx
@@ -0,0 +1,45 @@
+import { Button, Icon } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+import { CircleAlert, Loader2 } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { channelActions, type ChannelOutgoingMessage } from '@/store/channel';
+
+import { statusStyles, styles, toneStyles } from './styles';
+
+/** Below a message this tab sent: sending, or failed with retry and delete. */
+export function OutgoingStatus({
+ message,
+ onRetry,
+}: {
+ message: ChannelOutgoingMessage;
+ /** Sends the failed message again; the conversation follows where it lands. */
+ onRetry: (message: ChannelOutgoingMessage) => void;
+}) {
+ const { t } = useTranslation('channel');
+ if (message.status === 'sent') return null;
+ if (message.status === 'sending')
+ return (
+ <span
+ role="status"
+ {...stylex.props(statusStyles.receipts, statusStyles.state, styles.muted)}
+ >
+ <Icon spin icon={Loader2} size={12} />
+ {t('outgoing.sending')}
+ </span>
+ );
+ return (
+ <span role="alert" {...stylex.props(statusStyles.receipts, statusStyles.state)}>
+ <span {...stylex.props(statusStyles.state, toneStyles.error)}>
+ <Icon icon={CircleAlert} size={12} />
+ {t('outgoing.failed')}
+ </span>
+ <Button size="small" type="text" onClick={() => onRetry(message)}>
+ {t('outgoing.retry')}
+ </Button>
+ <Button size="small" type="text" onClick={() => channelActions.discardSend(message)}>
+ {t('outgoing.discard')}
+ </Button>
+ </span>
+ );
+}
diff --git a/src/features/Channels/outgoing.test.ts b/src/features/Channels/outgoing.test.ts
new file mode 100644
index 00000000000..449b9266351
--- /dev/null
+++ b/src/features/Channels/outgoing.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+
+import { timelineTail } from './outgoing';
+
+const failed = [{ message: { id: 'outgoing:request' } }];
+
+describe('timelineTail', () => {
+ it('changes when a reply arrives while a failed message stays last', () => {
+ const before = timelineTail([{ id: 'a' }], failed);
+ const after = timelineTail([{ id: 'a' }, { id: 'reply' }], failed);
+
+ expect(after).not.toBe(before);
+ });
+
+ it('changes when this tab queues a message', () => {
+ expect(timelineTail([{ id: 'a' }], failed)).not.toBe(timelineTail([{ id: 'a' }], []));
+ });
+
+ it('stays the same when nothing was added at either end', () => {
+ expect(timelineTail([{ id: 'a' }], failed)).toBe(timelineTail([{ id: 'a' }], failed));
+ expect(timelineTail(undefined, [])).toBe(timelineTail([], []));
+ });
+});
diff --git a/src/features/Channels/outgoing.ts b/src/features/Channels/outgoing.ts
new file mode 100644
index 00000000000..b388af8e553
--- /dev/null
+++ b/src/features/Channels/outgoing.ts
@@ -0,0 +1,49 @@
+import type { ChannelPublicMember, ChannelPublicMessage } from '@lobechat/types';
+
+import type { ChannelOutgoingMessage } from '@/store/channel';
+
+import { memberName } from './memberName';
+
+const OUTGOING_PREFIX = 'outgoing:';
+
+export const outgoingMessageId = (message: Pick<ChannelOutgoingMessage, 'requestKey'>) =>
+ `${OUTGOING_PREFIX}${message.requestKey}`;
+
+/**
+ * A message this tab sent, shaped like a stored one so the timeline groups and renders it the
+ * same way. It is the viewer's own; the server has not routed it yet.
+ */
+export const presentOutgoingMessage = (
+ message: ChannelOutgoingMessage,
+ author: { member?: ChannelPublicMember; userId?: string },
+): ChannelPublicMessage => ({
+ agentId: null,
+ author: {
+ avatar: author.member?.userAvatar ?? null,
+ id: author.userId ?? null,
+ name: memberName(author.member, '') || null,
+ type: 'user',
+ },
+ content: message.content,
+ createdAt: message.createdAt,
+ fileIds: message.fileIds,
+ id: outgoingMessageId(message),
+ mentions: message.mentions,
+ recipientMemberIds: [],
+ replyTo: message.replyTo ?? (message.replyToId ? null : undefined),
+ replyToId: message.replyToId ?? null,
+ routingStatus: 'pending',
+ sequence: message.sent?.sequence ?? Number.MAX_SAFE_INTEGER,
+ threadId: message.threadId,
+ userId: author.userId ?? null,
+});
+
+/**
+ * Changes whenever the feed gains a message at its end, stored or sent from this tab. The two
+ * tails are tracked apart: a failed message stays last until retried or deleted, and replies
+ * arriving above it must still be followed.
+ */
+export const timelineTail = (
+ messages: Pick<ChannelPublicMessage, 'id'>[] | undefined,
+ outgoing: { message: Pick<ChannelPublicMessage, 'id'> }[],
+) => `${messages?.at(-1)?.id ?? ''}|${outgoing.at(-1)?.message.id ?? ''}`;
diff --git a/src/features/Channels/useFollowSent.test.ts b/src/features/Channels/useFollowSent.test.ts
new file mode 100644
index 00000000000..a21fa9ecfaa
--- /dev/null
+++ b/src/features/Channels/useFollowSent.test.ts
@@ -0,0 +1,81 @@
+import { act, renderHook } from '@testing-library/react';
+import { createElement, type ReactNode } from 'react';
+import { MemoryRouter, useNavigate } from 'react-router';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+
+import { useFollowSent } from './useFollowSent';
+
+const wrapper = ({ children }: { children: ReactNode }) =>
+ createElement(MemoryRouter, { initialEntries: ['/channels/chn_1'] }, children);
+
+const render = (threadId: string | null, onOpenThread = vi.fn()) => {
+ const hook = renderHook(
+ () => ({ follow: useFollowSent(threadId, onOpenThread), navigate: useNavigate() }),
+ { wrapper },
+ );
+ return { ...hook, onOpenThread };
+};
+
+describe('useFollowSent', () => {
+ let scope: string;
+ beforeEach(() => {
+ scope = 'scope';
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ });
+ afterEach(() => vi.restoreAllMocks());
+
+ it('opens the thread a main-conversation reply landed in, including after a retry', async () => {
+ const { result, onOpenThread } = render(null);
+
+ await act(async () => result.current.follow(Promise.resolve({ threadId: 'thread' })));
+
+ expect(onOpenThread).toHaveBeenCalledWith('thread', false);
+ });
+
+ it.each([
+ ['stays in the main conversation', null, { threadId: null }],
+ ['did not send', null, undefined],
+ ['was sent inside a thread already', 'thread', { threadId: 'thread' }],
+ ])('does nothing when the message %s', async (_, threadId, stored) => {
+ const { result, onOpenThread } = render(threadId);
+
+ await act(async () => result.current.follow(Promise.resolve(stored)));
+
+ expect(onOpenThread).not.toHaveBeenCalled();
+ });
+
+ it('does not pull the user back after they left the conversation', async () => {
+ const { result, onOpenThread } = render(null);
+ const gate = Promise.withResolvers<{ threadId: string }>();
+ act(() => result.current.follow(gate.promise));
+
+ act(() => result.current.navigate('/channels/chn_2'));
+ await act(async () => gate.resolve({ threadId: 'thread' }));
+
+ expect(onOpenThread).not.toHaveBeenCalled();
+ });
+
+ it('does not open a thread under an identity that replaced the sender', async () => {
+ const { result, onOpenThread } = render(null);
+ const gate = Promise.withResolvers<{ threadId: string }>();
+ act(() => result.current.follow(gate.promise));
+
+ scope = 'other';
+ await act(async () => gate.resolve({ threadId: 'thread' }));
+
+ expect(onOpenThread).not.toHaveBeenCalled();
+ });
+
+ it('does nothing once the conversation unmounted', async () => {
+ const { result, onOpenThread, unmount } = render(null);
+ const gate = Promise.withResolvers<{ threadId: string }>();
+ act(() => result.current.follow(gate.promise));
+
+ unmount();
+ await act(async () => gate.resolve({ threadId: 'thread' }));
+
+ expect(onOpenThread).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Channels/useFollowSent.ts b/src/features/Channels/useFollowSent.ts
new file mode 100644
index 00000000000..bed7e59209f
--- /dev/null
+++ b/src/features/Channels/useFollowSent.ts
@@ -0,0 +1,42 @@
+import type { ChannelPublicMessage } from '@lobechat/types';
+import { useLatest } from 'ahooks';
+import { useEffect, useRef } from 'react';
+
+import { useActiveLocation } from '@/hooks/useActiveLocation';
+import { cacheScope } from '@/libs/replica';
+
+/**
+ * A reply to an Agent sent from the main conversation is stored in a thread and leaves this
+ * feed, whether it sent at once or on retry. Opens that thread unless the user has moved on:
+ * left the conversation, switched identity, or the view unmounted.
+ */
+export const useFollowSent = (
+ threadId: string | null,
+ onOpenThread?: (threadId: string, toggle?: boolean) => void,
+) => {
+ const mounted = useRef(false);
+ const location = useLatest(useActiveLocation());
+ const openThread = useLatest(onOpenThread);
+ useEffect(() => {
+ mounted.current = true;
+ return () => {
+ mounted.current = false;
+ };
+ }, []);
+
+ return (send: Promise<Pick<ChannelPublicMessage, 'threadId'> | undefined>) => {
+ const sentLocation = location.current;
+ const sentScope = cacheScope.get();
+ void send.then((stored) => {
+ if (
+ stored?.threadId &&
+ !threadId &&
+ mounted.current &&
+ sentScope === cacheScope.get() &&
+ sentLocation.pathname === location.current.pathname &&
+ sentLocation.search === location.current.search
+ )
+ openThread.current?.(stored.threadId, false);
+ });
+ };
+};
diff --git a/src/store/channel/action.queueSend.test.ts b/src/store/channel/action.queueSend.test.ts
new file mode 100644
index 00000000000..c806d4983cc
--- /dev/null
+++ b/src/store/channel/action.queueSend.test.ts
@@ -0,0 +1,172 @@
+import type { ChannelDetail, ChannelPublicMessage } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { channelService } from '@/services/channel';
+
+import { channelActions } from './action';
+import { channelOutboxKey } from './outbox';
+import { channelOutboxStorage } from './outboxStorage';
+import { useChannelStore } from './store';
+
+vi.mock('@/services/channel', () => ({
+ channelService: { detail: vi.fn(), list: vi.fn(), send: vi.fn() },
+}));
+
+const input = {
+ attachments: [],
+ channelId: 'channel',
+ content: 'Hello',
+ fileIds: [],
+ mentions: [],
+};
+const key = channelOutboxKey('channel');
+const stored = (id: string, sequence: number) =>
+ ({ id, sequence, threadId: null }) as ChannelPublicMessage;
+const detail = (messages: ChannelPublicMessage[]) =>
+ ({
+ attachments: [],
+ channel: { createdAt: new Date(), id: 'channel', sequence: 1, title: 'Channel' },
+ hasMore: false,
+ jobs: [],
+ members: [],
+ messages,
+ rootMessage: null,
+ threads: [],
+ }) as unknown as ChannelDetail;
+const outgoing = () => useChannelStore.getState().outbox[key] ?? [];
+type SendResult = Awaited<ReturnType<typeof channelService.send>>;
+const result = (message: ChannelPublicMessage) => ({ data: message, success: true }) as SendResult;
+
+describe('Channel queued send', () => {
+ let scope: string;
+ beforeEach(() => {
+ scope = crypto.randomUUID();
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(false);
+ vi.mocked(channelService.list).mockResolvedValue([]);
+ vi.mocked(channelService.detail).mockResolvedValue(detail([]));
+ channelActions.reset();
+ });
+ afterEach(() => {
+ localStorage.clear();
+ channelActions.reset();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('shows the message as sending before the server answers', async () => {
+ const gate = Promise.withResolvers<SendResult>();
+ vi.mocked(channelService.send).mockReturnValue(gate.promise);
+ const pending = channelActions.queueSend(input);
+ expect(outgoing()).toMatchObject([{ content: 'Hello', status: 'sending', threadId: null }]);
+ gate.resolve(result(stored('message', 2)));
+ await pending;
+ });
+
+ it('settles the message once the refreshed conversation holds it', async () => {
+ vi.mocked(channelService.send).mockResolvedValue(result(stored('message', 2)));
+ vi.mocked(channelService.detail).mockResolvedValue(detail([stored('message', 2)]));
+ expect(await channelActions.queueSend(input)).toMatchObject({ id: 'message' });
+ await vi.waitFor(() => expect(outgoing()).toEqual([]));
+ });
+
+ it('keeps a failed message to retry under the same request key', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.mocked(channelService.send).mockRejectedValueOnce(new Error('offline'));
+ expect(await channelActions.queueSend(input)).toBeUndefined();
+ const [failed] = outgoing();
+ expect(failed).toMatchObject({ content: 'Hello', status: 'failed' });
+
+ vi.mocked(channelService.send).mockResolvedValueOnce(result(stored('message', 2)));
+ expect(await channelActions.retrySend(failed)).toMatchObject({ id: 'message' });
+ const requestKeys = vi.mocked(channelService.send).mock.calls.map(([call]) => call.requestKey);
+ expect(requestKeys).toEqual([failed.requestKey, failed.requestKey]);
+ });
+
+ it('does not send a failed message after it is deleted', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.mocked(channelService.send).mockRejectedValueOnce(new Error('offline'));
+ await channelActions.queueSend(input);
+ const [failed] = outgoing();
+ channelActions.discardSend(failed);
+ expect(outgoing()).toEqual([]);
+ expect(await channelActions.retrySend(failed)).toBeUndefined();
+ expect(channelService.send).toHaveBeenCalledTimes(1);
+ });
+
+ it('sends one conversation in order, each message after the previous answer', async () => {
+ const first = Promise.withResolvers<SendResult>();
+ vi.mocked(channelService.send)
+ .mockReturnValueOnce(first.promise)
+ .mockResolvedValueOnce(result(stored('second', 3)));
+ const sends = [
+ channelActions.queueSend(input),
+ channelActions.queueSend({ ...input, content: 'World' }),
+ ];
+ await Promise.resolve();
+ expect(channelService.send).toHaveBeenCalledTimes(1);
+ expect(outgoing().map((message) => message.content)).toEqual(['Hello', 'World']);
+ first.resolve(result(stored('first', 2)));
+ await Promise.all(sends);
+ const contents = vi.mocked(channelService.send).mock.calls.map(([call]) => call.content);
+ expect(contents).toEqual(['Hello', 'World']);
+ });
+
+ it('does not send a queued message under an identity that replaced its own', async () => {
+ const first = Promise.withResolvers<SendResult>();
+ vi.mocked(channelService.send).mockReturnValueOnce(first.promise);
+ const sends = [channelActions.queueSend(input), channelActions.queueSend(input)];
+ await Promise.resolve();
+ expect(channelService.send).toHaveBeenCalledTimes(1);
+ scope = crypto.randomUUID();
+ first.resolve(result(stored('first', 2)));
+ await Promise.all(sends);
+ expect(channelService.send).toHaveBeenCalledTimes(1);
+ expect(channelService.detail).not.toHaveBeenCalled();
+ expect(outgoing().map((message) => message.status)).toEqual(['sent', 'failed']);
+ });
+
+ it('keeps an unsent message across a reload until the server confirms it', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.mocked(channelService.send).mockRejectedValueOnce(new Error('offline'));
+ await channelActions.queueSend(input);
+ const [failed] = outgoing();
+
+ // A reload empties memory; the conversation reads the message back.
+ channelActions.reset();
+ expect(outgoing()).toEqual([]);
+ channelActions.restoreOutbox(scope);
+ expect(outgoing()).toMatchObject([
+ { content: 'Hello', requestKey: failed.requestKey, status: 'failed' },
+ ]);
+
+ vi.mocked(channelService.send).mockResolvedValueOnce(result(stored('message', 2)));
+ await channelActions.retrySend(outgoing()[0]);
+ expect(channelOutboxStorage.load(scope)).toEqual([]);
+ });
+
+ it('forgets a deleted message and restores a scope only once', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.mocked(channelService.send).mockRejectedValueOnce(new Error('offline'));
+ await channelActions.queueSend(input);
+ channelActions.restoreOutbox(scope);
+ expect(outgoing()).toHaveLength(1);
+
+ channelActions.discardSend(outgoing()[0]);
+
+ expect(channelOutboxStorage.load(scope)).toEqual([]);
+ });
+
+ it('marks a message whose send was interrupted by a reload as failed', () => {
+ const gate = Promise.withResolvers<SendResult>();
+ vi.mocked(channelService.send).mockReturnValue(gate.promise);
+ void channelActions.queueSend(input);
+
+ channelActions.reset();
+ channelActions.restoreOutbox(scope);
+
+ expect(outgoing()).toMatchObject([{ content: 'Hello', status: 'failed' }]);
+ });
+});
diff --git a/src/store/channel/action.ts b/src/store/channel/action.ts
index ad3a2ad2009..290f7f0e7a4 100644
--- a/src/store/channel/action.ts
+++ b/src/store/channel/action.ts
@@ -11,6 +11,16 @@ import {
} from '@/services/channel';
import { getElectronStoreState } from '@/store/electron';
+import {
+ addOutgoing,
+ type ChannelOutbox,
+ channelOutboxKey,
+ type ChannelOutgoingMessage,
+ findOutgoing,
+ patchOutgoing,
+ removeOutgoing,
+} from './outbox';
+import { channelOutboxStorage } from './outboxStorage';
import { ChannelPrivateAction } from './privateAction';
import { channelThreadEntityId } from './projection';
import { channelSelectors } from './selectors';
@@ -23,6 +33,14 @@ import { initialState, useChannelStore } from './store';
export const CHANNEL_ACTIVE_REFRESH_MS = 3000;
export const CHANNEL_IDLE_REFRESH_MS = 60_000;
+type ChannelSendInput = Parameters<typeof channelService.send>[0];
+
+/** What the composer hands over; the outbox adds the request key, time and status. */
+export type ChannelQueuedSendInput = Pick<
+ ChannelOutgoingMessage,
+ 'attachments' | 'channelId' | 'content' | 'fileIds' | 'mentions' | 'replyTo' | 'replyToId'
+> & { threadId?: string | null };
+
class ChannelActionImpl {
readonly #private = new ChannelPrivateAction(useChannelStore.setState, useChannelStore.getState);
useFetchUserCandidates = (channelId: string | undefined, search: string) =>
@@ -210,27 +228,131 @@ class ChannelActionImpl {
await this.#refreshAfterWrite(() => this.refreshDetail({ channelId }));
return data.id;
};
- send = async (input: Parameters<typeof channelService.send>[0]) => {
+ /** Waits for the server and the views it changed; the first message of a new thread uses it. */
+ send = async (input: ChannelSendInput) => {
const scope = cacheScope.get();
const { data } = await channelService.send(input);
- if (cacheScope.get() !== scope) return data;
- await this.#refreshAfterWrite(() =>
+ if (cacheScope.get() === scope) await this.#refreshAfterSend(input, data.threadId);
+ return data;
+ };
+ /**
+ * Sends without waiting: the message shows in its conversation at once, marked sending, and a
+ * failure keeps it there to retry. One conversation's messages reach the server in order.
+ * Resolves the stored message, or `undefined` when it did not send.
+ */
+ queueSend = (input: ChannelQueuedSendInput) => {
+ const message: ChannelOutgoingMessage = {
+ ...input,
+ createdAt: new Date(),
+ requestKey: crypto.randomUUID(),
+ scope: cacheScope.get(),
+ status: 'sending',
+ threadId: input.threadId ?? null,
+ };
+ this.#setOutbox((outbox) => addOutgoing(outbox, message), 'add');
+ channelOutboxStorage.save(message);
+ return this.#deliver(message);
+ };
+ /** Sends a failed message again under the same request key, so it is stored at most once. */
+ retrySend = (message: ChannelOutgoingMessage) => {
+ if (findOutgoing(useChannelStore.getState().outbox, message)?.status !== 'failed')
+ return Promise.resolve(undefined);
+ this.#setOutbox((outbox) => patchOutgoing(outbox, message, { status: 'sending' }), 'retry');
+ return this.#deliver(message);
+ };
+ discardSend = (message: ChannelOutgoingMessage) => {
+ this.#setOutbox((outbox) => removeOutgoing(outbox, message), 'discard');
+ channelOutboxStorage.forget(message);
+ };
+ /** Scopes whose unsent messages were read back after a reload; once per scope and session. */
+ readonly #restoredScopes = new Set<string>();
+ /** Brings back the scope's unsent messages from an earlier page load, marked failed. */
+ restoreOutbox = (scope: string) => {
+ if (this.#restoredScopes.has(scope)) return;
+ this.#restoredScopes.add(scope);
+ const stored = channelOutboxStorage.load(scope);
+ if (!stored.length) return;
+ this.#setOutbox(
+ (outbox) =>
+ stored.reduce(
+ (next, message) => (findOutgoing(next, message) ? next : addOutgoing(next, message)),
+ outbox,
+ ),
+ 'restore',
+ );
+ };
+ #setOutbox = (fn: (outbox: ChannelOutbox) => ChannelOutbox, action: string) =>
+ useChannelStore.setState(
+ (state) => ({ outbox: fn(state.outbox) }),
+ false,
+ `channel/outbox/${action}`,
+ );
+ /** The tail of each conversation's sends; a message waits for the ones queued before it. */
+ readonly #deliveries = new Map<string, Promise<unknown>>();
+ #deliver = (message: ChannelOutgoingMessage) => {
+ const key = channelOutboxKey(message.channelId, message.threadId);
+ const result = (this.#deliveries.get(key) ?? Promise.resolve()).then(() => this.#post(message));
+ this.#deliveries.set(key, result);
+ void result.then(() => {
+ if (this.#deliveries.get(key) === result) this.#deliveries.delete(key);
+ });
+ return result;
+ };
+ #post = async (queued: ChannelOutgoingMessage) => {
+ // It may have been discarded, or the identity switched, while it waited for its turn.
+ const message = findOutgoing(useChannelStore.getState().outbox, queued);
+ if (message?.status !== 'sending') return;
+ // Never under another identity; it stays in its own scope to retry after switching back.
+ if (message.scope !== cacheScope.get()) {
+ this.#setOutbox((outbox) => patchOutgoing(outbox, message, { status: 'failed' }), 'failed');
+ return;
+ }
+ const input = {
+ channelId: message.channelId,
+ content: message.content,
+ fileIds: message.fileIds,
+ mentions: message.mentions,
+ replyToId: message.replyToId,
+ requestKey: message.requestKey,
+ threadId: message.threadId,
+ };
+ try {
+ const { data } = await channelService.send(input);
+ // Shown as sent until a refreshed page of its conversation holds it.
+ this.#setOutbox(
+ (outbox) =>
+ patchOutgoing(outbox, message, {
+ sent: { id: data.id, sequence: data.sequence, threadId: data.threadId },
+ status: 'sent',
+ }),
+ 'sent',
+ );
+ channelOutboxStorage.forget(message);
+ if (cacheScope.get() === message.scope) void this.#refreshAfterSend(input, data.threadId);
+ return data;
+ } catch (error) {
+ console.error('Failed to send Channel message', error);
+ this.#setOutbox((outbox) => patchOutgoing(outbox, message, { status: 'failed' }), 'failed');
+ }
+ };
+ #refreshAfterSend = (input: ChannelSendInput, threadId: string | null) =>
+ this.#refreshAfterWrite(() =>
Promise.all([
- this.refreshDetail({ channelId: input.channelId, threadId: data.threadId }),
- ...(input.rootMessageId || (input.replyToId && data.threadId)
+ this.refreshDetail({ channelId: input.channelId, threadId }),
+ ...(input.rootMessageId || (input.replyToId && threadId)
? [this.refreshDetail({ channelId: input.channelId })]
: []),
this.refreshList(),
]),
);
- return data;
- };
stop = async (channelId: string, scope: Parameters<typeof channelService.stop>[1]) => {
await channelService.stop(channelId, scope);
await this.refreshDetail({ channelId, threadId: 'threadId' in scope ? scope.threadId : null });
};
reset = () => {
this.#private.resetThreadRemovals();
+ this.#deliveries.clear();
+ this.#restoredScopes.clear();
useChannelStore.setState(initialState, false, 'channel/reset');
};
}
diff --git a/src/store/channel/index.ts b/src/store/channel/index.ts
index dd7d57da6b5..b8d12564031 100644
--- a/src/store/channel/index.ts
+++ b/src/store/channel/index.ts
@@ -1,3 +1,4 @@
-export { channelActions } from './action';
+export { channelActions, type ChannelQueuedSendInput } from './action';
+export type { ChannelOutgoingMessage } from './outbox';
export { channelSelectors } from './selectors';
export { useChannelStore } from './store';
diff --git a/src/store/channel/outbox.test.ts b/src/store/channel/outbox.test.ts
new file mode 100644
index 00000000000..76e726e5000
--- /dev/null
+++ b/src/store/channel/outbox.test.ts
@@ -0,0 +1,58 @@
+import type { ChannelDetail, ChannelPublicMessage } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { addOutgoing, channelOutboxKey, type ChannelOutgoingMessage, settleOutbox } from './outbox';
+
+const outgoing = (patch: Partial<ChannelOutgoingMessage> = {}): ChannelOutgoingMessage => ({
+ attachments: [],
+ channelId: 'channel',
+ content: 'Hello',
+ createdAt: new Date(),
+ fileIds: [],
+ mentions: [],
+ requestKey: 'request',
+ scope: 'scope',
+ status: 'sent',
+ threadId: null,
+ ...patch,
+});
+const stored = (id: string, sequence: number) => ({ id, sequence }) as ChannelPublicMessage;
+const page = (messages: ChannelPublicMessage[]) => ({ messages }) as ChannelDetail;
+const main = { channelId: 'channel' };
+const key = channelOutboxKey('channel');
+
+describe('settleOutbox', () => {
+ const sent = outgoing({ sent: { id: 'message', sequence: 5, threadId: null } });
+
+ it('drops a sent message once the latest page holds it', () => {
+ const outbox = addOutgoing({}, sent);
+ expect(settleOutbox(outbox, main, page([stored('message', 5)]), 'scope')).toEqual({});
+ });
+
+ it('drops a sent message when the page already holds a later message', () => {
+ const outbox = addOutgoing({}, sent);
+ expect(settleOutbox(outbox, main, page([stored('later', 6)]), 'scope')).toEqual({});
+ });
+
+ it('keeps a sent message that a page read before the write does not hold', () => {
+ const outbox = addOutgoing({}, sent);
+ expect(settleOutbox(outbox, main, page([stored('earlier', 4)]), 'scope')).toBe(outbox);
+ });
+
+ it('drops a reply the server moved into a thread from the main conversation', () => {
+ const moved = outgoing({ sent: { id: 'message', sequence: 5, threadId: 'thread' } });
+ expect(settleOutbox(addOutgoing({}, moved), main, page([]), 'scope')).toEqual({});
+ });
+
+ it('keeps messages still sending or failed, older pages and other scopes', () => {
+ const outbox = [
+ outgoing({ requestKey: 'sending', status: 'sending' }),
+ outgoing({ requestKey: 'failed', status: 'failed' }),
+ { ...sent, requestKey: 'other-scope', scope: 'other' },
+ ].reduce(addOutgoing, {});
+ const later = page([stored('later', 9)]);
+ expect(settleOutbox(outbox, main, later, 'scope')[key]).toHaveLength(3);
+ const settledSent = addOutgoing({}, sent);
+ expect(settleOutbox(settledSent, { ...main, before: 10 }, later, 'scope')).toBe(settledSent);
+ });
+});
diff --git a/src/store/channel/outbox.ts b/src/store/channel/outbox.ts
new file mode 100644
index 00000000000..8511ec7d477
--- /dev/null
+++ b/src/store/channel/outbox.ts
@@ -0,0 +1,103 @@
+import type { ChannelDetail, ChannelPublicMessage } from '@lobechat/types';
+
+import type { ChannelViewParams } from '@/services/channel';
+
+/** `sent` waits until a loaded page of its conversation holds the stored message. */
+export type ChannelOutgoingStatus = 'failed' | 'sending' | 'sent';
+
+/** A message this tab sent before the conversation it belongs to holds it. Never persisted. */
+export interface ChannelOutgoingMessage {
+ /** Uploaded files, kept so the message shows them before the conversation lists them. */
+ attachments: ChannelDetail['attachments'];
+ channelId: string;
+ content: string;
+ createdAt: Date;
+ fileIds: string[];
+ mentions: string[];
+ replyTo?: ChannelPublicMessage['replyTo'];
+ replyToId?: string;
+ /** Also its client id: a retry reuses it, so the server stores the message once. */
+ requestKey: string;
+ scope: string;
+ /** Where the server stored it; a reply to an Agent can move into a thread. */
+ sent?: Pick<ChannelPublicMessage, 'id' | 'sequence' | 'threadId'>;
+ status: ChannelOutgoingStatus;
+ threadId: string | null;
+}
+
+export type ChannelOutbox = Record<string, ChannelOutgoingMessage[]>;
+
+export const channelOutboxKey = (channelId: string, threadId?: string | null) =>
+ `${channelId}:${threadId ?? 'main'}`;
+
+const outboxKeyOf = (message: Pick<ChannelOutgoingMessage, 'channelId' | 'threadId'>) =>
+ channelOutboxKey(message.channelId, message.threadId);
+
+const withEntries = (outbox: ChannelOutbox, key: string, entries: ChannelOutgoingMessage[]) => {
+ const { [key]: _, ...rest } = outbox;
+ return entries.length ? { ...rest, [key]: entries } : rest;
+};
+
+export const findOutgoing = (outbox: ChannelOutbox, message: ChannelOutgoingMessage) =>
+ outbox[outboxKeyOf(message)]?.find((entry) => entry.requestKey === message.requestKey);
+
+export const addOutgoing = (outbox: ChannelOutbox, message: ChannelOutgoingMessage) => {
+ const key = outboxKeyOf(message);
+ return withEntries(outbox, key, [...(outbox[key] ?? []), message]);
+};
+
+export const patchOutgoing = (
+ outbox: ChannelOutbox,
+ message: ChannelOutgoingMessage,
+ patch: Partial<Pick<ChannelOutgoingMessage, 'sent' | 'status'>>,
+) => {
+ const key = outboxKeyOf(message);
+ const entries = outbox[key];
+ if (!entries?.some((entry) => entry.requestKey === message.requestKey)) return outbox;
+ return withEntries(
+ outbox,
+ key,
+ entries.map((entry) =>
+ entry.requestKey === message.requestKey ? { ...entry, ...patch } : entry,
+ ),
+ );
+};
+
+export const removeOutgoing = (outbox: ChannelOutbox, message: ChannelOutgoingMessage) => {
+ const key = outboxKeyOf(message);
+ const entries = outbox[key];
+ if (!entries) return outbox;
+ return withEntries(
+ outbox,
+ key,
+ entries.filter((entry) => entry.requestKey !== message.requestKey),
+ );
+};
+
+/**
+ * Drops the sent messages that a newly loaded latest page accounts for: the page holds the
+ * stored message or a later one, or the server moved it into another conversation. A page
+ * read before the write landed holds neither, so the message stays until a later read.
+ * Only confirmed sends settle: a send stored on the server whose response was lost stays
+ * failed beside the stored copy, and its retry returns that copy under the same request key.
+ */
+export const settleOutbox = (
+ outbox: ChannelOutbox,
+ params: ChannelViewParams,
+ data: ChannelDetail,
+ scope: string,
+) => {
+ if (params.before !== undefined) return outbox;
+ const key = channelOutboxKey(params.channelId, params.threadId);
+ const entries = outbox[key];
+ if (!entries) return outbox;
+ const threadId = params.threadId ?? null;
+ const remaining = entries.filter(
+ ({ scope: entryScope, sent }) =>
+ !sent ||
+ entryScope !== scope ||
+ (sent.threadId === threadId &&
+ !data.messages.some((item) => item.id === sent.id || item.sequence > sent.sequence)),
+ );
+ return remaining.length === entries.length ? outbox : withEntries(outbox, key, remaining);
+};
diff --git a/src/store/channel/outboxStorage.test.ts b/src/store/channel/outboxStorage.test.ts
new file mode 100644
index 00000000000..df5c826e4bf
--- /dev/null
+++ b/src/store/channel/outboxStorage.test.ts
@@ -0,0 +1,60 @@
+import { afterEach, describe, expect, it } from 'vitest';
+
+import type { ChannelOutgoingMessage } from './outbox';
+import { CHANNEL_OUTBOX_STORAGE_KEY, channelOutboxStorage } from './outboxStorage';
+
+const message = (patch: Partial<ChannelOutgoingMessage> = {}): ChannelOutgoingMessage => ({
+ attachments: [],
+ channelId: 'channel',
+ content: 'Hello',
+ createdAt: new Date('2026-11-05T10:00:00Z'),
+ fileIds: [],
+ mentions: [],
+ requestKey: 'request',
+ scope: 'scope',
+ status: 'sending',
+ threadId: null,
+ ...patch,
+});
+
+describe('channelOutboxStorage', () => {
+ afterEach(() => localStorage.clear());
+
+ it('brings an interrupted send back as failed, keeping its request key', () => {
+ channelOutboxStorage.save(message());
+
+ expect(channelOutboxStorage.load('scope')).toEqual([{ ...message(), status: 'failed' }]);
+ });
+
+ it('reads only the requested identity scope, oldest first', () => {
+ channelOutboxStorage.save(
+ message({ createdAt: new Date('2026-11-05T10:02:00Z'), requestKey: 'later' }),
+ );
+ channelOutboxStorage.save(message({ requestKey: 'other', scope: 'other' }));
+ channelOutboxStorage.save(message({ requestKey: 'earlier' }));
+
+ expect(channelOutboxStorage.load('scope').map((entry) => entry.requestKey)).toEqual([
+ 'earlier',
+ 'later',
+ ]);
+ });
+
+ it('forgets a confirmed or deleted message and keeps one copy per request key', () => {
+ channelOutboxStorage.save(message());
+ channelOutboxStorage.save(message({ status: 'failed' }));
+ expect(channelOutboxStorage.load('scope')).toHaveLength(1);
+
+ channelOutboxStorage.forget(message());
+
+ expect(channelOutboxStorage.load('scope')).toEqual([]);
+ expect(localStorage.getItem(CHANNEL_OUTBOX_STORAGE_KEY)).toBeNull();
+ });
+
+ it('ignores a corrupt or foreign value', () => {
+ localStorage.setItem(CHANNEL_OUTBOX_STORAGE_KEY, '{not json');
+ expect(channelOutboxStorage.load('scope')).toEqual([]);
+
+ localStorage.setItem(CHANNEL_OUTBOX_STORAGE_KEY, JSON.stringify([{ scope: 'scope' }]));
+ expect(channelOutboxStorage.load('scope')).toEqual([]);
+ });
+});
diff --git a/src/store/channel/outboxStorage.ts b/src/store/channel/outboxStorage.ts
new file mode 100644
index 00000000000..f0ade7bf6ce
--- /dev/null
+++ b/src/store/channel/outboxStorage.ts
@@ -0,0 +1,86 @@
+import type { ChannelOutgoingMessage } from './outbox';
+
+export const CHANNEL_OUTBOX_STORAGE_KEY = 'lobehub:channel-outbox:v1';
+
+const MAX_MESSAGES = 100;
+
+/** What survives a reload: the message itself, not where its last send attempt got to. */
+type StoredMessage = Omit<ChannelOutgoingMessage, 'createdAt' | 'sent' | 'status'> & {
+ createdAt: string;
+};
+
+const isStringArray = (value: unknown): value is string[] =>
+ Array.isArray(value) && value.every((item) => typeof item === 'string');
+
+const isStoredMessage = (value: unknown): value is StoredMessage => {
+ if (!value || typeof value !== 'object') return false;
+ const message = value as StoredMessage;
+ return (
+ typeof message.requestKey === 'string' &&
+ typeof message.scope === 'string' &&
+ typeof message.channelId === 'string' &&
+ typeof message.content === 'string' &&
+ typeof message.createdAt === 'string' &&
+ (message.threadId === null || typeof message.threadId === 'string') &&
+ isStringArray(message.fileIds) &&
+ isStringArray(message.mentions) &&
+ Array.isArray(message.attachments)
+ );
+};
+
+const read = (): StoredMessage[] => {
+ if (typeof window === 'undefined') return [];
+ try {
+ const parsed: unknown = JSON.parse(
+ window.localStorage.getItem(CHANNEL_OUTBOX_STORAGE_KEY) || '[]',
+ );
+ return Array.isArray(parsed) ? parsed.filter(isStoredMessage) : [];
+ } catch {
+ return [];
+ }
+};
+
+const write = (messages: StoredMessage[]) => {
+ if (typeof window === 'undefined') return;
+ try {
+ if (messages.length)
+ window.localStorage.setItem(
+ CHANNEL_OUTBOX_STORAGE_KEY,
+ JSON.stringify(messages.slice(-MAX_MESSAGES)),
+ );
+ else window.localStorage.removeItem(CHANNEL_OUTBOX_STORAGE_KEY);
+ } catch {
+ // A blocked or full store keeps the message for this session only.
+ }
+};
+
+/**
+ * Keeps messages that have not reached the server across reloads, like a composer draft
+ * would have. Shared by the tabs of a browser; each identity scope reads only its own.
+ */
+export const channelOutboxStorage = {
+ /** Removes a message the server confirmed, or one the user deleted. */
+ forget: (message: Pick<ChannelOutgoingMessage, 'requestKey'>) => {
+ const messages = read();
+ const remaining = messages.filter((entry) => entry.requestKey !== message.requestKey);
+ if (remaining.length !== messages.length) write(remaining);
+ },
+ /**
+ * The scope's unsent messages, oldest first. Whether an interrupted send reached the server
+ * is unknown, so every one comes back failed; a retry reuses its request key.
+ */
+ load: (scope: string): ChannelOutgoingMessage[] =>
+ read()
+ .filter((entry) => entry.scope === scope)
+ .map((entry) => ({
+ ...entry,
+ createdAt: new Date(entry.createdAt),
+ status: 'failed' as const,
+ }))
+ .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime()),
+ save: ({ createdAt, sent: _, status: __, ...message }: ChannelOutgoingMessage) =>
+ write([
+ ...read().filter((entry) => entry.requestKey !== message.requestKey),
+ { ...message, createdAt: createdAt.toISOString() },
+ ]),
+};
diff --git a/src/store/channel/privateAction.ts b/src/store/channel/privateAction.ts
index 2dc42e54018..3280f62c2b6 100644
--- a/src/store/channel/privateAction.ts
+++ b/src/store/channel/privateAction.ts
@@ -10,6 +10,7 @@ import {
import type { StoreSetter } from '@/store/types';
import { isTrpcErrorCode } from '@/utils/trpcError';
+import { settleOutbox } from './outbox';
import {
channelDetailEntity,
channelDetailResource,
@@ -50,6 +51,11 @@ export class ChannelPrivateAction {
this.detail = createReplicaSlice(channelDetailResource, {
actionPrefix: 'channel/detail',
effects: {
+ onApplied: (data, params, { scope }) => {
+ const { outbox } = get();
+ const next = settleOutbox(outbox, params, data, scope);
+ if (next !== outbox) set({ outbox: next }, false, 'channel/outbox/settle');
+ },
onError: (error, params, { scope }) => {
if (params.threadId && isTrpcErrorCode(error, 'NOT_FOUND')) {
this.removeThread(params.channelId, params.threadId, scope);
diff --git a/src/store/channel/selectors.ts b/src/store/channel/selectors.ts
index 90faa4fb1b5..11442f08d61 100644
--- a/src/store/channel/selectors.ts
+++ b/src/store/channel/selectors.ts
@@ -2,9 +2,12 @@ import type { ChannelJobBlockCode } from '@lobechat/types';
import type { ChannelViewParams } from '@/services/channel';
+import { channelOutboxKey, type ChannelOutgoingMessage } from './outbox';
import { channelViewKey } from './projection';
import type { ChannelState } from './store';
+const NO_OUTGOING: ChannelOutgoingMessage[] = [];
+
/** These wait for a device or a person rather than for earlier work to finish. */
const EXTERNAL_BLOCKS = new Set<ChannelJobBlockCode>([
'device_approval_pending',
@@ -41,4 +44,7 @@ export const channelSelectors = {
directByAgent: (agentId: string) => (state: ChannelState) =>
state.listMap.all?.find((channel) => channel.agentId === agentId && !channel.projectId),
list: (state: ChannelState) => state.listMap.all,
+ /** This tab's messages for one conversation that its loaded pages do not hold yet. */
+ outgoing: (channelId: string, threadId?: string | null) => (state: ChannelState) =>
+ state.outbox[channelOutboxKey(channelId, threadId)] ?? NO_OUTGOING,
};
diff --git a/src/store/channel/store.ts b/src/store/channel/store.ts
index b4bd865165f..816cdebb321 100644
--- a/src/store/channel/store.ts
+++ b/src/store/channel/store.ts
@@ -5,11 +5,15 @@ import { createWithEqualityFn } from 'zustand/traditional';
import { createReplicaState, type ReplicaState } from '@/libs/replica';
import { createDevtools } from '@/store/middleware/createDevtools';
+import type { ChannelOutbox } from './outbox';
+
export interface ChannelState {
detailMap: Record<string, ChannelDetail>;
detailReplica: ReplicaState<ChannelDetail>;
listMap: Record<string, ChannelListItem[]>;
listReplica: ReplicaState<ChannelListItem[]>;
+ /** Messages sent from this tab, by conversation, until a loaded page holds them. */
+ outbox: ChannelOutbox;
}
export const initialState: ChannelState = {
@@ -17,6 +21,7 @@ export const initialState: ChannelState = {
detailReplica: createReplicaState(),
listMap: {},
listReplica: createReplicaState(),
+ outbox: {},
};
export const useChannelStore = createWithEqualityFn<ChannelState>()(