🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(channel): return an image attachment's pixel size so clients reserve its box before loading (#23644)
Lobehub Coder979a93109449
diff --git a/apps/server/src/services/channel/ChannelHistoryService.ts b/apps/server/src/services/channel/ChannelHistoryService.tsindex 9a48c8622ac..de39bfe3377 100644--- a/apps/server/src/services/channel/ChannelHistoryService.ts+++ b/apps/server/src/services/channel/ChannelHistoryService.ts@@ -1,9 +1,7 @@import type { ChannelReadMessageParams, ChannelReadMessagesParams } from '@lobechat/types';-import { inArray } from 'drizzle-orm';import pMap from 'p-map';-import { ChannelHistoryRepository } from '@/database/repositories/channel';-import { files } from '@/database/schemas';+import { channelAttachments, ChannelHistoryRepository } from '@/database/repositories/channel';import type { LobeChatDatabase } from '@/database/type';import { FileService } from '@/server/services/file';@@ -31,18 +29,7 @@ export class ChannelHistoryService {await assertChannelEnabled(this.userId);const result = await this.repository.readMessage(this.operationId, params);const ids = result.message.fileIds ?? [];- const shared = ids.length- ? await this.db- .select({- id: files.id,- name: files.name,- fileType: files.fileType,- size: files.size,- url: files.url,- })- .from(files)- .where(inArray(files.id, ids))- : [];+ const shared = await channelAttachments(this.db, ids);const fileService = new FileService(this.db, this.userId, this.workspaceId);return {...result,diff --git a/packages/database/src/repositories/channel/__tests__/attachments.test.ts b/packages/database/src/repositories/channel/__tests__/attachments.test.tsindex 5c2df9163dc..57723ebce80 100644--- a/packages/database/src/repositories/channel/__tests__/attachments.test.ts+++ b/packages/database/src/repositories/channel/__tests__/attachments.test.ts@@ -15,11 +15,12 @@ const execution = new ChannelExecutionRepository(db);beforeEach(fixture.setup);afterEach(fixture.cleanup);-const createFile = async (name: string, fileType = 'text/plain') => {+const createFile = async (name: string, fileType = 'text/plain', metadata?: object) => {const [file] = await db.insert(files).values({fileType,+ metadata,name,size: 1,url: `files/${name}`,@@ -103,4 +104,41 @@ describe('channel message attachments', () => {},});});++ // Mobile sized an image's box only after fetching it, so the row grew and the feed jumped.+ it("returns an image attachment's recorded pixel size, and nothing else from its metadata", async () => {+ const { asMember, channel } = await fixture.createTeamChannel();+ const shot = await createFile('shot.png', 'image/png', {+ filename: 'shot.png',+ height: 2622,+ path: 'files/private/shot.png',+ ratio: 1206 / 2622,+ width: 1206,+ });+ const legacy = await createFile('old.png', 'image/png', { path: 'files/old.png' });+ const half = await createFile('half.png', 'image/png', { width: 10 });+ const text = await createFile('a.txt');+ await asMember.send(channel.id, {+ content: '',+ fileIds: [shot, legacy, half, text],+ requestKey: 'req-1',+ routing: 'decision',+ });++ const { attachments } = await asMember.detail(channel.id);+ const byId = new Map(attachments.map((file) => [file.id, file]));++ expect(byId.get(shot)).toEqual({+ fileType: 'image/png',+ height: 2622,+ id: shot,+ name: 'shot.png',+ size: 1,+ url: 'files/shot.png',+ width: 1206,+ });+ for (const id of [legacy, half, text]) {+ expect(byId.get(id)).toMatchObject({ height: null, width: null });+ }+ });});diff --git a/packages/database/src/repositories/channel/attachments.ts b/packages/database/src/repositories/channel/attachments.tsindex 2ab16f84989..4fb1f4ff2d9 100644--- a/packages/database/src/repositories/channel/attachments.ts+++ b/packages/database/src/repositories/channel/attachments.ts@@ -1,7 +1,7 @@import type { SQLWrapper } from 'drizzle-orm';import { asc, inArray } from 'drizzle-orm';-import { channelMessageFiles } from '../../schemas';+import { channelMessageFiles, files } from '../../schemas';import type { LobeChatDatabase, Transaction } from '../../type';/**@@ -50,3 +50,36 @@ export const fileIdsByMessage = async (return result;};++/** A positive finite pixel count from caller-written JSON metadata, or `null`. */+const pixels = (value: unknown) =>+ typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.round(value) : null;++/**+ * The attachments a Channel shows, by file id. `width` / `height` are the picture's intrinsic+ * pixels as the uploader recorded them in `metadata`, so a client can size the picture's box+ * before fetching it; `null` when unknown (not an image, or an upload that did not record them).+ * Nothing else in `metadata` is returned: it also holds the storage path.+ */+export const channelAttachments = async (tx: LobeChatDatabase | Transaction, ids: string[]) => {+ if (!ids.length) return [];++ const rows = await tx+ .select({+ fileType: files.fileType,+ id: files.id,+ metadata: files.metadata,+ name: files.name,+ size: files.size,+ url: files.url,+ })+ .from(files)+ .where(inArray(files.id, ids));+ return rows.map(({ metadata, ...file }) => {+ const meta = (metadata ?? {}) as { height?: unknown; width?: unknown };+ const [width, height] = [pixels(meta.width), pixels(meta.height)];+ // Half a size reserves nothing: report both or neither.+ const known = width !== null && height !== null;+ return { ...file, height: known ? height : null, width: known ? width : null };+ });+};diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.tsindex e3937a74027..7faa3fbc55c 100644--- a/packages/database/src/repositories/channel/index.ts+++ b/packages/database/src/repositories/channel/index.ts@@ -81,6 +81,7 @@ import {export type { ChannelAddAgentInput } from './agent';export { memberEnvironment } from './agent';+export { channelAttachments } from './attachments';export {CHANNEL_ROUTING_BATCH_SIZE,CHANNEL_ROUTING_LEASE_MS,diff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.tsindex 7ed5ed3634d..635f74f4cb1 100644--- a/packages/database/src/repositories/channel/view.ts+++ b/packages/database/src/repositories/channel/view.ts@@ -40,7 +40,6 @@ import {channels,channelThreads,devices,- files as fileTable,topics,users,workspaceUserSettings,@@ -48,7 +47,7 @@ import {import type { Transaction } from '../../type';import { agentAvatarSql, agentTitleSql } from '../../utils/inboxAgent';import { notTrashed } from '../../utils/softDelete';-import { fileIdsByMessage } from './attachments';+import { channelAttachments, fileIdsByMessage } from './attachments';import { isAgentAuthored } from './author';import { activeMembers } from './delivery';import { ChannelError } from './error';@@ -747,18 +746,7 @@ export const readChannelView = async (relayAgentAvatars(tx, [...page, ...(rootMessage ? [rootMessage] : [])]),]);const ids = [...new Set([...files.values()].flat())];- const attachments = ids.length- ? await tx- .select({- id: fileTable.id,- name: fileTable.name,- fileType: fileTable.fileType,- size: fileTable.size,- url: fileTable.url,- })- .from(fileTable)- .where(inArray(fileTable.id, ids))- : [];+ const attachments = await channelAttachments(tx, ids);return {attachments,hasMore: reversed.length > limit,