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.

💄 style(channel): IM-style composer attachments and WeChat-style day dividers (#22556)

Arvin Xu5556624f6ca0
diff --git a/.agents/ux/lobe-design-rules.md b/.agents/ux/lobe-design-rules.md
index c93beccd7c3..31988a0be44 100644
--- a/.agents/ux/lobe-design-rules.md
+++ b/.agents/ux/lobe-design-rules.md
@@ -137,3 +137,11 @@ Source: the Channel composer audit checked internal asymmetry and button weight
Reply is the primary Channel message action. Replying to a person only posts a quoted message in the current feed, with no Agent dispatch or new thread, even if the text mentions Agents. Replying to an Agent on the main feed atomically creates/reuses a thread rooted at that Agent's answer and sends the continuation there. The target Agent and explicitly mentioned Agents participate; unrelated Agents do not join. Inside a thread, keep replies in that thread and retain existing participants. Opening or cancelling reply mode never persists an empty thread.
Source: user correction of the proposed in-channel reply semantics (2026-10-31).
+
+## LOBE-UX-020 — Conversation day dividers follow WeChat, time included
+
+A Channel day divider stamps the first message of the day the way WeChat does: today is the time alone ("10:17"), not "今天"; earlier days are the day followed by the time ("昨天 01:36", "星期五 10:15", "11 月 7 日 10:15", "2025 年 11 月 7 日 10:15"). Days are calendar days in local time, not 24-hour spans. The full date stays in the hover title and the separator's accessible label.
+
+Enforcement: `src/features/Channels/messagePresentation.test.ts` (`channelDayLabel`) covers today, the yesterday boundary, weekdays, this year and earlier years in zh-CN and en-US.
+
+Source: user correction on PR #22556 (2026-11-08): "今天应该显示时间", after a first version labelled today as "今天".
diff --git a/locales/en-US/channel.json b/locales/en-US/channel.json
index d0613815dda..5345df83fc1 100644
--- a/locales/en-US/channel.json
+++ b/locales/en-US/channel.json
@@ -14,8 +14,12 @@
"archivedGroup": "Archived · {{count}}",
"archivedNotice": "This channel is archived. Its history stays readable, but it takes no new messages.",
"attachments.failed": "Upload failed. Try again.",
+ "attachments.failedShort": "Upload failed",
"attachments.limit": "Attach up to {{count}} files.",
+ "attachments.remove": "Remove {{name}}",
+ "attachments.retry": "Retry",
"attachments.upload": "Attach files",
+ "attachments.uploading": "Uploading",
"autoTitle.empty": "My Channel",
"autoTitle.more": "{{names}} and {{count}} more",
"autoTitle.separator": ", ",
@@ -38,6 +42,7 @@
"copyIdSuccess": "Channel ID copied",
"create": "Create channel",
"create.onlyYou": "Only you for now. Create it and invite members whenever you like.",
+ "date.yesterday": "Yesterday",
"delete": "Delete Channel",
"deleteConfirm": "Delete “{{title}}”? This channel will disappear for all its members and can no longer be opened. Running tasks will be requested to stop. Agents and local files will not be deleted.",
"deleteFailed": "Could not confirm the deletion. Try again.",
diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.json
index e2883848080..a2196b0b992 100644
--- a/locales/zh-CN/channel.json
+++ b/locales/zh-CN/channel.json
@@ -14,8 +14,12 @@
"archivedGroup": "已归档 · {{count}}",
"archivedNotice": "此频道已归档。历史消息仍可查看,但不再接收新消息。",
"attachments.failed": "上传失败,请重试。",
+ "attachments.failedShort": "上传失败",
"attachments.limit": "最多添加 {{count}} 个附件。",
+ "attachments.remove": "移除 {{name}}",
+ "attachments.retry": "重试",
"attachments.upload": "添加附件",
+ "attachments.uploading": "上传中",
"autoTitle.empty": "我的频道",
"autoTitle.more": "{{names}} 等 {{total}} 位成员",
"autoTitle.separator": "、",
@@ -38,6 +42,7 @@
"copyIdSuccess": "已复制频道 ID",
"create": "创建频道",
"create.onlyYou": "目前只有你。可以先创建,之后随时邀请成员。",
+ "date.yesterday": "昨天",
"delete": "删除频道",
"deleteConfirm": "删除「{{title}}」后,所有成员都将无法再访问此频道。运行中的任务将被请求停止,Agent 和本地文件不会被删除。",
"deleteFailed": "未能确认删除结果,请重试。",
diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.ts
index ddba0b2e269..ae7739d36b0 100644
--- a/packages/locales/src/default/channel.ts
+++ b/packages/locales/src/default/channel.ts
@@ -118,8 +118,13 @@ export default {
'mentionInvite.failedReason': "Couldn't add {{name}} to the channel: {{reason}}",
'mentionInvite.section': 'Not in this channel · mention to add',
'attachments.upload': 'Attach files',
+ 'date.yesterday': 'Yesterday',
'attachments.failed': 'Upload failed. Try again.',
'attachments.limit': 'Attach up to {{count}} files.',
+ 'attachments.failedShort': 'Upload failed',
+ 'attachments.remove': 'Remove {{name}}',
+ 'attachments.retry': 'Retry',
+ 'attachments.uploading': 'Uploading',
'routing.receiving': 'Agents receiving your message…',
'routing.unassigned': 'No Agent picked this up. Mention one to get a reply.',
'receipt.failedHint': 'Mention it again to retry.',
diff --git a/src/features/Channels/ChannelConversation.tsx b/src/features/Channels/ChannelConversation.tsx
index dbe4e908115..fc8858d1a82 100644
--- a/src/features/Channels/ChannelConversation.tsx
+++ b/src/features/Channels/ChannelConversation.tsx
@@ -23,7 +23,11 @@ import { Composer } from './Composer';
import { JoinEventLine } from './JoinEventLine';
import { channelJoinEvents, channelTimeline } from './joinEvents';
import { isCurrentUserMember } from './memberName';
-import { channelTimeFormatters, presentChannelTimeline } from './messagePresentation';
+import {
+ channelDayLabel,
+ channelTimeFormatters,
+ presentChannelTimeline,
+} from './messagePresentation';
import { presentOutgoingMessage, timelineTail } from './outgoing';
import { OutgoingStatus } from './OutgoingStatus';
import { ReplyActivity } from './ReplyActivity';
@@ -212,7 +216,12 @@ const Timeline = ({
role="separator"
{...stylex.props(styles.dateDivider)}
>
- <time dateTime={date.toISOString()}>{timeFormats.date.format(date)}</time>
+ <time dateTime={date.toISOString()} title={timeFormats.date.format(date)}>
+ {channelDayLabel(date, {
+ locale: i18n.language,
+ yesterday: t('date.yesterday'),
+ })}
+ </time>
</div>
)}
{item.kind === 'event' ? (
diff --git a/src/features/Channels/Composer.tsx b/src/features/Channels/Composer.tsx
index 04c41eb5b30..0c11acf5495 100644
--- a/src/features/Channels/Composer.tsx
+++ b/src/features/Channels/Composer.tsx
@@ -19,8 +19,6 @@ import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { useLocalDragUpload } from '@/components/DragUploadZone/useLocalDragUpload';
import { usePasteFile } from '@/components/DragUploadZone/usePasteFile';
-import DraftFile from '@/features/ChatInput/Mobile/FilePreview/FileItem/File';
-import DraftImage from '@/features/ChatInput/Mobile/FilePreview/FileItem/Image';
import WideScreenContainer from '@/features/WideScreenContainer';
import { useEnterToSend } from '@/hooks/useEnterToSend';
import { usePermission } from '@/hooks/usePermission';
@@ -34,6 +32,7 @@ import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
import { ComposerActions } from './ComposerActions';
+import { ComposerAttachments } from './ComposerAttachments';
import { MemberAvatar } from './MemberAvatar';
import { isCurrentUserMember, memberName } from './memberName';
import { getMentionGroups, mentionDescription } from './mentionGroups';
@@ -220,25 +219,12 @@ export function Composer({
}
};
const preview = attachments.items.length > 0 && (
- <Flexbox horizontal gap={8} inert={busy} padding={8} wrap="wrap">
- {attachments.items.map((item) =>
- item.file.type.startsWith('image/') && item.status === 'success' ? (
- <DraftImage
- alt={item.file.name}
- key={item.id}
- src={item.fileUrl}
- onRemove={() => attachments.remove(item.id)}
- />
- ) : (
- <DraftFile
- {...item}
- key={item.id}
- onRemove={() => attachments.remove(item.id)}
- onRetry={() => attachments.retry(item.id)}
- />
- ),
- )}
- </Flexbox>
+ <ComposerAttachments
+ disabled={busy}
+ items={attachments.items}
+ onRemove={attachments.remove}
+ onRetry={attachments.retry}
+ />
);
return (
<WideScreenContainer fullWidth paddingInline={16}>
diff --git a/src/features/Channels/ComposerAttachments.test.tsx b/src/features/Channels/ComposerAttachments.test.tsx
new file mode 100644
index 00000000000..f2fbd9e1660
--- /dev/null
+++ b/src/features/Channels/ComposerAttachments.test.tsx
@@ -0,0 +1,73 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { fireEvent, render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { ComposerAttachments } from './ComposerAttachments';
+import type { DraftFile } from './useAttachments';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: { name?: string }) =>
+ options?.name ? `${key}:${options.name}` : key,
+ }),
+}));
+vi.mock(
+ '@/features/ChatInput/Desktop/ContextContainer/ContextItem/FilePreviewModal.loader',
+ () => ({
+ openFilePreviewModal: vi.fn(),
+ }),
+);
+vi.mock('@/business/client/features/FileUploadErrorActions', () => ({
+ FileUploadErrorActions: () => null,
+}));
+
+const draft = (name: string, type: string, patch: Partial<DraftFile> = {}): DraftFile =>
+ ({ file: new File(['x'], name, { type }), id: name, status: 'success', ...patch }) as DraftFile;
+
+describe('ComposerAttachments', () => {
+ it('shows an image from its local copy while it uploads', () => {
+ render(
+ <ComposerAttachments
+ items={[
+ draft('shot.png', 'image/png', {
+ previewUrl: 'blob:local',
+ status: 'uploading',
+ uploadState: { progress: 40, restTime: 1, speed: 1 },
+ }),
+ ]}
+ onRemove={vi.fn()}
+ onRetry={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByAltText('shot.png').getAttribute('src')).toBe('blob:local');
+ expect(screen.getByRole('status').getAttribute('aria-label')).toBe('attachments.uploading');
+ });
+
+ it('removes from the corner and retries a failed upload', () => {
+ const onRemove = vi.fn();
+ const onRetry = vi.fn();
+ render(
+ <ComposerAttachments
+ items={[draft('notes.pdf', 'application/pdf', { status: 'error' })]}
+ onRemove={onRemove}
+ onRetry={onRetry}
+ />,
+ );
+
+ fireEvent.click(screen.getByText('attachments.retry'));
+ fireEvent.click(screen.getByRole('button', { name: 'attachments.remove:notes.pdf' }));
+ expect(onRetry).toHaveBeenCalledWith('notes.pdf');
+ expect(onRemove).toHaveBeenCalledWith('notes.pdf');
+ expect(screen.getByText('attachments.failedShort')).toBeTruthy();
+ });
+
+ it('renders nothing without attachments', () => {
+ const { container } = render(
+ <ComposerAttachments items={[]} onRemove={vi.fn()} onRetry={vi.fn()} />,
+ );
+ expect(container.innerHTML).toBe('');
+ });
+});
diff --git a/src/features/Channels/ComposerAttachments.tsx b/src/features/Channels/ComposerAttachments.tsx
new file mode 100644
index 00000000000..186966629a4
--- /dev/null
+++ b/src/features/Channels/ComposerAttachments.tsx
@@ -0,0 +1,336 @@
+import { Icon, Progress } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { CircleAlertIcon, Loader2Icon, RotateCwIcon, XIcon } from 'lucide-react';
+import type { KeyboardEvent } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { FileUploadErrorActions } from '@/business/client/features/FileUploadErrorActions';
+import FileIcon from '@/components/FileIcon';
+import { openFilePreviewModal } from '@/features/ChatInput/Desktop/ContextContainer/ContextItem/FilePreviewModal.loader';
+import {
+ getUploadChipSize,
+ getUploadChipState,
+} from '@/features/ChatInput/Desktop/ContextContainer/ContextItem/utils';
+import { formatSize } from '@/utils/format';
+
+import type { DraftFile } from './useAttachments';
+
+const HOVER = '@media (hover: hover)';
+const TILE = 64;
+
+const styles = stylex.create({
+ list: {
+ display: 'flex',
+ flexWrap: 'wrap',
+ gap: 8,
+ paddingBlockStart: 10,
+ paddingInline: 10,
+ },
+ tile: {
+ position: 'relative',
+ flexShrink: 0,
+ height: TILE,
+ borderWidth: 1,
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: cssVar.colorFillQuaternary,
+ },
+ imageTile: { width: TILE },
+ fileTile: {
+ display: 'flex',
+ gap: 10,
+ alignItems: 'center',
+ width: 224,
+ paddingInline: 10,
+ },
+ clickable: { cursor: 'pointer' },
+ failed: { borderColor: cssVar.colorErrorBorder },
+ image: {
+ display: 'block',
+ width: '100%',
+ height: '100%',
+ borderRadius: `calc(${cssVar.borderRadiusLG} - 1px)`,
+ objectFit: 'cover',
+ },
+ /** Dims an image while it uploads or after it failed, so the state reads at a glance. */
+ overlay: {
+ position: 'absolute',
+ inset: 0,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ borderWidth: 0,
+ borderRadius: `calc(${cssVar.borderRadiusLG} - 1px)`,
+ color: cssVar.colorTextLightSolid,
+ backgroundColor: cssVar.colorBgMask,
+ },
+ retryOverlay: { cursor: 'pointer' },
+ fileText: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 2,
+ minWidth: 0,
+ flex: '1',
+ },
+ name: {
+ overflow: 'hidden',
+ fontSize: cssVar.fontSize,
+ lineHeight: 1.4,
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ meta: {
+ display: 'flex',
+ gap: 4,
+ alignItems: 'center',
+ fontSize: cssVar.fontSizeSM,
+ fontVariantNumeric: 'tabular-nums',
+ lineHeight: 1.4,
+ color: cssVar.colorTextTertiary,
+ },
+ error: { color: cssVar.colorError },
+ retry: {
+ cursor: 'pointer',
+ display: 'inline-flex',
+ gap: 2,
+ alignItems: 'center',
+ padding: 0,
+ borderWidth: 0,
+ fontSize: cssVar.fontSizeSM,
+ color: cssVar.colorPrimary,
+ backgroundColor: 'transparent',
+ },
+ /** Corner remove button: always there on touch, revealed by hover or focus with a pointer. */
+ remove: {
+ cursor: 'pointer',
+ position: 'absolute',
+ insetBlockStart: -6,
+ insetInlineEnd: -6,
+ zIndex: 1,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: 18,
+ height: 18,
+ padding: 0,
+ borderWidth: 1.5,
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBgContainer,
+ borderRadius: '50%',
+ color: cssVar.colorBgContainer,
+ backgroundColor: {
+ 'default': cssVar.colorTextSecondary,
+ ':hover': cssVar.colorText,
+ },
+ opacity: {
+ default: 1,
+ [HOVER]: {
+ 'default': 0,
+ ':focus-visible': 1,
+ [stylex.when.ancestor(':hover')]: 1,
+ [stylex.when.ancestor(':focus-within')]: 1,
+ },
+ },
+ },
+});
+
+/** Opens an uploaded attachment's preview by click, Enter or Space, like a button. */
+const previewProps = (item: DraftFile, canPreview: boolean) =>
+ canPreview
+ ? {
+ onClick: () => void openFilePreviewModal(item),
+ onKeyDown: (event: KeyboardEvent<HTMLDivElement>) => {
+ if (event.target !== event.currentTarget) return;
+ if (event.key !== 'Enter' && event.key !== ' ') return;
+ event.preventDefault();
+ void openFilePreviewModal(item);
+ },
+ role: 'button' as const,
+ tabIndex: 0,
+ }
+ : {};
+
+interface ItemProps {
+ item: DraftFile;
+ onRemove: (id: string) => void;
+ onRetry: (id: string) => void;
+}
+
+const RemoveButton = ({ item, onRemove }: Omit<ItemProps, 'onRetry'>) => {
+ const { t } = useTranslation('channel');
+ return (
+ <button
+ aria-label={t('attachments.remove', { name: item.file.name })}
+ title={t('attachments.remove', { name: item.file.name })}
+ type="button"
+ {...stylex.props(styles.remove)}
+ onClick={(event) => {
+ event.stopPropagation();
+ onRemove(item.id);
+ }}
+ >
+ <Icon icon={XIcon} size={11} />
+ </button>
+ );
+};
+
+/** What the tile says about an upload that is not done yet. */
+const Progressing = ({ item, light }: { item: DraftFile; light?: boolean }) => {
+ const { progress } = getUploadChipState(item);
+ return progress === undefined || item.status !== 'uploading' ? (
+ <Icon spin icon={Loader2Icon} size={light ? 18 : 12} />
+ ) : (
+ <Progress
+ percent={progress}
+ showInfo={false}
+ size={light ? 22 : 12}
+ status="normal"
+ // Drawn in the overlay's light text color, so the ring reads on any image.
+ strokeColor={light ? 'currentColor' : undefined}
+ type="circle"
+ />
+ );
+};
+
+const ImageTile = ({ item, onRemove, onRetry }: ItemProps) => {
+ const { t } = useTranslation('channel');
+ const { busy, canPreview, canRetry } = getUploadChipState(item);
+ return (
+ <div
+ aria-busy={busy}
+ title={item.file.name}
+ {...stylex.props(
+ stylex.defaultMarker(),
+ styles.tile,
+ styles.imageTile,
+ canPreview && styles.clickable,
+ canRetry && styles.failed,
+ )}
+ {...previewProps(item, canPreview)}
+ >
+ <img
+ alt={item.file.name}
+ src={item.previewUrl ?? item.fileUrl}
+ {...stylex.props(styles.image)}
+ />
+ {busy && (
+ <div
+ aria-label={t('attachments.uploading')}
+ role="status"
+ {...stylex.props(styles.overlay)}
+ >
+ <Progressing light item={item} />
+ </div>
+ )}
+ {canRetry &&
+ (item.errorCode ? (
+ <div {...stylex.props(styles.overlay)}>
+ <FileUploadErrorActions compact code={item.errorCode} />
+ </div>
+ ) : (
+ <button
+ aria-label={t('attachments.retry')}
+ title={item.error ?? t('attachments.failed')}
+ type="button"
+ {...stylex.props(styles.overlay, styles.retryOverlay)}
+ onClick={(event) => {
+ event.stopPropagation();
+ onRetry(item.id);
+ }}
+ >
+ <Icon icon={RotateCwIcon} size={18} />
+ </button>
+ ))}
+ <RemoveButton item={item} onRemove={onRemove} />
+ </div>
+ );
+};
+
+const FileTile = ({ item, onRemove, onRetry }: ItemProps) => {
+ const { t } = useTranslation('channel');
+ const { busy, canPreview, canRetry } = getUploadChipState(item);
+ return (
+ <div
+ aria-busy={busy}
+ title={item.file.name}
+ {...stylex.props(
+ stylex.defaultMarker(),
+ styles.tile,
+ styles.fileTile,
+ canPreview && styles.clickable,
+ canRetry && styles.failed,
+ )}
+ {...previewProps(item, canPreview)}
+ >
+ <FileIcon fileName={item.file.name} fileType={item.file.type} size={32} />
+ <div {...stylex.props(styles.fileText)}>
+ <span {...stylex.props(styles.name)}>{item.file.name}</span>
+ <span {...stylex.props(styles.meta, canRetry && styles.error)}>
+ {busy ? (
+ <>
+ <Progressing item={item} />
+ {getUploadChipSize(item)}
+ </>
+ ) : canRetry ? (
+ <>
+ <Icon icon={CircleAlertIcon} size={12} />
+ {t('attachments.failedShort')}
+ {item.errorCode ? (
+ <FileUploadErrorActions compact code={item.errorCode} />
+ ) : (
+ <button
+ type="button"
+ {...stylex.props(styles.retry)}
+ onClick={(event) => {
+ event.stopPropagation();
+ onRetry(item.id);
+ }}
+ >
+ {t('attachments.retry')}
+ </button>
+ )}
+ </>
+ ) : (
+ formatSize(item.file.size)
+ )}
+ </span>
+ </div>
+ <RemoveButton item={item} onRemove={onRemove} />
+ </div>
+ );
+};
+
+interface ComposerAttachmentsProps {
+ disabled?: boolean;
+ items: DraftFile[];
+ onRemove: (id: string) => void;
+ onRetry: (id: string) => void;
+}
+
+/**
+ * The composer's pending attachments, IM style: an image is a thumbnail from the moment it is
+ * picked, with its upload progress over it; any other file is a compact card. Each removes from
+ * its corner and opens a preview once uploaded.
+ */
+export const ComposerAttachments = ({
+ disabled,
+ items,
+ onRemove,
+ onRetry,
+}: ComposerAttachmentsProps) => {
+ if (!items.length) return null;
+ return (
+ <div inert={disabled} {...stylex.props(styles.list)}>
+ {items.map((item) =>
+ item.file.type.startsWith('image/') ? (
+ <ImageTile item={item} key={item.id} onRemove={onRemove} onRetry={onRetry} />
+ ) : (
+ <FileTile item={item} key={item.id} onRemove={onRemove} onRetry={onRetry} />
+ ),
+ )}
+ </div>
+ );
+};
diff --git a/src/features/Channels/messagePresentation.test.ts b/src/features/Channels/messagePresentation.test.ts
index b44d59db149..6eb2451deac 100644
--- a/src/features/Channels/messagePresentation.test.ts
+++ b/src/features/Channels/messagePresentation.test.ts
@@ -2,7 +2,11 @@ import type { ChannelPublicMessage } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
import type { TimelineItem } from './joinEvents';
-import { channelTimeFormatters, presentChannelTimeline } from './messagePresentation';
+import {
+ channelDayLabel,
+ channelTimeFormatters,
+ presentChannelTimeline,
+} from './messagePresentation';
const message = (at: Date, patch: Partial<ChannelPublicMessage> = {}): TimelineItem => ({
kind: 'message',
@@ -74,3 +78,25 @@ describe('channel timestamps', () => {
expect(zh.full.format(date)).toContain('2026年10月31日');
});
});
+
+describe('channelDayLabel', () => {
+ // Sunday 8 November 2026, a little past midnight: the day boundary is what matters.
+ const now = new Date(2026, 10, 8, 0, 18);
+ const label = (date: Date, locale = 'zh-CN') =>
+ channelDayLabel(date, { locale, now, yesterday: '昨天' });
+
+ it('shows only the time today, and yesterday by calendar day, not by 24 hours', () => {
+ expect(label(new Date(2026, 10, 8, 0, 1))).toBe('00:01');
+ // 01:36 yesterday is under 24 hours ago but still yesterday; 23:59 the day before is not.
+ expect(label(new Date(2026, 10, 7, 1, 36))).toBe('昨天 01:36');
+ expect(label(new Date(2026, 10, 6, 23, 59))).not.toMatch(/^昨天/);
+ });
+
+ it('names the weekday within the past week, then the date, each with the time', () => {
+ expect(label(new Date(2026, 10, 6, 10, 15))).toBe('星期五 10:15');
+ expect(label(new Date(2026, 10, 2, 9, 0))).toBe('星期一 09:00');
+ expect(label(new Date(2026, 10, 1, 9, 0))).toBe('11月1日 09:00');
+ expect(label(new Date(2025, 10, 7, 9, 0))).toBe('2025年11月7日 09:00');
+ expect(label(new Date(2026, 10, 6, 10, 15), 'en-US')).toBe('Friday 10:15 AM');
+ });
+});
diff --git a/src/features/Channels/messagePresentation.ts b/src/features/Channels/messagePresentation.ts
index b499a411af1..aded7a73044 100644
--- a/src/features/Channels/messagePresentation.ts
+++ b/src/features/Channels/messagePresentation.ts
@@ -37,3 +37,44 @@ export const channelTimeFormatters = (locale: string) => ({
full: new Intl.DateTimeFormat(locale, { dateStyle: 'full', timeStyle: 'medium' }),
time: new Intl.DateTimeFormat(locale, { hour: '2-digit', minute: '2-digit' }),
});
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+/** Whole calendar days from `date` to `now`, in local time, unaffected by daylight-saving shifts. */
+const calendarDaysAgo = (date: Date, now: Date) =>
+ Math.round(
+ (Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()) -
+ Date.UTC(date.getFullYear(), date.getMonth(), date.getDate())) /
+ DAY_MS,
+ );
+
+/**
+ * A day divider's label, the way WeChat stamps a conversation: the time alone today, then
+ * "Yesterday", the weekday within the past week, the month and day within this year, or the full
+ * date before that, each followed by the time of the day's first message.
+ */
+export const channelDayLabel = (
+ date: Date,
+ {
+ locale,
+ now = new Date(),
+ yesterday,
+ }: {
+ locale: string;
+ now?: Date;
+ yesterday: string;
+ },
+) => {
+ const time = new Intl.DateTimeFormat(locale, { hour: '2-digit', minute: '2-digit' }).format(date);
+ const days = calendarDaysAgo(date, now);
+ if (days === 0) return time;
+ const day =
+ days === 1
+ ? yesterday
+ : days > 1 && days < 7
+ ? new Intl.DateTimeFormat(locale, { weekday: 'long' }).format(date)
+ : date.getFullYear() === now.getFullYear()
+ ? new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'long' }).format(date)
+ : new Intl.DateTimeFormat(locale, { dateStyle: 'long' }).format(date);
+ return `${day} ${time}`;
+};
diff --git a/src/features/Channels/useAttachments.test.ts b/src/features/Channels/useAttachments.test.ts
new file mode 100644
index 00000000000..ec03fd5e352
--- /dev/null
+++ b/src/features/Channels/useAttachments.test.ts
@@ -0,0 +1,45 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { useAttachments } from './useAttachments';
+
+const upload = vi.hoisted(() => vi.fn());
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('@lobehub/ui', () => ({ toast: { error: vi.fn() } }));
+vi.mock('@lobechat/utils/compressImage', () => ({
+ COMPRESSIBLE_IMAGE_TYPES: new Set(),
+ compressImageFile: vi.fn(),
+}));
+vi.mock('@/store/file', () => ({
+ useFileStore: (selector: (s: { uploadWithProgress: typeof upload }) => unknown) =>
+ selector({ uploadWithProgress: upload }),
+}));
+
+describe('useAttachments local image previews', () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it('shows an image from a local URL at once and releases it when removed', async () => {
+ const create = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:shot');
+ const revoke = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
+ upload.mockResolvedValue({ id: 'file-1', url: 'https://cdn/shot.png' });
+ const { result } = renderHook(() => useAttachments());
+
+ await act(() =>
+ result.current.upload([
+ new File(['x'], 'shot.png', { type: 'image/png' }),
+ new File(['x'], 'notes.txt', { type: 'text/plain' }),
+ ]),
+ );
+
+ expect(create).toHaveBeenCalledTimes(1);
+ const [image, text] = result.current.items;
+ expect(image).toMatchObject({ previewUrl: 'blob:shot', status: 'success' });
+ expect(text.previewUrl).toBeUndefined();
+
+ act(() => result.current.remove(image.id));
+ expect(revoke).toHaveBeenCalledWith('blob:shot');
+ });
+});
diff --git a/src/features/Channels/useAttachments.ts b/src/features/Channels/useAttachments.ts
index 52926b6765a..4ae2243b16e 100644
--- a/src/features/Channels/useAttachments.ts
+++ b/src/features/Channels/useAttachments.ts
@@ -7,7 +7,14 @@ import { useTranslation } from 'react-i18next';
import { FILE_UPLOAD_BLACKLIST } from '@/const/file';
import { useFileStore } from '@/store/file';
-type DraftFile = UploadFileItem & { fileId?: string };
+export type DraftFile = UploadFileItem & { fileId?: string };
+
+/** An image is shown from the local file while it uploads; the URL lives as long as the draft. */
+const localPreview = (file: File) =>
+ file.type.startsWith('image/') ? URL.createObjectURL(file) : undefined;
+const releasePreview = (item: DraftFile) => {
+ if (item.previewUrl?.startsWith('blob:')) URL.revokeObjectURL(item.previewUrl);
+};
/** Each mounted Channel composer owns its uploads; ordinary chat's global draft is untouched. */
export function useAttachments() {
@@ -24,7 +31,10 @@ export function useAttachments() {
useEffect(
() => () => {
- for (const item of current.current) item.abortController?.abort();
+ for (const item of current.current) {
+ item.abortController?.abort();
+ releasePreview(item);
+ }
},
[],
);
@@ -76,19 +86,26 @@ export function useAttachments() {
const added = accepted.map((file): DraftFile => ({
file,
id: crypto.randomUUID(),
+ previewUrl: localPreview(file),
status: 'pending',
}));
update([...current.current, ...added]);
await Promise.all(added.map(run));
},
remove: (id: string) => {
- current.current.find((item) => item.id === id)?.abortController?.abort();
+ const removed = current.current.find((item) => item.id === id);
+ removed?.abortController?.abort();
+ if (removed) releasePreview(removed);
update(current.current.filter((item) => item.id !== id));
},
retry: (id: string) => {
const item = current.current.find((item) => item.id === id);
if (item?.status === 'error') void run(item);
},
- clear: () => update([]),
+ // A sent draft's images are shown from their uploaded URLs; the local copies can go.
+ clear: () => {
+ for (const item of current.current) releasePreview(item);
+ update([]);
+ },
};
}