Skip to content

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

πŸ› fix(resource): one library section, recent pages that stay visible, and image cards that reserve their real box (#18124)

Arvin Xu0642572a6604
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.md
index c6217918dfc..c3b40a3f648 100644
--- a/.agents/acceptance/common-mistakes.md
+++ b/.agents/acceptance/common-mistakes.md
@@ -175,6 +175,25 @@ disclosure is not expressible in that field.
**Correct approach:** set `"verifier": "llm"` and carry the multimodal disclosure in
the plan item's `method` prose alongside `"requiredEvidence": ["screenshot"]`.
+### L-E13 β€” Publishing uncommitted work onto the branch's unrelated PR
+
+**Wrong approach:** verify working-tree changes that have no PR of their own, then
+ingest without stating that, assuming the round carries no PR because `result.json`
+omits `pullRequest` (or sets it to `null`).
+
+**Why it fails:** the ingest resolves the PR from `branch` whenever the field is
+absent OR null, so a long-lived branch that already owns a PR stamps every round
+with it. The page then presents an unrelated PR as the provenance of this
+verification, and deleting the run and re-ingesting reproduces the same stamp.
+Two rounds later nobody can tell which delivery the evidence belongs to.
+
+**Correct approach:** before publishing a round for uncommitted work, decide the
+provenance explicitly β€” commit and open the real PR first, or state in `report.md`
+that this round has no PR and that any PR shown belongs to other work on the same
+branch. Also re-read `branch` / `commit` at publish time rather than trusting the
+scaffold: a session that spans a branch switch fills them from whatever is checked
+out when `report-init.sh` ran.
+
## Product and interaction contracts
### L-D1 β€” Rebuilding a canonical surface from visual impression
@@ -291,6 +310,25 @@ count the versions under `node_modules/<pkg>` and every `packages/*/node_modules
and require one distinct value β€” never from the root manifest. Remember `apps/desktop`
and `apps/cli` are standalone installs that a root install never covers.
+### L-S0b β€” Reading a first-boot renderer crash as a defect of the change under test
+
+**Wrong approach:** treat the Electron dev instance's first renderer boot as
+representative, and diagnose a `ReferenceError: Cannot access '<X>' before
+initialization` thrown from the desktop router config as a bug in the branch.
+
+**Why it fails:** the desktop Vite renderer can serve a partially initialized
+module graph on the very first boot after a cold start (dependency optimization
+runs concurrently with the first evaluation). The app stays on the HTML loading
+shell with `rootChildren: 0` while the stores are already exposed, which reads
+exactly like a broken route tree. A single `location.reload()` boots it cleanly
+with no code change.
+
+**Correct approach:** on a first-boot renderer error, reload once and re-probe
+before drawing any conclusion. Only if the error survives a reload does it belong
+to the code. Never attribute it to the change under test without that A/B β€” and
+note that `electron-dev.sh start` reports "Ready" even when the renderer never
+became interactive, so its own readiness line is not the gate.
+
### L-S1 β€” Publishing to an assumed server target
**Wrong approach:** strip a server environment variable and treat `lh whoami` as
@@ -391,6 +429,18 @@ the served bundle carries it β€” fetch the relevant `/node_modules/.vite/deps/*`
from the dev server and grep for a marker of the fix β€” or restart the dev server
process outright and re-verify.
+**Same failure, second shape β€” a dev server that was already running when the run
+started.** A leftover server can be listening on a port that no longer matches what
+`test-env.sh` resolves, serving a dep graph optimized against a different config. The
+SPA then dies at the ErrorBoundary with `TypeError: Failed to fetch dynamically
+imported module: …/_layout/index.tsx`, which reads exactly like a broken route tree in
+the branch under test β€” while every module in that graph still returns 200 to `curl`,
+because the served copy and the requested copy disagree, not the source. Before
+attributing any module-load failure to the change under test, compare the running
+server's port with `test-env.sh`'s resolved `PORT`; on a mismatch, `stop-dev` and
+restart before diagnosing anything. The restarted server is then yours to stop at
+teardown even though you did not start the original.
+
---
## Cross-agent dispatch envelopes are not visible user turns
diff --git a/apps/server/src/routers/lambda/file.ts b/apps/server/src/routers/lambda/file.ts
index f6dde618db7..fce026f7715 100644
--- a/apps/server/src/routers/lambda/file.ts
+++ b/apps/server/src/routers/lambda/file.ts
@@ -1,8 +1,4 @@
-import {
- CUSTOM_DOCUMENT_FILE_TYPE,
- CUSTOM_FOLDER_FILE_TYPE,
- DERIVED_DOCUMENT_SOURCE_TYPE,
-} from '@lobechat/const';
+import { CUSTOM_FOLDER_FILE_TYPE, DERIVED_DOCUMENT_SOURCE_TYPE } from '@lobechat/const';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
@@ -566,11 +562,9 @@ export const fileRouter = router({
.input(z.object({ limit: z.number().max(50).optional() }).optional())
.query(async ({ ctx, input }) => {
const limit = input?.limit ?? 12;
- // Query recent items and filter for files only (exclude documents/pages)
- const allItems = await ctx.knowledgeRepo.queryRecent(limit * 3); // Query more to ensure we have enough files after filtering
- const fileItems = allItems
- .filter((item) => item.sourceType === 'file' && item.fileType !== CUSTOM_DOCUMENT_FILE_TYPE)
- .slice(0, limit);
+ // Files only (pages are excluded in SQL, so `limit` can't be eaten by
+ // page rows that are then filtered out).
+ const fileItems = await ctx.knowledgeRepo.queryRecent(limit, 'file');
if (fileItems.length === 0) return [];
@@ -626,15 +620,9 @@ export const fileRouter = router({
.input(z.object({ limit: z.number().max(50).optional() }).optional())
.query(async ({ ctx, input }) => {
const limit = input?.limit ?? 12;
- // Query recent items and filter for pages (documents) only, exclude folders
- const allItems = await ctx.knowledgeRepo.queryRecent(limit * 3); // Query more to ensure we have enough pages after filtering
- return allItems
- .filter(
- (item) =>
- item.sourceType === DERIVED_DOCUMENT_SOURCE_TYPE &&
- item.fileType !== CUSTOM_FOLDER_FILE_TYPE,
- )
- .slice(0, limit);
+ // Pages only (folders and files are excluded in SQL, so `limit` can't be
+ // eaten by rows that are then filtered out).
+ return ctx.knowledgeRepo.queryRecent(limit, 'page');
}),
removeFile: fileProcedure
diff --git a/locales/en-US/components.json b/locales/en-US/components.json
index 09426d34178..0c4a07b383c 100644
--- a/locales/en-US/components.json
+++ b/locales/en-US/components.json
@@ -54,6 +54,7 @@
"FileManager.emptyStatus.actions.knowledgeBase": "Create Library",
"FileManager.emptyStatus.or": "or",
"FileManager.emptyStatus.title": "Drag files or folders here",
+ "FileManager.image.loadFailed": "Preview unavailable",
"FileManager.noFolders": "No folders available",
"FileManager.search.noResults": "No files found",
"FileManager.search.placeholder": "Search files...",
diff --git a/locales/zh-CN/components.json b/locales/zh-CN/components.json
index abe7f61b6c2..66d81dbf254 100644
--- a/locales/zh-CN/components.json
+++ b/locales/zh-CN/components.json
@@ -54,6 +54,7 @@
"FileManager.emptyStatus.actions.knowledgeBase": "新建衄源库",
"FileManager.emptyStatus.or": "ζˆ–θ€…",
"FileManager.emptyStatus.title": "ζŠŠζ–‡δ»Άζˆ–ζ–‡δ»Άε€Ήζ‹–εˆ°θΏ™ι‡Œ",
+ "FileManager.image.loadFailed": "ι’„θ§ˆζš‚ζ—ΆεŠ θ½½δΈε‡Ίζ₯",
"FileManager.noFolders": "θΏ˜ζ²‘ζœ‰ζ–‡δ»Άε€Ή",
"FileManager.search.noResults": "ζœͺζ‰Ύεˆ°ζ–‡δ»Ά",
"FileManager.search.placeholder": "ζœη΄’ζ–‡δ»Ά...",
diff --git a/packages/database/src/repositories/knowledge/index.test.ts b/packages/database/src/repositories/knowledge/index.test.ts
index 2ea769469bd..b08d5418ac1 100644
--- a/packages/database/src/repositories/knowledge/index.test.ts
+++ b/packages/database/src/repositories/knowledge/index.test.ts
@@ -720,6 +720,64 @@ describe('KnowledgeRepo', () => {
const otherUserItem = results.find((item) => item.name === 'other-recent.pdf');
expect(otherUserItem).toBeUndefined();
});
+
+ it('should still return pages when newer files would fill the limit', async () => {
+ // The page kind has to be filtered in SQL: filtering a truncated
+ // recent-everything list dropped every page as soon as the newest rows
+ // were all files, emptying the resource home "recent pages" section.
+ await serverDB.insert(files).values(
+ Array.from({ length: 5 }, (_, index) => ({
+ id: `newer-file-${index}`,
+ fileType: 'application/pdf',
+ name: `newer-${index}.pdf`,
+ size: 1024,
+ url: `newer-url-${index}`,
+ userId,
+ updatedAt: new Date('2024-02-01T10:00:00Z'),
+ })),
+ );
+
+ const results = await knowledgeRepo.queryRecent(3, 'page');
+
+ expect(results.map((item) => item.name)).toEqual(['recent-doc.txt']);
+ });
+
+ it('should exclude folders from the page kind', async () => {
+ await serverDB.insert(documents).values({
+ id: 'recent-folder',
+ fileType: 'custom/folder',
+ filename: 'recent folder',
+ source: 'api-source',
+ sourceType: 'api',
+ title: 'recent folder',
+ totalCharCount: 0,
+ totalLineCount: 0,
+ updatedAt: new Date('2024-01-04T10:00:00Z'),
+ userId,
+ });
+
+ const results = await knowledgeRepo.queryRecent(10, 'page');
+
+ expect(results.some((item) => item.id === 'recent-folder')).toBe(false);
+ expect(results.map((item) => item.name)).toEqual(['recent-doc.txt']);
+ });
+
+ it('should exclude derived page rows from the file kind', async () => {
+ await serverDB.insert(files).values({
+ id: 'derived-page-file',
+ fileType: 'custom/document',
+ name: 'a page',
+ size: 0,
+ url: 'url-page',
+ userId,
+ updatedAt: new Date('2024-01-04T10:00:00Z'),
+ });
+
+ const results = await knowledgeRepo.queryRecent(10, 'file');
+
+ expect(results.some((item) => item.id === 'derived-page-file')).toBe(false);
+ expect(results.map((item) => item.name)).toEqual(['recent-1.pdf', 'recent-2.pdf']);
+ });
});
describe('deleteItem', () => {
diff --git a/packages/database/src/repositories/knowledge/index.ts b/packages/database/src/repositories/knowledge/index.ts
index d3437be9713..eaf9b5650c5 100644
--- a/packages/database/src/repositories/knowledge/index.ts
+++ b/packages/database/src/repositories/knowledge/index.ts
@@ -1,3 +1,4 @@
+import { CUSTOM_DOCUMENT_FILE_TYPE, CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';
import type { FileUploader, QueryFileListParams } from '@lobechat/types';
import { FilesTabs, SortType } from '@lobechat/types';
import { and, eq, sql } from 'drizzle-orm';
@@ -42,6 +43,13 @@ export interface KnowledgeItem {
visibility?: 'private' | 'public' | null;
}
+/**
+ * Kind of row a recent query is after:
+ * - `file` β€” uploaded files, excluding the file rows that back a derived page
+ * - `page` β€” derived pages / notes, excluding folders
+ */
+export type RecentItemKind = 'file' | 'page';
+
interface KnowledgeQueryParams extends QueryFileListParams {
/** Restrict the result set to rows created by a specific workspace member. */
creatorUserId?: string;
@@ -227,8 +235,21 @@ export class KnowledgeRepo {
/**
* Query recent items (files and documents)
* Returns the most recently updated items
+ *
+ * `kind` narrows the result to uploaded files or derived pages. The narrowing
+ * has to happen inside SQL: filtering the combined list afterwards lets
+ * `LIMIT` truncate away every row of the wanted kind β€” a burst of uploads
+ * left the resource home with an empty "recent pages" section.
*/
- async queryRecent(limit: number = 12): Promise<KnowledgeItem[]> {
+ async queryRecent(limit: number = 12, kind?: RecentItemKind): Promise<KnowledgeItem[]> {
+ // Derived pages live in the documents table; their backing file row is not
+ // a file the user uploaded, so it never belongs to the file list.
+ const fileKindCondition =
+ kind === 'file' ? sql` AND f.file_type != ${CUSTOM_DOCUMENT_FILE_TYPE}` : sql``;
+ // Folders are containers, not pages.
+ const pageKindCondition =
+ kind === 'page' ? sql` AND file_type != ${CUSTOM_FOLDER_FILE_TYPE}` : sql``;
+
const fileQuery = sql`
SELECT
COALESCE(d.id, f.id) as id,
@@ -262,7 +283,7 @@ export class KnowledgeRepo {
AND NOT EXISTS (
SELECT 1 FROM ${knowledgeBaseFiles}
WHERE ${knowledgeBaseFiles.fileId} = f.id
- )
+ )${fileKindCondition}
`;
const documentQuery = sql`
@@ -302,14 +323,23 @@ export class KnowledgeRepo {
) documents
WHERE ${this.documentOwnershipSql('documents')}
AND source_type != ${'file'}
- AND knowledge_base_id IS NULL
+ AND knowledge_base_id IS NULL${pageKindCondition}
`;
- const combinedQuery = sql`
- SELECT * FROM (
+ const sourceQuery =
+ kind === 'file'
+ ? sql`(${fileQuery})`
+ : kind === 'page'
+ ? sql`(${documentQuery})`
+ : sql`
(${fileQuery})
UNION ALL
(${documentQuery})
+ `;
+
+ const combinedQuery = sql`
+ SELECT * FROM (
+ ${sourceQuery}
) as combined
ORDER BY updated_at DESC
LIMIT ${limit}
diff --git a/packages/locales/src/default/components.ts b/packages/locales/src/default/components.ts
index 2cc4d607b27..507eba8a6b1 100644
--- a/packages/locales/src/default/components.ts
+++ b/packages/locales/src/default/components.ts
@@ -65,6 +65,7 @@ export default {
'FileManager.emptyStatus.actions.knowledgeBase': 'Create Library',
'FileManager.emptyStatus.or': 'or',
'FileManager.emptyStatus.title': 'Drag files or folders here',
+ 'FileManager.image.loadFailed': 'Preview unavailable',
'FileManager.noFolders': 'No folders available',
'FileManager.search.noResults': 'No files found',
'FileManager.search.placeholder': 'Search files...',
diff --git a/src/features/ResourceHome/Home/FrequentLibraries.tsx b/src/features/ResourceHome/Home/FrequentLibraries.tsx
deleted file mode 100644
index a743740c25a..00000000000
--- a/src/features/ResourceHome/Home/FrequentLibraries.tsx
+++ /dev/null
@@ -1,158 +0,0 @@
-'use client';
-
-import { Flexbox, Icon } from '@lobehub/ui';
-import { Skeleton } from 'antd';
-import { createStaticStyles } from 'antd-style';
-import { PlusIcon } from 'lucide-react';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import LibIcon from '@/components/LibIcon';
-import { useCreateNewModal } from '@/features/LibraryModal';
-import { useResourceManagerStore } from '@/features/ResourceManager/store';
-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { usePermission } from '@/hooks/usePermission';
-import { useKnowledgeBaseStore } from '@/store/library';
-
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chip: css`
- cursor: pointer;
-
- display: flex;
- gap: 10px;
- align-items: center;
-
- min-width: 0;
- padding-block: 14px;
- padding-inline: 16px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadiusLG};
-
- text-align: start;
-
- background: ${cssVar.colorFillQuaternary};
-
- transition: all 0.2s ${cssVar.motionEaseInOut};
-
- &:hover {
- border-color: ${cssVar.colorBorder};
- background: ${cssVar.colorFillTertiary};
- }
- `,
- createChip: css`
- cursor: pointer;
-
- display: flex;
- gap: 8px;
- align-items: center;
- justify-content: center;
-
- padding-block: 14px;
- padding-inline: 16px;
- border: 1px dashed ${cssVar.colorBorder};
- border-radius: ${cssVar.borderRadiusLG};
-
- color: ${cssVar.colorTextSecondary};
-
- background: transparent;
-
- transition: all 0.2s ${cssVar.motionEaseInOut};
-
- &:hover {
- border-color: ${cssVar.colorTextQuaternary};
- color: ${cssVar.colorText};
- }
-
- &:disabled {
- cursor: not-allowed;
- opacity: 0.5;
- }
- `,
- grid: css`
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
- gap: 12px;
- `,
- name: css`
- overflow: hidden;
-
- font-size: 13px;
- font-weight: 500;
- color: ${cssVar.colorText};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
-
-/** How many libraries the quick-access row shows before "all" lives in the sidebar. */
-const MAX_FREQUENT_LIBRARIES = 7;
-
-/**
- * Quick access to the user's libraries, sitting right under the greeting β€”
- * the everyday entry point of the library home.
- */
-const FrequentLibraries = memo(() => {
- const { t } = useTranslation('file');
- const navigate = useWorkspaceAwareNavigate();
- const { allowed: canCreate } = usePermission('create_content');
-
- const listVisibility = useResourceManagerStore((s) => s.listVisibility);
- const visibility = listVisibility === 'private' ? ('private' as const) : ('public' as const);
-
- const useFetchKnowledgeBaseList = useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseList);
- const { data, isLoading } = useFetchKnowledgeBaseList(visibility);
-
- const setLibraryId = useResourceManagerStore((s) => s.setLibraryId);
- const { open: openCreateLibrary } = useCreateNewModal();
-
- const handleCreate = () => {
- if (!canCreate) return;
- openCreateLibrary({
- onSuccess: (id) => {
- navigate(`/resource/library/${id}`);
- },
- });
- };
-
- return (
- <Flexbox gap={12}>
- {isLoading ? (
- <div className={styles.grid}>
- {Array.from({ length: 4 }, (_, index) => (
- <Skeleton.Node active key={index} style={{ height: 52, width: '100%' }} />
- ))}
- </div>
- ) : (
- <div className={styles.grid}>
- {data?.slice(0, MAX_FREQUENT_LIBRARIES).map((item) => (
- <button
- className={styles.chip}
- key={item.id}
- type={'button'}
- onClick={() => {
- setLibraryId(item.id);
- navigate(`/resource/library/${item.id}`);
- }}
- >
- <LibIcon size={18} />
- <span className={styles.name}>{item.name}</span>
- </button>
- ))}
- <button
- className={styles.createChip}
- disabled={!canCreate}
- type={'button'}
- onClick={handleCreate}
- >
- <Icon icon={PlusIcon} size={16} />
- {t('home.uploadEntries.library.title')}
- </button>
- </div>
- )}
- </Flexbox>
- );
-});
-
-FrequentLibraries.displayName = 'FrequentLibraries';
-
-export default FrequentLibraries;
diff --git a/src/features/ResourceHome/Home/Libraries.tsx b/src/features/ResourceHome/Home/Libraries.tsx
index 2dd161dcbf8..88b5856bbab 100644
--- a/src/features/ResourceHome/Home/Libraries.tsx
+++ b/src/features/ResourceHome/Home/Libraries.tsx
@@ -17,29 +17,31 @@ import { useKnowledgeBaseStore } from '@/store/library';
import SectionTitle from './SectionTitle';
const styles = createStaticStyles(({ css, cssVar }) => ({
- card: css`
+ chip: css`
cursor: pointer;
display: flex;
- flex-direction: column;
- gap: 8px;
+ gap: 10px;
+ align-items: center;
- padding: 16px;
+ min-width: 0;
+ padding-block: 14px;
+ padding-inline: 16px;
border: 1px solid ${cssVar.colorBorderSecondary};
border-radius: ${cssVar.borderRadiusLG};
text-align: start;
- background: ${cssVar.colorBgContainer};
+ background: ${cssVar.colorFillQuaternary};
transition: all 0.2s ${cssVar.motionEaseInOut};
&:hover {
border-color: ${cssVar.colorBorder};
- box-shadow: ${cssVar.boxShadowTertiary};
+ background: ${cssVar.colorFillTertiary};
}
`,
- createCard: css`
+ createChip: css`
cursor: pointer;
display: flex;
@@ -47,7 +49,8 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
align-items: center;
justify-content: center;
- min-height: 88px;
+ padding-block: 14px;
+ padding-inline: 16px;
border: 1px dashed ${cssVar.colorBorder};
border-radius: ${cssVar.borderRadiusLG};
@@ -67,18 +70,9 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
opacity: 0.5;
}
`,
- description: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 2;
-
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- `,
grid: css`
display: grid;
- grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
+ grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 12px;
`,
name: css`
@@ -92,6 +86,17 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
}));
+/**
+ * How many libraries the quick-access row shows. The list is ordered by last
+ * update, so this is "the ones you are working in"; the sidebar stays the full
+ * index, which is why the home page must not repeat every library here.
+ */
+const MAX_LIBRARIES = 9;
+
+/**
+ * Quick access to the user's libraries β€” the everyday entry point of the
+ * library home, and the page's only library list.
+ */
const Libraries = memo(() => {
const { t } = useTranslation('file');
const navigate = useWorkspaceAwareNavigate();
@@ -120,15 +125,15 @@ const Libraries = memo(() => {
<SectionTitle title={t('home.libraries')} />
{isLoading ? (
<div className={styles.grid}>
- {Array.from({ length: 3 }, (_, index) => (
- <Skeleton.Node active key={index} style={{ height: 88, width: '100%' }} />
+ {Array.from({ length: 4 }, (_, index) => (
+ <Skeleton.Node active key={index} style={{ height: 52, width: '100%' }} />
))}
</div>
) : (
<div className={styles.grid}>
- {data?.map((item) => (
+ {data?.slice(0, MAX_LIBRARIES).map((item) => (
<button
- className={styles.card}
+ className={styles.chip}
key={item.id}
type={'button'}
onClick={() => {
@@ -136,15 +141,12 @@ const Libraries = memo(() => {
navigate(`/resource/library/${item.id}`);
}}
>
- <Flexbox horizontal align={'center'} gap={8}>
- <LibIcon size={18} />
- <span className={styles.name}>{item.name}</span>
- </Flexbox>
- {item.description && <span className={styles.description}>{item.description}</span>}
+ <LibIcon size={18} />
+ <span className={styles.name}>{item.name}</span>
</button>
))}
<button
- className={styles.createCard}
+ className={styles.createChip}
disabled={!canCreate}
type={'button'}
onClick={handleCreate}
diff --git a/src/features/ResourceHome/Home/index.tsx b/src/features/ResourceHome/Home/index.tsx
index 155100e8c96..5d5b7f8368a 100644
--- a/src/features/ResourceHome/Home/index.tsx
+++ b/src/features/ResourceHome/Home/index.tsx
@@ -8,7 +8,6 @@ import { useTranslation } from 'react-i18next';
import NavHeader from '@/features/NavHeader';
import AddButton from '@/features/ResourceManager/components/Header/AddButton';
-import FrequentLibraries from './FrequentLibraries';
import Libraries from './Libraries';
import RecentFiles from './RecentFiles';
import RecentPages from './RecentPages';
@@ -29,9 +28,9 @@ const styles = createStaticStyles(({ css }) => ({
}));
/**
- * The library-style landing page of /resource: quick library access, then
- * works β†’ recent pages β†’ libraries β†’ recent files β€” instead of the flat
- * all-files table (which now lives at /resource/all).
+ * The library-style landing page of /resource: libraries (once β€” the sidebar
+ * holds the full index), then works β†’ recent pages β†’ recent files, instead of
+ * the flat all-files table (which now lives at /resource/all).
*/
const ResourceHomeDashboard = memo(() => {
const { t } = useTranslation('file');
@@ -45,10 +44,9 @@ const ResourceHomeDashboard = memo(() => {
/>
<div className={styles.scroll}>
<Flexbox className={styles.content} gap={40}>
- <FrequentLibraries />
+ <Libraries />
<RecentWorks />
<RecentPages />
- <Libraries />
<RecentFiles />
</Flexbox>
</div>
diff --git a/src/features/ResourceHome/Layout/Header/CategoryMenu.tsx b/src/features/ResourceHome/Layout/Header/CategoryMenu.tsx
index b408a6985da..ac319d202e7 100644
--- a/src/features/ResourceHome/Layout/Header/CategoryMenu.tsx
+++ b/src/features/ResourceHome/Layout/Header/CategoryMenu.tsx
@@ -8,7 +8,6 @@ import {
FileText,
HouseIcon,
ImageIcon,
- LayoutPanelTopIcon,
type LucideIcon,
Mic2,
SquarePlay,
@@ -44,9 +43,11 @@ const CategoryMenu = memo(() => {
// workspace prefix.
const worksActive = location.pathname.endsWith('/resource/works');
- // Two groups below the fixed Home/All entries: file-based categories
- // (uploaded files by type) and LobeHub business entities (pages, works,
- // webpages), separated by a gap.
+ // Two groups below the fixed Home entry: file-based categories (uploaded
+ // files by type) and LobeHub business entities (pages, works, webpages),
+ // separated by a gap. The flat everything-list stays reachable at
+ // /resource/all (the home page's "view all" target) but is not a nav entry β€”
+ // browsing starts from a category, not from an undifferentiated pile.
const groups = useMemo(
() => [
[
@@ -56,12 +57,6 @@ const CategoryMenu = memo(() => {
title: t('tab.home'),
url: '/resource',
},
- {
- icon: LayoutPanelTopIcon,
- key: FilesTabs.All,
- title: t('tab.all'),
- url: '/resource/all',
- },
],
// file-based categories β€” Files (the misc raw-data bucket) sits last
[
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/ImageFileItem.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/ImageFileItem.tsx
index 67d07c64321..1fea6219700 100644
--- a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/ImageFileItem.tsx
+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/ImageFileItem.tsx
@@ -1,19 +1,30 @@
-import { Flexbox, stopPropagation, Tooltip } from '@lobehub/ui';
+import { Icon, stopPropagation, Tooltip } from '@lobehub/ui';
import { Button } from '@lobehub/ui/base-ui';
import { Image } from 'antd';
-import { createStaticStyles, cx } from 'antd-style';
+import { createStaticStyles, cx, keyframes } from 'antd-style';
import { isNull } from 'es-toolkit/compat';
-import { FileBoxIcon } from 'lucide-react';
-import { memo, useState } from 'react';
+import { FileBoxIcon, ImageIcon } from 'lucide-react';
+import { memo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import FileIcon from '@/components/FileIcon';
import { fileManagerSelectors, useFileStore } from '@/store/file';
import { type AsyncTaskStatus, type IAsyncTaskError } from '@/types/asyncTask';
import { formatSize } from '@/utils/format';
import { isChunkingUnsupported } from '@/utils/isChunkingUnsupported';
import ChunksBadge from '../../ListView/ListItem/ChunkTag';
+import { FALLBACK_ASPECT_RATIO, readAspectRatio } from './imageAspectRatio';
+
+const pulse = keyframes`
+ 0%,
+ 100% {
+ opacity: 1;
+ }
+
+ 50% {
+ opacity: 0.5;
+ }
+`;
const styles = createStaticStyles(({ css, cssVar }) => ({
floatingChunkBadge: css`
@@ -54,31 +65,12 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
imageWrapper: css`
position: relative;
- display: flex;
- align-items: center;
- justify-content: center;
+ container-type: size;
+ overflow: hidden;
width: 100%;
- min-height: 120px;
background: ${cssVar.colorFillQuaternary};
-
- img {
- display: block;
- height: auto;
- }
- `,
- name: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 2;
-
- margin-block-end: 12px;
-
- font-weight: ${cssVar.fontWeightStrong};
- color: ${cssVar.colorText};
- word-break: break-word;
`,
overlaySize: css`
font-size: 12px;
@@ -100,6 +92,66 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
text-align: center;
word-break: break-word;
`,
+ /**
+ * Quiet stand-in for the bitmap: a tinted box with a muted glyph, not a
+ * file-type badge β€” a thumbnail that hasn't arrived should read as "picture
+ * on its way", not as a document card. A failure says so in words; a
+ * crossed-out glyph alone leaves the viewer guessing what it is accusing the
+ * file of.
+ */
+ placeholder: css`
+ position: absolute;
+ inset: 0;
+
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ align-items: center;
+ justify-content: center;
+
+ padding-inline: 16px;
+
+ color: ${cssVar.colorTextQuaternary};
+ `,
+ placeholderLoading: css`
+ animation: ${pulse} 1.5s ease-in-out infinite;
+ `,
+ /**
+ * One line only: the box is sized by the image's aspect ratio, so a wide, short
+ * card has no room for a wrapping name β€” a second line gets clipped mid-glyph,
+ * which looks more broken than the failure it is explaining.
+ */
+ placeholderName: css`
+ overflow: hidden;
+
+ max-width: 100%;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextQuaternary};
+ text-align: center;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+
+ @container (max-height: 92px) {
+ display: none;
+ }
+ `,
+ /**
+ * The card's height is dictated by the image's aspect ratio, so a wide, short
+ * box cannot hold the whole stack. Drop the decoration before the words: the
+ * glyph goes first, the explanation is the last thing to leave.
+ */
+ placeholderIcon: css`
+ @container (max-height: 56px) {
+ display: none;
+ }
+ `,
+ placeholderReason: css`
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ text-align: center;
+ `,
}));
interface ImageFileItemProps {
@@ -112,6 +164,7 @@ interface ImageFileItemProps {
finishEmbedding?: boolean;
id: string;
isInView: boolean;
+ metadata?: Record<string, any> | null;
name: string;
size: number;
url?: string;
@@ -128,44 +181,57 @@ const ImageFileItem = memo<ImageFileItemProps>(
finishEmbedding,
id,
isInView,
+ metadata,
name,
size,
url,
}) => {
const { t } = useTranslation('components');
- const [imageLoaded, setImageLoaded] = useState(false);
+ const wrapperRef = useRef<HTMLDivElement>(null);
+ const knownAspectRatio = readAspectRatio(metadata);
+ const [status, setStatus] = useState<'loading' | 'loaded' | 'error'>('loading');
+ // Falls back to a reserved box until the bitmap reports its own ratio.
+ const [aspectRatio, setAspectRatio] = useState(knownAspectRatio ?? FALLBACK_ASPECT_RATIO);
const [isCreatingFileParseTask, parseFiles] = useFileStore((s) => [
fileManagerSelectors.isCreatingFileParseTask(id)(s),
s.parseFilesToChunks,
]);
const isSupportedForChunking = !isChunkingUnsupported(fileType || '');
+ const imageLoaded = status === 'loaded';
+
+ /**
+ * Read the bitmap through the wrapper rather than the load event: antd's
+ * `Image` renders the `<img>` inside its own wrapper, so the event's
+ * `currentTarget` is not the image and `naturalWidth` reads back undefined.
+ * Silently skipping the correction left every upload with no stored
+ * dimensions parked on the fallback ratio β€” and `object-fit: cover` then
+ * cropped the thumbnail to a box the image never had.
+ */
+ const applyNaturalRatio = () => {
+ const img = wrapperRef.current?.querySelector('img');
+ if (img && img.naturalWidth > 0 && img.naturalHeight > 0) {
+ setAspectRatio(img.naturalWidth / img.naturalHeight);
+ }
+ };
return (
<>
- <div className={styles.imageWrapper}>
+ <div className={styles.imageWrapper} ref={wrapperRef} style={{ aspectRatio }}>
{!imageLoaded && (
- <Flexbox
- align={'center'}
- gap={12}
- justify={'center'}
- paddingBlock={24}
- paddingInline={12}
+ <div
+ className={cx(styles.placeholder, status === 'loading' && styles.placeholderLoading)}
>
- <FileIcon fileName={name} fileType={fileType} size={48} />
- <div className={styles.name} style={{ textAlign: 'center' }}>
- {name}
- </div>
- <div
- style={{
- color: 'var(--lobe-chat-text-tertiary)',
- fontSize: 12,
- textAlign: 'center',
- }}
- >
- {formatSize(size)}
- </div>
- </Flexbox>
+ <Icon className={styles.placeholderIcon} icon={ImageIcon} size={28} />
+ {status === 'error' && (
+ <>
+ <div className={styles.placeholderReason}>
+ {t('FileManager.image.loadFailed')}
+ </div>
+ <div className={styles.placeholderName}>{name}</div>
+ </>
+ )}
+ </div>
)}
{isInView && url && (
<Image
@@ -177,19 +243,25 @@ const ImageFileItem = memo<ImageFileItemProps>(
}}
style={{
display: 'block',
- height: 'auto',
+ height: '100%',
+ objectFit: 'cover',
opacity: imageLoaded ? 1 : 0,
transition: 'opacity 0.3s',
width: '100%',
}}
wrapperStyle={{
- inset: 0,
+ display: 'block',
+ height: '100%',
pointerEvents: imageLoaded ? 'auto' : 'none',
- position: imageLoaded ? 'relative' : 'absolute',
width: '100%',
}}
- onError={() => setImageLoaded(false)}
- onLoad={() => setImageLoaded(true)}
+ onError={() => setStatus('error')}
+ onLoad={() => {
+ // Trust the bitmap over the stored metadata: a wrong stored
+ // ratio would crop the thumbnail for good.
+ applyNaturalRatio();
+ setStatus('loaded');
+ }}
/>
)}
{/* Hover overlay - only show when image is loaded */}
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/imageAspectRatio.test.ts b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/imageAspectRatio.test.ts
new file mode 100644
index 00000000000..ab5e624f3b1
--- /dev/null
+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/imageAspectRatio.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest';
+
+import { FALLBACK_ASPECT_RATIO, readAspectRatio } from './imageAspectRatio';
+
+describe('readAspectRatio', () => {
+ it('uses the ratio recorded at upload time', () => {
+ expect(readAspectRatio({ height: 400, ratio: 2, width: 800 })).toBe(2);
+ });
+
+ it('derives the ratio from width / height when `ratio` is missing', () => {
+ expect(readAspectRatio({ height: 400, width: 800 })).toBe(2);
+ });
+
+ it('returns undefined for uploads with no usable dimensions', () => {
+ // CLI / desktop / public-API uploads and pre-rollout rows: the card has to
+ // fall back to the reserved box instead of collapsing to zero height.
+ expect(readAspectRatio(undefined)).toBeUndefined();
+ expect(readAspectRatio(null)).toBeUndefined();
+ expect(readAspectRatio({ date: '2026-08-09' })).toBeUndefined();
+ expect(readAspectRatio({ height: 0, width: 800 })).toBeUndefined();
+ expect(readAspectRatio({ height: -400, width: 800 })).toBeUndefined();
+ expect(readAspectRatio({ height: 'tall', width: 'wide' })).toBeUndefined();
+ });
+
+ it('ignores a non-positive stored ratio and falls back to the dimensions', () => {
+ expect(readAspectRatio({ height: 400, ratio: 0, width: 800 })).toBe(2);
+ });
+
+ it('keeps a landscape default so unmeasured cards read as image slots', () => {
+ expect(FALLBACK_ASPECT_RATIO).toBeGreaterThan(1);
+ });
+});
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/imageAspectRatio.ts b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/imageAspectRatio.ts
new file mode 100644
index 00000000000..53349974364
--- /dev/null
+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/imageAspectRatio.ts
@@ -0,0 +1,26 @@
+/**
+ * Box reserved for a thumbnail whose dimensions we don't know yet. Any value
+ * shifts once when the real bitmap lands, but a reserved box keeps the masonry
+ * columns from collapsing and re-flowing while the images stream in.
+ */
+export const FALLBACK_ASPECT_RATIO = 4 / 3;
+
+/**
+ * Aspect ratio recorded at upload time (`FileMetadataSchema`: width / height /
+ * ratio), which keeps an image card at its final size from the first paint.
+ * Uploads that never measured the bitmap β€” CLI, desktop, public API, anything
+ * older than the metadata rollout β€” return `undefined` and fall back to
+ * {@link FALLBACK_ASPECT_RATIO}.
+ */
+export const readAspectRatio = (metadata?: Record<string, any> | null): number | undefined => {
+ const ratio = Number(metadata?.ratio);
+ if (Number.isFinite(ratio) && ratio > 0) return ratio;
+
+ const width = Number(metadata?.width);
+ const height = Number(metadata?.height);
+
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0)
+ return undefined;
+
+ return width / height;
+};
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx
index 137f43451c6..9fc04aaf36a 100644
--- a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx
@@ -476,6 +476,7 @@ const MasonryFileItem = memo<MasonryFileItemProps>(
finishEmbedding={finishEmbedding}
id={chunkTargetId}
isInView={isInView}
+ metadata={metadata}
name={name}
size={size}
url={url}