🤯 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: add product-origin artifact share page (#18569)
Inneia5e0f569b173
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.tsindex 56a9ff458fb..0e18fc8cd8d 100644--- a/apps/server/src/routers/lambda/index.ts+++ b/apps/server/src/routers/lambda/index.ts@@ -2,6 +2,7 @@* This file contains the root router of Lobe Chat tRPC-backend*/import { accountDeletionRouter } from '@/business/server/lambda-routers/accountDeletion';+import { artifactShareRouter } from '@/business/server/lambda-routers/artifactShare';import { pageShareRouter } from '@/business/server/lambda-routers/pageShare';import { referralRouter } from '@/business/server/lambda-routers/referral';import { spendRouter } from '@/business/server/lambda-routers/spend';@@ -181,6 +182,7 @@ export const lambdaRouter = router({workspaceUsage: workspaceUsageRouter,workspaceUserSettings: workspaceUserSettingsRouter,accountDeletion: accountDeletionRouter,+ artifactShare: artifactShareRouter,pageShare: pageShareRouter,referral: referralRouter,spend: spendRouter,diff --git a/apps/share/app/lib/seo.ts b/apps/share/app/lib/seo.tsindex bd9909ec2fd..90a3fed268b 100644--- a/apps/share/app/lib/seo.ts+++ b/apps/share/app/lib/seo.ts@@ -7,9 +7,10 @@ import type { MetaDescriptor } from 'react-router';const OG_IMAGE_URL = 'https://lobehub.com/assets/cao-og.webp';const TWITTER_SITE = '@lobehub';-type DescriptionKey = 'pageDescription' | 'topicDescription';+type DescriptionKey = 'artifactDescription' | 'pageDescription' | 'topicDescription';const FALLBACK_DESCRIPTION: Record<DescriptionKey, string> = {+ artifactDescription: `An artifact shared from ${BRANDING_NAME}.`,pageDescription: `A page shared from ${BRANDING_NAME}.`,topicDescription: `A conversation shared from ${BRANDING_NAME}.`,};diff --git a/apps/share/app/routes.ts b/apps/share/app/routes.tsindex 5aa41ddd637..d2168087dce 100644--- a/apps/share/app/routes.ts+++ b/apps/share/app/routes.ts@@ -4,5 +4,6 @@ export default [index('routes/homeRedirect.tsx'),route('share/t/:id', 'routes/shareTopic.tsx'),route('share/page/:id', 'routes/sharePage.tsx'),+ route('share/artifact/:id', 'routes/shareArtifact.tsx'),route('*', 'routes/catchall.tsx'),] satisfies RouteConfig;diff --git a/apps/share/app/routes/shareArtifact.tsx b/apps/share/app/routes/shareArtifact.tsxnew file mode 100644index 00000000000..4878226cb55--- /dev/null+++ b/apps/share/app/routes/shareArtifact.tsx@@ -0,0 +1,58 @@+import { BRANDING_NAME } from '@lobechat/business-const';+import type { LoaderFunctionArgs, MetaFunction } from 'react-router';+import { useLoaderData } from 'react-router';+import { SWRConfig, unstable_serialize } from 'swr';++import { shareKeys } from '@/libs/swr/keys';+import { resolveRequestLocale } from '@/locales/requestLocale';++import SharedArtifactView from '../../src/features/artifact/SharedArtifactView';+import { loadShareResources } from '../../src/shell/createShareI18n';+import { cloudflareContext } from '../lib/cloudflareContext';+import { buildPageMeta, shareMetaDescription } from '../lib/seo';+import { createServerLambdaClient } from '../lib/serverTrpc';++export const loader = async ({ context, params, request }: LoaderFunctionArgs) => {+ const id = params.id!;+ const locale = resolveRequestLocale(request);+ const apiBase = context.get(cloudflareContext).env.SHARE_API_BASE as string | undefined;++ const artifact = await createServerLambdaClient(request, apiBase)+ .artifactShare.getShared.query({ id })+ .catch((error) => {+ console.error('[share] shared artifact SSR fetch failed:', error);+ return null;+ });++ return {+ artifact,+ description: shareMetaDescription(await loadShareResources(locale), 'artifactDescription'),+ id,+ locale,+ };+};++export const meta: MetaFunction<typeof loader> = ({ loaderData }) => {+ const title = loaderData?.artifact?.title;++ return buildPageMeta({+ description: loaderData?.description ?? '',+ locale: loaderData?.locale,+ title: title ? `${title} · ${BRANDING_NAME}` : BRANDING_NAME,+ type: 'website',+ });+};++export default function ShareArtifactRoute() {+ const { artifact, id } = useLoaderData<typeof loader>();++ return (+ <SWRConfig+ value={{+ fallback: artifact ? { [unstable_serialize(shareKeys.artifact(id))]: artifact } : {},+ }}+ >+ <SharedArtifactView />+ </SWRConfig>+ );+}diff --git a/apps/share/src/features/artifact/ArtifactShareChrome.tsx b/apps/share/src/features/artifact/ArtifactShareChrome.tsxnew file mode 100644index 00000000000..99b86292305--- /dev/null+++ b/apps/share/src/features/artifact/ArtifactShareChrome.tsx@@ -0,0 +1,76 @@+'use client';++import { copyToClipboard, Flexbox, Text } from '@lobehub/ui';+import { Button, toast } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';+import { useTranslation } from 'react-i18next';++import { ProductLogo } from '@/components/Branding';++const styles = createStaticStyles(({ css, cssVar }) => ({+ header: css`+ flex-shrink: 0;++ height: 48px;+ padding-inline: 12px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};++ background: ${cssVar.colorBgContainer};+ `,+ logo: css`+ display: flex;+ color: inherit;+ `,+ title: css`+ min-width: 0;+ `,+}));++interface ArtifactShareChromeProps {+ title?: string | null;+}++export const ArtifactShareChrome = ({ title }: ArtifactShareChromeProps) => {+ const { t } = useTranslation('chat');++ const handleShare = async () => {+ await copyToClipboard(window.location.href);+ toast.success(t('shareModal.copyLinkSuccess'));+ };++ return (+ <Flexbox+ horizontal+ align={'center'}+ className={styles.header}+ gap={12}+ justify={'space-between'}+ >+ <Flexbox horizontal align={'center'} flex={1} style={{ minWidth: 0 }}>+ <a className={styles.logo} href={'/'}>+ <ProductLogo size={28} />+ </a>+ </Flexbox>+ <Flexbox flex={2} style={{ minWidth: 0 }}>+ <Text+ ellipsis+ strong+ align={'center'}+ className={styles.title}+ fontSize={14}+ style={{ margin: 0 }}+ >+ {title}+ </Text>+ </Flexbox>+ <Flexbox horizontal align={'center'} flex={1} gap={8} justify={'flex-end'}>+ <Button shape={'round'} size={'small'} onClick={handleShare}>+ {t('sharePage.artifact.share')}+ </Button>+ <Button href={'/'} shape={'round'} size={'small'}>+ {t('sharePage.menu.goToLobeHub')}+ </Button>+ </Flexbox>+ </Flexbox>+ );+};diff --git a/apps/share/src/features/artifact/SharedArtifactView.tsx b/apps/share/src/features/artifact/SharedArtifactView.tsxnew file mode 100644index 00000000000..c2d4ded04a2--- /dev/null+++ b/apps/share/src/features/artifact/SharedArtifactView.tsx@@ -0,0 +1,81 @@+'use client';++import { Center } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { useParams } from 'react-router';+import useSWR from 'swr';++import Loading from '@/components/Loading/BrandTextLoading';+import ShareErrorView from '@/features/Share/ErrorView';+import { shareKeys } from '@/libs/swr/keys';+import { lambdaClient } from '@/libs/trpc/client';++import { ArtifactShareChrome } from './ArtifactShareChrome';++const styles = createStaticStyles(({ css, cssVar }) => ({+ frame: css`+ width: 100%;+ height: 100%;+ border: 0;+ background: ${cssVar.colorBgLayout};+ `,+ root: css`+ display: flex;+ flex-direction: column;++ width: 100%;+ height: 100dvh;++ background: ${cssVar.colorBgLayout};+ `,+ stage: css`+ overflow: hidden;+ flex: 1;+ `,+}));++const SharedArtifactView = () => {+ const { id } = useParams<{ id: string }>();++ const { data, error, isLoading } = useSWR(+ id ? shareKeys.artifact(id) : null,+ () => lambdaClient.artifactShare.getShared.query({ id: id! }),+ { revalidateOnFocus: false },+ );++ if (!error && !data && isLoading) {+ return (+ <Center height={'100dvh'}>+ <Loading debugId="SharedArtifactView" />+ </Center>+ );+ }++ if (error || !data) {+ return (+ <div className={styles.root}>+ <ArtifactShareChrome />+ <div className={styles.stage}>+ <ShareErrorView error={error} />+ </div>+ </div>+ );+ }++ return (+ <div className={styles.root}>+ <ArtifactShareChrome title={data.title} />+ <div className={styles.stage}>+ <iframe+ className={styles.frame}+ referrerPolicy={'no-referrer'}+ sandbox={'allow-scripts'}+ src={data.iframeSrc}+ title={data.title ?? 'Artifact'}+ />+ </div>+ </div>+ );+};++export default SharedArtifactView;diff --git a/apps/share/src/router.tsx b/apps/share/src/router.tsxindex 0062c5fb46f..c6611638186 100644--- a/apps/share/src/router.tsx+++ b/apps/share/src/router.tsx@@ -80,6 +80,10 @@ export const shareRoutes: RouteObject[] = [element: lazyElement(() => import('./features/page/SharedPageView')),path: 'share/page/:id',},+ {+ element: lazyElement(() => import('./features/artifact/SharedArtifactView')),+ path: 'share/artifact/:id',+ },{element: <ExitShare />,path: '*',diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 4a9eefcdfb2..979e8f393ec 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1264,6 +1264,7 @@"shareModal.withRole": "Include Message Role","shareModal.withSystemRole": "Include Agent Profile","sharePage.actions.tryItYourself": "Try it yourself",+ "sharePage.artifact.share": "Share","sharePage.error.forbidden.subtitle": "This share is private and not accessible.","sharePage.error.forbidden.title": "Access Denied","sharePage.error.notFound.subtitle": "This topic does not exist or has been removed.",@@ -1275,6 +1276,7 @@"sharePage.menu.goToLobeHub": "Go to LobeHub","sharePage.menu.more": "More","sharePage.menu.report": "Report",+ "sharePage.meta.artifactDescription": "An artifact shared from {{appName}}.","sharePage.meta.pageDescription": "A page shared from {{appName}}.","sharePage.meta.topicDescription": "A conversation shared from {{appName}}.","sharePage.pill.edit": "Edit",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 5ead5d4390b..70a6c5b89de 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1264,6 +1264,7 @@"shareModal.withRole": "包含消息角色","shareModal.withSystemRole": "包含助理档案","sharePage.actions.tryItYourself": "做同款",+ "sharePage.artifact.share": "分享","sharePage.error.forbidden.subtitle": "此分享为私密状态,无法访问。","sharePage.error.forbidden.title": "无权访问","sharePage.error.notFound.subtitle": "该话题不存在或已被删除。",@@ -1275,6 +1276,7 @@"sharePage.menu.goToLobeHub": "前往 LobeHub","sharePage.menu.more": "更多","sharePage.menu.report": "举报",+ "sharePage.meta.artifactDescription": "分享自 {{appName}} 的 Artifact。","sharePage.meta.pageDescription": "分享自 {{appName}} 的页面。","sharePage.meta.topicDescription": "分享自 {{appName}} 的对话。","sharePage.pill.edit": "编辑",diff --git a/packages/business-server/src/lambda-routers/artifactShare.ts b/packages/business-server/src/lambda-routers/artifactShare.tsnew file mode 100644index 00000000000..8a84f881d70--- /dev/null+++ b/packages/business-server/src/lambda-routers/artifactShare.ts@@ -0,0 +1,13 @@+import type { SharedArtifactData } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { publicProcedure, router } from '@/libs/trpc/lambda';++export const artifactShareRouter = router({+ getShared: publicProcedure+ .input(z.object({ id: z.string().min(1) }))+ .query(async (): Promise<SharedArtifactData> => {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Artifact sharing is not available' });+ }),+});diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.tsindex 9d56928d684..0ada181c788 100644--- a/packages/const/src/apiKeyScope.ts+++ b/packages/const/src/apiKeyScope.ts@@ -188,6 +188,7 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRule// keys must not mint or manage keysapiKey: 'blocked',asr: { any: 'model:invoke' },+ artifactShare: rw('chat:read', null),// decrypts stored bot/messenger credentials and calls external channel APIsbotMessage: 'blocked',brief: rw('chat:read', 'chat:write'),diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex f949bdadd52..5f758fa412c 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1325,6 +1325,7 @@ export default {'shareModal.withRole': 'Include Message Role','shareModal.withSystemRole': 'Include Agent Profile','sharePage.actions.tryItYourself': 'Try it yourself',+ 'sharePage.artifact.share': 'Share','sharePage.error.forbidden.subtitle': 'This share is private and not accessible.','sharePage.error.forbidden.title': 'Access Denied','sharePage.error.notFound.subtitle': 'This topic does not exist or has been removed.',@@ -1336,6 +1337,7 @@ export default {'sharePage.menu.goToLobeHub': 'Go to LobeHub','sharePage.menu.more': 'More','sharePage.menu.report': 'Report',+ 'sharePage.meta.artifactDescription': 'An artifact shared from {{appName}}.','sharePage.meta.pageDescription': 'A page shared from {{appName}}.','sharePage.meta.topicDescription': 'A conversation shared from {{appName}}.','sharePage.pill.edit': 'Edit',diff --git a/packages/types/src/artifact.ts b/packages/types/src/artifact.tsindex b4a0037ca69..e312b983b91 100644--- a/packages/types/src/artifact.ts+++ b/packages/types/src/artifact.ts@@ -13,3 +13,9 @@ export enum ArtifactType {Python = 'python',React = 'application/lobe.artifacts.react',}++export interface SharedArtifactData {+ id: string;+ iframeSrc: string;+ title: string | null;+}diff --git a/src/features/Portal/LocalFile/publishWorkspaceHtmlArtifact.test.ts b/src/features/Portal/LocalFile/publishWorkspaceHtmlArtifact.test.tsindex b8762a82cd1..f2b1334e7b4 100644--- a/src/features/Portal/LocalFile/publishWorkspaceHtmlArtifact.test.ts+++ b/src/features/Portal/LocalFile/publishWorkspaceHtmlArtifact.test.ts@@ -18,6 +18,7 @@ describe('publishWorkspaceHtmlArtifact', () => {}),);const publishArtifact = vi.fn(async () => ({+ id: 'dep_1',latestRevisionNumber: 2,publicUrl: 'https://example.lobehub.com/page',}));@@ -48,6 +49,7 @@ describe('publishWorkspaceHtmlArtifact', () => {);expect(result).toEqual({+ id: 'dep_1',publicUrl: 'https://example.lobehub.com/page',revision: 2,});diff --git a/src/features/Portal/LocalFile/publishWorkspaceHtmlArtifact.ts b/src/features/Portal/LocalFile/publishWorkspaceHtmlArtifact.tsindex 7319455a098..d26a8a78083 100644--- a/src/features/Portal/LocalFile/publishWorkspaceHtmlArtifact.ts+++ b/src/features/Portal/LocalFile/publishWorkspaceHtmlArtifact.ts@@ -41,10 +41,10 @@ export const publishWorkspaceHtmlArtifact = async (messageId: string;requestedSlug?: string;topicId: string;- }) => Promise<{ latestRevisionNumber?: number; publicUrl?: string }>;+ }) => Promise<{ id?: string; latestRevisionNumber?: number; publicUrl?: string }>;publishSite?: (params: PublishWorkspaceHtmlSiteParams,- ) => Promise<{ latestRevisionNumber?: number; publicUrl?: string }>;+ ) => Promise<{ id?: string; latestRevisionNumber?: number; publicUrl?: string }>;},): Promise<WorkspaceHtmlArtifactPublishResult> => {if (!input.agentId) {@@ -81,6 +81,7 @@ export const publishWorkspaceHtmlArtifact = async (});return {+ id: deployment.id,publicUrl: deployment.publicUrl,revision: deployment.latestRevisionNumber,};@@ -105,6 +106,7 @@ export const publishWorkspaceHtmlArtifact = async (});return {+ id: deployment.id,publicUrl: deployment.publicUrl,revision: deployment.latestRevisionNumber,};diff --git a/src/features/Portal/LocalFile/workspaceHtmlArtifact.ts b/src/features/Portal/LocalFile/workspaceHtmlArtifact.tsindex 9de53e8a3f9..1c8209a4726 100644--- a/src/features/Portal/LocalFile/workspaceHtmlArtifact.ts+++ b/src/features/Portal/LocalFile/workspaceHtmlArtifact.ts@@ -16,6 +16,7 @@ export interface WorkspaceHtmlArtifactPublishInput {}export interface WorkspaceHtmlArtifactExisting {+ id?: string;identifier: string;publicUrl?: string;revision?: number;@@ -23,6 +24,7 @@ export interface WorkspaceHtmlArtifactExisting {}export interface WorkspaceHtmlArtifactPublishResult {+ id?: string;publicUrl?: string;revision?: number;}diff --git a/src/libs/next/proxy/define-config.test.ts b/src/libs/next/proxy/define-config.test.tsindex 6e6ac30426a..3fdc9138bbb 100644--- a/src/libs/next/proxy/define-config.test.ts+++ b/src/libs/next/proxy/define-config.test.ts@@ -97,10 +97,12 @@ describe('defineConfig Share SPA rewrite', () => {);const desktopTopic = await run('http://localhost:3010/share/t/topic-1?hl=en-US');const desktopPage = await run('http://localhost:3010/share/page/docs_1?hl=en-US');+ const desktopArtifact = await run('http://localhost:3010/share/artifact/42?hl=en-US');expect(new URL(mobileTopic!).pathname).toBe('/spa-share/en-US/share/t/topic-1');expect(new URL(desktopTopic!).pathname).toBe('/spa-share/en-US/share/t/topic-1');expect(new URL(desktopPage!).pathname).toBe('/spa-share/en-US/share/page/docs_1');+ expect(new URL(desktopArtifact!).pathname).toBe('/spa-share/en-US/share/artifact/42');});it('leaves non-share paths that merely start with the prefix in the main SPA', async () => {diff --git a/src/libs/next/shareRoutes.test.ts b/src/libs/next/shareRoutes.test.tsindex 6ef86ffe0e6..45a295b7f7e 100644--- a/src/libs/next/shareRoutes.test.ts+++ b/src/libs/next/shareRoutes.test.ts@@ -3,17 +3,22 @@ import { describe, expect, it } from 'vitest';import { isShareSpaRoute } from './shareRoutes';describe('isShareSpaRoute', () => {- it.each(['/share/t/abc', '/share/t/abc/', '/share/page/docs_1', '/share/t/abc?hl=zh-CN'])(- 'matches %s',- (pathname) => {- expect(isShareSpaRoute(pathname)).toBe(true);- },- );+ it.each([+ '/share/t/abc',+ '/share/t/abc/',+ '/share/page/docs_1',+ '/share/t/abc?hl=zh-CN',+ '/share/artifact/42',+ '/share/artifact/42/',+ ])('matches %s', (pathname) => {+ expect(isShareSpaRoute(pathname)).toBe(true);+ });it.each(['/share','/share/','/share/t',+ '/share/artifact','/share/t/abc/extra','/shared/t/abc','/chat',diff --git a/src/libs/next/shareRoutes.ts b/src/libs/next/shareRoutes.tsindex 574f68c7b4a..5d4fd91b23a 100644--- a/src/libs/next/shareRoutes.ts+++ b/src/libs/next/shareRoutes.ts@@ -1,5 +1,6 @@const SHARE_TOPIC_ROUTE = /^\/share\/t\/[^/]+\/?$/;const SHARE_PAGE_ROUTE = /^\/share\/page\/[^/]+\/?$/;+const SHARE_ARTIFACT_ROUTE = /^\/share\/artifact\/[^/]+\/?$/;const pathOnly = (pathname: string) => pathname.split(/[?#]/, 1)[0]!;@@ -7,5 +8,7 @@ const pathOnly = (pathname: string) => pathname.split(/[?#]/, 1)[0]!;export const isShareSpaRoute = (pathname: string): boolean => {const path = pathOnly(pathname);- return SHARE_TOPIC_ROUTE.test(path) || SHARE_PAGE_ROUTE.test(path);+ return (+ SHARE_TOPIC_ROUTE.test(path) || SHARE_PAGE_ROUTE.test(path) || SHARE_ARTIFACT_ROUTE.test(path)+ );};diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 117b49ee36a..bdef3dab485 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -1038,6 +1038,7 @@ export const inboxKeys = {// ---- share (shared topic / page) ----------------------------------------export const shareKeys = {+ artifact: def('share:artifact', (id: string) => ['share:artifact', id]),pageDocument: def('share:pageDocument', (documentId: string) => ['share:pageDocument',documentId,diff --git a/src/utils/artifactShare.test.ts b/src/utils/artifactShare.test.tsnew file mode 100644index 00000000000..75925e38094--- /dev/null+++ b/src/utils/artifactShare.test.ts@@ -0,0 +1,15 @@+import { describe, expect, it } from 'vitest';++import { artifactSharePath, artifactShareUrl } from './artifactShare';++describe('artifactShareUrl', () => {+ it('builds the product share path and URL', () => {+ expect(artifactSharePath('42')).toBe('/share/artifact/42');+ expect(artifactShareUrl('https://app.lobehub.com', '42')).toBe(+ 'https://app.lobehub.com/share/artifact/42',+ );+ expect(artifactShareUrl('https://app.lobehub.com/', '42')).toBe(+ 'https://app.lobehub.com/share/artifact/42',+ );+ });+});diff --git a/src/utils/artifactShare.ts b/src/utils/artifactShare.tsnew file mode 100644index 00000000000..dad195a95fb--- /dev/null+++ b/src/utils/artifactShare.ts@@ -0,0 +1,4 @@+export const artifactSharePath = (deploymentId: string) => `/share/artifact/${deploymentId}`;++export const artifactShareUrl = (origin: string, deploymentId: string) =>+ `${origin.replace(/\/+$/, '')}${artifactSharePath(deploymentId)}`;