π€― 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(share): extract share pages into a standalone SSR micro app (#18496)
Innei2df9829a5eb2
diff --git a/.agents/skills/split-micro-app/SKILL.md b/.agents/skills/split-micro-app/SKILL.mdindex 62a6373e49f..4d1eebcc9f8 100644--- a/.agents/skills/split-micro-app/SKILL.md+++ b/.agents/skills/split-micro-app/SKILL.md@@ -1,32 +1,59 @@---name: split-micro-app-description: 'Use when splitting a monorepo surface into a standalone micro app (React Router SSR on Cloudflare Workers), fighting SSR bundle bloat from main-src imports, deploying its assets to CDN/R2, adding SEO/OG meta to an SSR page, adding a target and route rules for it in the lobehub gateway (torii), wiring it into the OSS Docker image, or deciding whether Cloud Next should still build or rewrite it.'+description: 'Use when splitting a monorepo surface into a standalone micro app (React Router SSR on Cloudflare Workers), splitting a surface whose rendering code lives in the lobehub-cloud business overlay, fighting SSR bundle bloat from main-src imports, deploying its assets to CDN/R2, adding SEO/OG meta to an SSR page, adding a target and route rules for it in the lobehub gateway (torii), wiring it into the OSS Docker image, or deciding whether Cloud Next should still build or rewrite it.'user-invocable: false---# Micro App: Split, SSR, SEO, Gateway-Canonical living example: **`apps/workbench`** (verify/acceptance, extracted 2026-08). When-in doubt, read the real files there β this skill records the decisions and landmines, not-copies of the code.+Canonical living examples, both extracted 2026-08 β read the real files, this skill records+the decisions and landmines, not copies of the code:++- **`apps/workbench`** (`/verify`, `/acceptance`) β all code in this repo, builds and deploys from OSS CI.+- **`apps/share`** (`/share/t/:id`, `/share/page/:id`) β renders Cloud-only surfaces, so it+ builds and deploys from **lobehub-cloud** CI. See Β§1b before touching it.## HostingOne app, two serve paths. Do not mix them.-| Surface | Who serves `/verify` `/acceptance` | Build |-| ------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| Cloud | Gateway (torii) β workbench Worker | Cloud Next does **not** `build:spa:workbench`, copy `_spa-workbench`, rewrite to `/spa-workbench`, or CDN-upload that prefix |-| OSS / ει¨η½² Docker | Next in the same image | `build:docker` runs `build:spa:workbench`; `WORKBENCH_REQUIRED=1` on `generateSpaTemplates`; Dockerfile copies `apps/workbench/package.json` before `pnpm i` |+| Surface | Who serves it | Build |+| ------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Cloud | Gateway (torii) β Worker (SSR) | Cloud Next does **not** `build:spa:<name>`, copy `_spa-<name>`, rewrite to `/spa-<name>`, or CDN-upload that prefix |+| OSS / ει¨η½² Docker | Next in the same image, client-rendered | `build:docker` runs `build:spa:<name>`; `<NAME>_REQUIRED=1` on `generateSpaTemplates`; Dockerfile copies `apps/<name>/package.json` before `pnpm i` and `public/_spa-<name>` into the runtime image |++`generateSpaTemplates` skips a missing `dist/<name>` HTML unless `<NAME>_REQUIRED=1`. Cloud must skip. Docker must require.++Do not revive Cloud `SPA_TARGET=<name>` Vite builds or a `/spa-<name>` middleware rewrite.-`generateSpaTemplates` skips a missing `dist/<name>` HTML unless `WORKBENCH_REQUIRED=1`. Cloud must skip. Docker must require.+The Docker chain per app, all five links or the route is dead: root `build:docker` script β+`copySpaBuildCore.ts` target entry (`dist/<name>` β `public/_spa-<name>`) β `spaHtmlPaths.ts`+resolver + `generateSpaTemplates` block β `src/app/spa-<name>/[locale]/[[...path]]/route.ts` β+middleware rewrite (`src/libs/next/<name>Routes.ts` + `define-config.ts`) plus the path in+`src/proxy.ts`'s matcher and, for public pages, in `isPublicRoute`.-Do not revive Cloud `SPA_TARGET=workbench` Vite builds or a `/spa-workbench` middleware rewrite.+**Self-hosted loses per-page SSR.** The Next shell serves the built SPA HTML with a brand OG+card and `noindex, nofollow`; per-subject title/OG only exists in the Worker build. That is the+accepted trade, not a bug to chase.++**Dev shells β a 200 that lies.** A `/spa-<name>` handler may only call+`fetchViteDevTemplate('/index.<name>.html')` if that file exists at the repo **root** (workbench+has one; it differs from `apps/<name>/index.html` only in the entry path, which must point at+`/apps/<name>/src/entry.tsx`). Miss it and Vite's HTML fallback answers **200 with the main SPA+shell** β the micro app never loads, nothing errors, and the main SPA no longer has those routes.+An app developed against its own Vite server (share: `dev:spa:share`) carries **no dev branch at+all**. `scripts/spaDevShells.test.ts` guards both directions.## Crossing from the main SPAOnly markdown internal entity links leave the main SPA (`InternalEntityLink` β `window.location.assign` when `shouldHardNavigateToWorkbench`). `Link` and `useWorkspaceAwareNavigate` stay in-router. Electron never hard-navs (portal). Do not add a `__WORKBENCH__` Vite define β the helper keys off the path (and skips Electron).+Share needed none of this: the only producer builds an **absolute** URL for copy/open+(`${appOrigin}/share/t/${id}` in `SharePopover`), which is already a hard navigation. Before+deleting `src/routes/<x>/**`, grep for in-router links to those paths β a surviving `Link` lands+on the main SPA's 404. Then drop the routes from `desktopRouter.config.tsx` /+`mobileRouter.config.tsx` and update `desktopRouter.sync.test.tsx` + `routeScope.test.ts`.+## 1. Splitting & ArtifactsApp layout (`apps/<name>/`):@@ -49,18 +76,24 @@ tsconfig `include` must cover `app/`). Stack: `@react-router/dev@8` + `@cloudfla**SSR bundle weight is the whole battle.** Main-src imports drag the app universe(store web β chat/agent/electron). Tools and cuts, in order:-| Tool / cut | How |-| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| Trace who pulls a module | `WORKBENCH_TRACE_MODULE=store/chat/store [WORKBENCH_TRACE_ENV=client] bun run build:rr` β prints importer chain |-| Client-gate heavy routes | `.client.tsx` module + `clientOnlyRoute()` factory (hydration gate; SSR renders loading) |-| SSR-stub store hubs | vite `resolveId` stubs per env (`app/stubs/`): trpc client, services/global, store/electron, store/file, i18n loader. Stubs must be **callable empty-state hooks**, not throwing proxies β render paths call them. Keep the implemented surface explicit (no catch-all `Proxy` / `as never`): `stubSurfaceGuard` in `vite.config.rr.mts` fails the build when the graph imports an export or member the stub does not implement. Add the member (empty / `reject`) or keep the importer off the graph. |-| Client-shim lambda | Client `@/libs/trpc/client` is a cookie-only `httpLink` (`trpcClient.client.ts`). Do not ship the real `lambda.ts` β its `headers()` pulls image store β chat store + `model-bank` catalog. |-| SSR-stub shiki langs | On the SSR env, resolve `@shikijs/langs` / `@shikijs/themes` / shiki's `langs-bundle` / `themes` / wasm to `app/stubs/shiki.ts`. Do **not** stub the `shiki` package entry β Pierre diffs and Highlighter import named APIs from it. |-| Client shiki from CDN | On the client env, resolve `shiki` / `shiki/*` / `@shikijs/*` to pinned `https://esm.sh/...@<installed shiki version>` as externals. Do not bundle grammars or wasm into `build/client`. |-| Slot-inject app-only features | Context seam owned by the shared feature (see `src/features/Verify/Acceptance/originConversation.tsx`); app provides, micro app leaves null β affordances hide |-| Bypass barrels | Deep-path imports (`@/features/Verify/Acceptance`, not the barrel) β barrels evaluate sibling exports with side effects |-| Compose capability atoms | Shared UI is assembled per surface; the light app never imports the fat viewer. See **`compose-atoms`**. Do not add `readOnly` on the in-app page |-| Decouple dual-use components | Lift store reads to optional props (see AudioPlayer `uploadState`/`onCancelUpload`) |+| Tool / cut | How |+| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| Trace who pulls a module | `<APP>_TRACE_MODULE=store/chat/store [<APP>_TRACE_ENV=client] bun run build:rr` β prints importer chain (`SHARE_`/`WORKBENCH_`). In an overlay repo, run it there too (Β§1b) |+| Client-gate heavy routes | `.client.tsx` module + `clientOnlyRoute()` factory (hydration gate; SSR renders loading) |+| SSR-stub store hubs | vite `resolveId` stubs per env (`app/stubs/`): trpc client, services/global, store/electron, store/file, store/user, i18n loader. Stubs must be **callable empty-state hooks**, not throwing proxies β render paths call them. Keep the implemented surface explicit (no catch-all `Proxy` / `as never`): `stubSurfaceGuard` in `vite.config.rr.mts` fails the build when the graph imports an export or member the stub does not implement. Add the member (empty / `reject`) or keep the importer off the graph. |+| Client-shim lambda | Client `@/libs/trpc/client` is a cookie-only `httpLink` (`trpcClient.client.ts`). Do not ship the real `lambda.ts` β its `headers()` pulls image store β chat store + `model-bank` catalog. |+| SSR-stub shiki langs | On the SSR env, resolve `@shikijs/langs` / `@shikijs/themes` / shiki's `langs-bundle` / `themes` / wasm to `app/stubs/shiki.ts`. Do **not** stub the `shiki` package entry β Pierre diffs and Highlighter import named APIs from it. |+| Client shiki from CDN | On the client env, resolve `shiki` / `shiki/*` / `@shikijs/*` to pinned `https://esm.sh/...@<installed shiki version>` as externals. Do not bundle grammars or wasm into `build/client`. |+| Slot-inject app-only features | Context seam owned by the shared feature (see `src/features/Verify/Acceptance/originConversation.tsx`); app provides, micro app leaves null β affordances hide |+| Bypass barrels | Deep-path imports (`@/features/Verify/Acceptance`, not the barrel) β barrels evaluate sibling exports with side effects |+| Compose capability atoms | Shared UI is assembled per surface; the light app never imports the fat viewer. See **`compose-atoms`**. Do not add `readOnly` on the in-app page |+| Decouple dual-use components | Lift store reads to optional props (see AudioPlayer `uploadState`/`onCancelUpload`) |++Share's cuts took SSR from **9.84MB β 1.78MB gzip**. Two build-level snags worth knowing:+`resolve.dedupe` must include `@lobehub/ui` (the `builtin-tool-*` packages declare a loose `^5`+and resolve to an older copy whose base-ui lacks components the app renders β `MISSING_EXPORT:+Alert`), and a `*.client` module needs its own SSR-env stub so the hydration gate does not drag+the gated tree into the worker anyway.Products: `build/client` (assets β CDN), `build/server` (worker; deploy with`wrangler deploy --config build/server/wrangler.json`). Budget: worker gzip β€ 10MB paid.@@ -69,13 +102,61 @@ Products: `build/client` (assets β CDN), `build/server` (worker; deploy withthe deploy workflow diffs changed files against the manifest from the **last successful run'sartifact** (carry-forward on skip), plus meta triggers (app dir, plugins/vite, lockfile,tsconfig, glob dirs). New `import.meta.glob` patterns in shared code need a new meta trigger β-the one manual rule. See `apps/workbench/scripts/should-build.mjs` + `.github/workflows/deploy-workbench.yml`.+the one manual rule. See `apps/workbench/scripts/should-build.mjs` ++`.github/workflows/deploy-workbench.yml`; the overlay-hosted variant is lobehub-cloud's+`scripts/shouldBuildShare.ts` + `.github/workflows/deploy-share.yml` (Β§1b).++## 1b. When the surface renders Cloud-only code++`lobehub-cloud` includes this repo as a submodule at `lobehub/` and shadows it path-by-path+through tsconfig `paths` (`@/business/*` β `./src/business/*` then `./lobehub/src/business/*`;+`@/*` β `./src/*` then `./lobehub/src/*`). Split by **ownership**, not by which repo is handy:++| Code | Where it goes |+| ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |+| Routes, shell, SSR pipeline, worker, CDN deploy, SSR stubs of OSS modules | OSS `apps/<name>` β Docker serves the same app |+| Rendering surfaces only Cloud implements | Stays in Cloud. OSS keeps the `@/business/*` stub (`return null` / passthrough, real types); the app imports the seam |+| SSR stubs for Cloud-only store hubs | Cloud (`apps/<name>/stubs/*`), injected into the shared config |++The RR config is a **factory** so both hosts share one pipeline:+`apps/share/vite.config.shared.mts` exports+`createShareRrConfig({ appRoot, extraSsrStubs, repoRoot, resolvePlugins, staticCss })`, and the+OSS `vite.config.rr.mts` is a thin caller reading `SHARE_TSCONFIG_PROJECT` /+`SHARE_EXTRA_SSR_STUBS`. Cloud fills both in `scripts/shareApp.ts` and drives the submodule app+through `scripts/{buildShare,devShare,deployShare,shouldBuildShare}.ts`.++**Landmine β the overlay silently doesn't apply.** Vite 8's native `resolve.tsconfigPaths`+resolves against the tsconfig _nearest each importer_, so submodule files resolve through the+submodule's own tsconfig and the host overlay is lost. The build still succeeds and ships the+open-source fallback surfaces (for share: a blank page). An overlay build must use the+`vite-tsconfig-paths` **plugin** pinned to the host tsconfig and switch the native one off+(`tsconfigPaths: !resolvePlugins`). Both settings are right in their own context β native for+the standalone build, plugin for the overlay build. Verify by grepping `build-inputs.txt` for a+Cloud-only file.++**Whoever's code must be inside the artifact owns the build.** Share deploys from+lobehub-cloud (`.github/workflows/deploy-share.yml`), not OSS. Never add a deploy workflow to a+repo that can only produce the fallback.++**Cloud affected-detection needs submodule history**: a bump is a single `lobehub` entry in the+host diff, so the workflow runs `git -C lobehub fetch --unshallow` and compares the previous+submodule SHA (carried in the state artifact) before diffing against `build-inputs.txt`.++**Re-run the module trace in the Cloud build** β the overlay adds chains OSS never sees+(`ShareAppShell β @/store/serverConfig/Provider β β¦ β @/store/workspace β workspaceBootstrap β+@/store/home β @/store/chat` cost 8.2MB gzip until stubbed).++**Merge order**: OSS PR β submodule bump β Cloud PR. Until the OSS PR lands, anything deployed+from a local submodule mirror is not reproducible from any commit β say so when handing over.## 2. Deploy: CDN Assets + WorkerAssets follow the cloud convention (`resolveViteBase`): **stable prefix, no version stamp** β`VITE_CDN_BASE=https://web-assets.lobehub.com/<name>/`; content-hashed filenames make uploads-incremental and immutable. `bun run deploy` (see `apps/workbench/scripts/deploy.ts`) =+incremental and immutable. The prefix axis is the **app**, nothing else: do not invent+`<name>-oss` / `<name>-cloud` variants to separate build origins β hashed filenames already make+one prefix safe for all of them. `ASSET_S3_PUBLIC_DOMAIN` is an origin; any path segment belongs+on `ASSET_BASE_URL` instead. `bun run deploy` (see `apps/workbench/scripts/deploy.ts`) =build with CDN base β upload `build/client/assets` to R2 (`web-assets` bucket, LobeHubaccount) β `wrangler deploy`. R2 creds: 1Password Shared vault item "CI R2 - web-assets".CI injects repo secrets `ASSET_S3_*` (`ACCESS_KEY_ID`, `SECRET_ACCESS_KEY`, `BUCKET`,@@ -103,6 +184,16 @@ gateway routes API to `app` instead), and redirect `/` + unknown paths to `WORKB`buildInlineAntdStyle(cache, { styleKeys })` fallback. Non-streaming render(`await stream.allReady`) so extraction is complete.- `<html suppressHydrationWarning>` β next-themes stamps `data-theme` pre-hydration.+- **Time-dependent output must be client-gated**: relative timestamps and anything else the+ server and client compute differently belong behind a `useHydrated()`+ (`useSyncExternalStore`) check, not in the SSR pass.+- **Skeletons must not swallow SSR'd chrome**: a list that flips to a skeleton on mount blanks+ the server-rendered header with it. Render the header slot in the skeleton branch too.+- **Preload the `error` namespace**, not just the render ones. The boundary shows exactly when a+ chunk failed to load β precisely when the client can no longer fetch a dictionary β and an+ untranslated boundary prints raw keys (`error.title`β¦). Cost for share: +6.3KB gzip/document.+- **Prefilling a virtualized list**: `virtua` caches measured sizes by index, so a _truncated_+ prefill that later grows misaligns every row. Prefill the whole list or none of it.RR v8 gotchas (docs/templates still say v7):@@ -129,14 +220,19 @@ To add a micro app:1. `targets.<name>` = worker hostname (must be cross-zone, e.g. `*.workers.dev`; https).2. `targetPolicies.<name>` β `cookies` if SSR loaders need the `.lobehub.com` session- forwarded; `none` for public-only; `all` adds Authorization.+ forwarded; `none` for public-only; `all` adds Authorization. Add `"locale": "query"` when the+ app reads `?hl=` (share does).3. `rules` β first-match path prefixes (`{ "match": "/acceptance", "target": "<name>" }`).Leave `/trpc` unruled: it falls to `default` (app) so browser API calls stay same-originauthenticated. `.data` suffix is normalized before matching.4. Validate: `bun run test` in the gateway repo (invariant suite reads the mirror).5. Staging: `bun scripts/torii.ts push --env staging --expect <fp>` (needs TORII\_ACCESS\_\*),or poke staging KV directly (`wrangler kv key put --namespace-id <staging CONFIG ns>`) β- README-sanctioned. Prod writes only via the Toriiban (ι³₯ε± ηͺ) admin **Promote** button.+ README-sanctioned. Prod writes only via the Toriiban (ι³₯ε± ηͺ) admin **Promote** button:+ `torii.ts promote` prints the exact delta and refuses to write, and+ `push --env prod --confirm-prod` exists but bypasses a deliberate human gate β don't.+ Before promoting, `pull --env prod` (repo mirrors go stale β a mirror-vs-live diff is not+ drift), run the invariant suite, and re-run `verify --env staging`.6. Verify with staging debug headers: `x-torii-target` / `x-torii-decision` per request, andtest document + `.data` + unaffected routes.@@ -146,13 +242,25 @@ protocol affinity for the landing pair; it consults `resolveRule` and lets other## Checklist for a new micro app-1. Scaffold `apps/<name>` (copy workbench shapes); routes + root + entry.server + worker.-2. Build, run the module trace, cut SSR weight (gate/stub/slot/deep-import) until gzip sane.-3. Wire CDN deploy (`deploy.ts`, stable `_<name>/` prefix) + wrangler vars + redirects.-4. Loader data + SWR fallback + meta builder + i18n narrowing; verify with `/trpc`-blocked- browser run (content must survive) and view-source (SSR content + meta present).-5. Deploy worker; verify workers.dev standalone (API proxy, `/` redirect).-6. Gateway: target + policy + rules on staging KV; curl matrix with x-torii headers; promote.-7. OSS Docker: workspace `package.json` in the Dockerfile `pnpm i` layer; `build:docker`- builds the app; `WORKBENCH_REQUIRED=1` (or the new app's equivalent) on template gen.-8. Cloud Next: no Vite target, no `/spa-<name>` rewrite, no `_spa-<name>` CDN upload.+1. Decide ownership first (Β§1b): does the surface render Cloud-only code? That fixes which repo+ builds, deploys, and holds the extra SSR stubs.+2. Scaffold `apps/<name>` (copy workbench/share shapes); routes + root + entry.server + worker.+3. Build, run the module trace, cut SSR weight (gate/stub/slot/deep-import) until gzip sane β+ in the overlay repo too, if there is one.+4. Wire CDN deploy (`deploy.ts`, stable `_<name>/` prefix) + wrangler vars + redirects.+5. Loader data + SWR fallback + meta builder + i18n narrowing (+ `error`); verify with+ `/trpc`-blocked browser run (content must survive) and view-source (SSR content + meta present).+6. Deploy worker; verify workers.dev standalone (API proxy, `/` redirect).+7. Gateway: target + policy + rules on staging KV; curl matrix with x-torii headers; promote.+8. OSS Docker: all five links in the Hosting section, plus the removal sweep from the main SPA.+9. Cloud Next: no Vite target, no `/spa-<name>` rewrite, no `_spa-<name>` CDN upload.++## Verifying, before you tell anyone it works++Build success proves nothing about what rendered. Each of these produced a real defect that a+green build hid: the overlay resolving to OSS stubs, the dev shell answering 200 with the wrong+app, an edit that silently no-op'd because the anchor string had drifted (deployed a 500 β+so: build β local `wrangler dev` β browser β _then_ deploy), and a "fix" asserted from the+source instead of the page. Prove the Docker chain by running `build:spa:<name>` ++`<NAME>_REQUIRED=1 build:spa:copy` and asserting every asset the generated template references+exists under `public/`; prove the SSR page by viewing source, not by reading the loader.diff --git a/.gitignore b/.gitignoreindex 4ddb6caa41d..f4accfb963b 100644--- a/.gitignore+++ b/.gitignore@@ -60,6 +60,7 @@ bun.lockbdist/public/_spa/public/_spa-auth/+public/_spa-share/public/_spa-workbench/public/spa/es/@@ -95,6 +96,7 @@ public/swe-worker*# Generated filessrc/app/spa/[variants]/[[...path]]/spaHtmlTemplates.tssrc/app/spa-auth/authHtmlTemplate.ts+src/app/spa-share/shareHtmlTemplate.tssrc/app/spa-workbench/workbenchHtmlTemplate.tspublic/*.jsrobots.txtdiff --git a/.vscode/settings.json b/.vscode/settings.jsonindex 76fb403b5dc..e0feee21d43 100644--- a/.vscode/settings.json+++ b/.vscode/settings.json@@ -29,6 +29,7 @@"**/logs/**": true,"**/node_modules/*/**": true,"**/public/_spa-auth/**": true,+ "**/public/_spa-share/**": true,"**/public/_spa-workbench/**": true,"**/public/_spa/**": true},diff --git a/Dockerfile b/Dockerfileindex 9bcd2b96b6a..de7464f4a6c 100644--- a/Dockerfile+++ b/Dockerfile@@ -67,6 +67,7 @@ COPY packages ./packagesCOPY patches ./patches# workspace manifests must exist before pnpm i so --filter can resolve themCOPY apps/desktop/src/main/package.json ./apps/desktop/src/main/package.json+COPY apps/share/package.json ./apps/share/package.jsonCOPY apps/workbench/package.json ./apps/workbench/package.jsonRUN set -e && \@@ -108,6 +109,7 @@ COPY --from=builder /app/.next/standalone /app/COPY --from=builder /app/.next/static /app/.next/static# Copy SPA assets (Vite build output)COPY --from=builder /app/public/_spa /app/public/_spa+COPY --from=builder /app/public/_spa-share /app/public/_spa-shareCOPY --from=builder /app/public/_spa-workbench /app/public/_spa-workbench# Copy database migrationsCOPY --from=builder /app/packages/database/migrations /app/migrationsdiff --git a/apps/share/.gitignore b/apps/share/.gitignorenew file mode 100644index 00000000000..2d9485ea4b4--- /dev/null+++ b/apps/share/.gitignore@@ -0,0 +1,6 @@+.react-router/+!app/lib/+.wrangler/+build/+build-inputs.txt+ssr-chunk-report.jsondiff --git a/apps/share/app/entry.client.tsx b/apps/share/app/entry.client.tsxnew file mode 100644index 00000000000..452d07a8188--- /dev/null+++ b/apps/share/app/entry.client.tsx@@ -0,0 +1,34 @@+import { startTransition, StrictMode } from 'react';+import { hydrateRoot } from 'react-dom/client';+import { HydratedRouter } from 'react-router/dom';++import { ensureBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';++// RR suffixes dynamically-shared route CSS hrefs with `#`, so the vite preload+// helper re-requests them with `crossorigin` β against our cross-origin CDN the+// browser reuses the plain-cached (ACAO-less) response and fails the CORS+// check, which would otherwise crash route loading. The stylesheet is already+// applied via RR's own link, so a failed duplicate preload is safe to ignore.+// Must attach here (first client module) β route chunks load in parallel with+// root.tsx, so a root-level listener can miss the event.+window.addEventListener('vite:preloadError', (event) => {+ const payload = (event as Event & { payload?: Error }).payload;+ if (String(payload).includes('CSS')) {+ console.warn('[share] ignored css preload failure:', payload);+ event.preventDefault();+ }+});++// The conversation route blocks its first render on this registry, whose own+// dependency chain is several round trips deep. Kicking it off with the entry+// β rather than when the gated chunk mounts β overlaps it with hydration.+void ensureBuiltinToolSurfaces();++startTransition(() => {+ hydrateRoot(+ document,+ <StrictMode>+ <HydratedRouter />+ </StrictMode>,+ );+});diff --git a/apps/share/app/entry.server.tsx b/apps/share/app/entry.server.tsxnew file mode 100644index 00000000000..d86af14eee1--- /dev/null+++ b/apps/share/app/entry.server.tsx@@ -0,0 +1,45 @@+import { createCache } from '@ant-design/cssinjs';+import { buildInlineAntdStyle } from '@lobehub/ui/static-css/runtime';+import { extractStaticStyle, StyleProvider } from 'antd-style';+import { renderToReadableStream } from 'react-dom/server';+import type { EntryContext } from 'react-router';+import { ServerRouter } from 'react-router';+import { styleKeys } from 'virtual:lobehub/antd-static-css';++export default async function handleRequest(+ request: Request,+ responseStatusCode: number,+ responseHeaders: Headers,+ routerContext: EntryContext,+) {+ let status = responseStatusCode;+ const antdCache = createCache();++ const stream = await renderToReadableStream(+ <StyleProvider cache={antdCache} speedy={false}>+ <ServerRouter context={routerContext} url={request.url} />+ </StyleProvider>,+ {+ onError(error) {+ status = 500;+ console.error(error);+ },+ },+ );++ await stream.allReady;+ const html = await new Response(stream).text();++ const inlineAntd = buildInlineAntdStyle(antdCache, { styleKeys });+ const emotionTags = extractStaticStyle(html, { includeAntd: false })+ .map((item) => item.tag)+ .join('');++ responseHeaders.set('Content-Type', 'text/html; charset=utf-8');+ responseHeaders.set('x-share-antd-uncovered', String(inlineAntd.uncovered.length));++ return new Response(html.replace('</head>', `${inlineAntd.html}${emotionTags}</head>`), {+ headers: responseHeaders,+ status,+ });+}diff --git a/apps/share/app/lib/cloudflareContext.ts b/apps/share/app/lib/cloudflareContext.tsnew file mode 100644index 00000000000..2d6a6ee068f--- /dev/null+++ b/apps/share/app/lib/cloudflareContext.ts@@ -0,0 +1,11 @@+import { createContext } from 'react-router';++export interface WorkerExecutionContext {+ passThroughOnException: () => void;+ waitUntil: (promise: Promise<unknown>) => void;+}++export const cloudflareContext = createContext<{+ ctx: WorkerExecutionContext;+ env: Record<string, unknown>;+}>();diff --git a/apps/share/app/lib/seo.ts b/apps/share/app/lib/seo.tsnew file mode 100644index 00000000000..bd9909ec2fd--- /dev/null+++ b/apps/share/app/lib/seo.ts@@ -0,0 +1,64 @@+import { BRANDING_NAME } from '@lobechat/business-const';+import type { MetaDescriptor } from 'react-router';++// Shared with landing-rr: share pages ship behind the lobehub.com gateway, so+// the landing's OG artwork is the brand card for these pages too. Absolute URL+// on purpose β OG scrapers do not resolve relative image paths.+const OG_IMAGE_URL = 'https://lobehub.com/assets/cao-og.webp';+const TWITTER_SITE = '@lobehub';++type DescriptionKey = 'pageDescription' | 'topicDescription';++const FALLBACK_DESCRIPTION: Record<DescriptionKey, string> = {+ pageDescription: `A page shared from ${BRANDING_NAME}.`,+ topicDescription: `A conversation shared from ${BRANDING_NAME}.`,+};++export const shareMetaDescription = (resources: unknown, key: DescriptionKey): string => {+ const chat = (resources as Record<string, Record<string, unknown>> | undefined)?.chat;+ const text = chat?.[`sharePage.meta.${key}`];++ return typeof text === 'string'+ ? text.replaceAll('{{appName}}', BRANDING_NAME)+ : FALLBACK_DESCRIPTION[key];+};++export const truncateDescription = (text: string | null | undefined, max = 200) => {+ if (!text) return undefined;+ const clean = text.replaceAll(/\s+/g, ' ').trim();+ if (!clean) return undefined;++ return clean.length > max ? `${clean.slice(0, max - 1)}β¦` : clean;+};++interface BuildPageMetaOptions {+ description: string;+ locale?: string;+ title: string;+ type?: 'article' | 'website';+}++export const buildPageMeta = ({+ description,+ locale = 'en-US',+ title,+ type = 'website',+}: BuildPageMetaOptions): MetaDescriptor[] => [+ { title },+ { content: description, name: 'description' },+ // Mirrors the apex robots.txt, which disallows /share/*: shared links are+ // meant to be passed around, not indexed. OG scrapers still read the card.+ { content: 'noindex, nofollow', name: 'robots' },+ { content: title, property: 'og:title' },+ { content: description, property: 'og:description' },+ { content: type, property: 'og:type' },+ { content: BRANDING_NAME, property: 'og:site_name' },+ { content: locale.replace('-', '_'), property: 'og:locale' },+ { content: OG_IMAGE_URL, property: 'og:image' },+ { content: title, property: 'og:image:alt' },+ { content: 'summary_large_image', name: 'twitter:card' },+ { content: TWITTER_SITE, name: 'twitter:site' },+ { content: title, name: 'twitter:title' },+ { content: description, name: 'twitter:description' },+ { content: OG_IMAGE_URL, name: 'twitter:image' },+];diff --git a/apps/share/app/lib/serverTrpc.ts b/apps/share/app/lib/serverTrpc.tsnew file mode 100644index 00000000000..9d8f874257f--- /dev/null+++ b/apps/share/app/lib/serverTrpc.ts@@ -0,0 +1,18 @@+import { createTRPCClient, httpLink } from '@trpc/client';+import superjson from 'superjson';++import type { LambdaRouter } from '@/server/routers/lambda';++export const createServerLambdaClient = (request: Request, apiBase?: string) =>+ createTRPCClient<LambdaRouter>({+ links: [+ httpLink({+ headers: () => {+ const cookie = request.headers.get('cookie');+ return cookie ? { cookie } : {};+ },+ transformer: superjson,+ url: new URL('/trpc/lambda', apiBase || request.url).toString(),+ }),+ ],+ });diff --git a/apps/share/app/root.tsx b/apps/share/app/root.tsxnew file mode 100644index 00000000000..d2940efe340--- /dev/null+++ b/apps/share/app/root.tsx@@ -0,0 +1,103 @@+import { BRANDING_NAME } from '@lobechat/business-const';+import type { PropsWithChildren } from 'react';+import type { LoaderFunctionArgs, MetaFunction } from 'react-router';+import {+ Links,+ Meta,+ Outlet,+ Scripts,+ ScrollRestoration,+ useRouteError,+ useRouteLoaderData,+} from 'react-router';+import { isRtlLang } from 'rtl-detect';+import { href as antdStaticCssHref } from 'virtual:lobehub/antd-static-css';+import { href as themeVarsCssHref } from 'virtual:lobehub/theme-vars-css';++import ErrorCapture, { type ErrorType } from '@/components/Error';+import NextThemeProvider from '@/layout/GlobalProvider/NextThemeProvider';+import { resolveRequestLocale } from '@/locales/requestLocale';+import { isChunkLoadError, notifyChunkError } from '@/utils/chunkError';++import ShareAppShell from '../src/shell';+import { loadShareResources } from '../src/shell/createShareI18n';+import { buildPageMeta, shareMetaDescription } from './lib/seo';++export const loader = async ({ request }: LoaderFunctionArgs) => {+ const locale = resolveRequestLocale(request);+ const resources = await loadShareResources(locale);++ return {+ dir: isRtlLang(locale) ? 'rtl' : 'ltr',+ locale,+ resources,+ };+};++export const meta: MetaFunction<typeof loader> = ({ loaderData }) =>+ buildPageMeta({+ description: shareMetaDescription(loaderData?.resources, 'topicDescription'),+ locale: loaderData?.locale,+ title: BRANDING_NAME,+ });++const bodyBackground = `+html body { background: #f8f8f8; }+html[data-theme='dark'] body { background-color: #000; }+`;++export const Layout = ({ children }: PropsWithChildren) => {+ const data = useRouteLoaderData<typeof loader>('root');++ return (+ <html suppressHydrationWarning dir={data?.dir ?? 'ltr'} lang={data?.locale ?? 'en-US'}>+ <head>+ <meta charSet="utf-8" />+ <meta content="width=device-width, initial-scale=1" name="viewport" />+ <link href="/favicon.ico" rel="icon" />+ <Meta />+ <Links />+ <style dangerouslySetInnerHTML={{ __html: bodyBackground }} />+ <link href={themeVarsCssHref} rel="stylesheet" />+ <link href={antdStaticCssHref} rel="stylesheet" />+ </head>+ <body>+ {children}+ <ScrollRestoration />+ <Scripts />+ </body>+ </html>+ );+};++export default function Root() {+ const data = useRouteLoaderData<typeof loader>('root');++ return (+ <NextThemeProvider>+ <ShareAppShell locale={data?.locale} resources={data?.resources} serverConfig={null}>+ <Outlet />+ </ShareAppShell>+ </NextThemeProvider>+ );+}++export const ErrorBoundary = () => {+ const rawError = useRouteError();+ const data = useRouteLoaderData<typeof loader>('root');++ if (typeof window !== 'undefined' && isChunkLoadError(rawError)) notifyChunkError();++ const error =+ rawError instanceof Error ? (rawError as ErrorType) : new Error(JSON.stringify(rawError));++ // The boundary replaces Root, so it must rebuild the provider shell itself+ // (theme + i18n) for the shared error page to render properly.+ return (+ <NextThemeProvider>+ <ShareAppShell locale={data?.locale} resources={data?.resources} serverConfig={null}>+ <ErrorCapture error={error} />+ </ShareAppShell>+ </NextThemeProvider>+ );+};diff --git a/apps/share/app/routes.ts b/apps/share/app/routes.tsnew file mode 100644index 00000000000..5aa41ddd637--- /dev/null+++ b/apps/share/app/routes.ts@@ -0,0 +1,8 @@+import { index, route, type RouteConfig } from '@react-router/dev/routes';++export default [+ index('routes/homeRedirect.tsx'),+ route('share/t/:id', 'routes/shareTopic.tsx'),+ route('share/page/:id', 'routes/sharePage.tsx'),+ route('*', 'routes/catchall.tsx'),+] satisfies RouteConfig;diff --git a/apps/share/app/routes/catchall.tsx b/apps/share/app/routes/catchall.tsxnew file mode 100644index 00000000000..672cc75a12f--- /dev/null+++ b/apps/share/app/routes/catchall.tsx@@ -0,0 +1,15 @@+import type { LoaderFunctionArgs } from 'react-router';+import { redirect } from 'react-router';++import ShareLoading from '../../src/shell/ShareLoading';+import { cloudflareContext } from '../lib/cloudflareContext';++export const loader = ({ context }: LoaderFunctionArgs) => {+ const appHome = context.get(cloudflareContext).env.SHARE_APP_HOME as string | undefined;++ return redirect(appHome || 'https://lobehub.com');+};++export default function ExitShare() {+ return <ShareLoading />;+}diff --git a/apps/share/app/routes/homeRedirect.tsx b/apps/share/app/routes/homeRedirect.tsxnew file mode 100644index 00000000000..e6e2a81bcb4--- /dev/null+++ b/apps/share/app/routes/homeRedirect.tsx@@ -0,0 +1 @@+export { default, loader } from './catchall';diff --git a/apps/share/app/routes/sharePage.tsx b/apps/share/app/routes/sharePage.tsxnew file mode 100644index 00000000000..29d106f1071--- /dev/null+++ b/apps/share/app/routes/sharePage.tsx@@ -0,0 +1,61 @@+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 { getIdFromIdentifier } from '@/utils/identifier';++import SharedPageView from '../../src/features/page/SharedPageView';+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 documentId = getIdFromIdentifier(params.id ?? '', 'docs');+ const locale = resolveRequestLocale(request);+ const apiBase = context.get(cloudflareContext).env.SHARE_API_BASE as string | undefined;++ const sharedDocument = await createServerLambdaClient(request, apiBase)+ .pageShare.getSharedDocument.query({ documentId })+ .catch((error) => {+ console.error('[share] shared document SSR fetch failed:', error);+ return null;+ });++ return {+ description: shareMetaDescription(await loadShareResources(locale), 'pageDescription'),+ documentId,+ locale,+ sharedDocument,+ };+};++export const meta: MetaFunction<typeof loader> = ({ loaderData }) => {+ const title = loaderData?.sharedDocument?.document?.title;++ return buildPageMeta({+ description: loaderData?.description ?? '',+ locale: loaderData?.locale,+ title: title ? `${title} Β· ${BRANDING_NAME}` : BRANDING_NAME,+ type: 'article',+ });+};++export default function SharePageRoute() {+ const { documentId, sharedDocument } = useLoaderData<typeof loader>();++ return (+ <SWRConfig+ value={{+ fallback: sharedDocument+ ? { [unstable_serialize(shareKeys.pageDocument(documentId))]: sharedDocument }+ : {},+ }}+ >+ <SharedPageView />+ </SWRConfig>+ );+}diff --git a/apps/share/app/routes/shareTopic.tsx b/apps/share/app/routes/shareTopic.tsxnew file mode 100644index 00000000000..0d906c487af--- /dev/null+++ b/apps/share/app/routes/shareTopic.tsx@@ -0,0 +1,63 @@+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 SharedTopicView from '../../src/features/topic/SharedTopicView';+import { buildTopicByline } from '../../src/features/topic/topicByline';+import { loadShareResources } from '../../src/shell/createShareI18n';+import { cloudflareContext } from '../lib/cloudflareContext';+import { buildPageMeta, shareMetaDescription, truncateDescription } from '../lib/seo';+import { createServerLambdaClient } from '../lib/serverTrpc';++export const loader = async ({ context, params, request }: LoaderFunctionArgs) => {+ const shareId = params.id!;+ const locale = resolveRequestLocale(request);+ const apiBase = context.get(cloudflareContext).env.SHARE_API_BASE as string | undefined;+ const client = createServerLambdaClient(request, apiBase);++ // SSR data is best-effort: on any backend failure fall back to CSR, where SWR+ // refetches and surfaces the error state exactly as before.+ const topic = await client.share.getSharedTopic.query({ shareId }).catch((error) => {+ console.error('[share] shared topic SSR fetch failed:', error);+ return null;+ });++ return {+ byline: topic ? buildTopicByline(topic) : undefined,+ description: shareMetaDescription(await loadShareResources(locale), 'topicDescription'),+ locale,+ shareId,+ topic,+ };+};++export const meta: MetaFunction<typeof loader> = ({ loaderData }) => {+ const title = loaderData?.topic?.title;++ return buildPageMeta({+ description: [truncateDescription(loaderData?.byline), loaderData?.description]+ .filter(Boolean)+ .join(' Β· '),+ locale: loaderData?.locale,+ title: title ? `${title} Β· ${BRANDING_NAME}` : BRANDING_NAME,+ type: 'article',+ });+};++export default function ShareTopicRoute() {+ const { shareId, topic } = useLoaderData<typeof loader>();++ return (+ <SWRConfig+ value={{+ fallback: topic ? { [unstable_serialize(shareKeys.topic(shareId))]: topic } : {},+ }}+ >+ <SharedTopicView />+ </SWRConfig>+ );+}diff --git a/apps/share/app/stubs/clientOnlyModule.tsx b/apps/share/app/stubs/clientOnlyModule.tsxnew file mode 100644index 00000000000..275dacc26b2--- /dev/null+++ b/apps/share/app/stubs/clientOnlyModule.tsx@@ -0,0 +1,7 @@+// Resolved in the SSR environment for every `*.client` module (see+// `share-client-only-stub`). The conversation and page-viewer stacks behind+// those imports are the app's whole weight; the worker never renders them, so+// they must not be bundled into it either.+const ClientOnlyModule = () => null;++export default ClientOnlyModule;diff --git a/apps/share/app/stubs/electronStore.ts b/apps/share/app/stubs/electronStore.tsnew file mode 100644index 00000000000..bdb29e0aa04--- /dev/null+++ b/apps/share/app/stubs/electronStore.ts@@ -0,0 +1,10 @@+const emptyState = {} as never;++// Renderable stand-in, not a throwing proxy: shared components may call the+// hook during SSR and must see "desktop features off", not a crash.+export const useElectronStore = <T = unknown>(selector?: (state: never) => T): T =>+ selector ? selector(emptyState) : (emptyState as T);++useElectronStore.getState = () => emptyState;++export const getElectronStoreState = () => emptyState;diff --git a/apps/share/app/stubs/fileStore.ts b/apps/share/app/stubs/fileStore.tsnew file mode 100644index 00000000000..0e04ff0db36--- /dev/null+++ b/apps/share/app/stubs/fileStore.ts@@ -0,0 +1,14 @@+const emptyState = {} as never;++export const useFileStore = <T = unknown>(selector?: (state: never) => T): T =>+ selector ? selector(emptyState) : (emptyState as T);++useFileStore.getState = () => emptyState;++const passiveSelectors = new Proxy({}, { get: () => () => undefined }) as never;++export const documentSelectors = passiveSelectors;+export const fileChatSelectors = passiveSelectors;+export const fileManagerSelectors = passiveSelectors;+export const filesSelectors = passiveSelectors;+export const getChunkTargetId = () => undefined;diff --git a/apps/share/app/stubs/globalService.ts b/apps/share/app/stubs/globalService.tsnew file mode 100644index 00000000000..52674a92a7d--- /dev/null+++ b/apps/share/app/stubs/globalService.ts@@ -0,0 +1,3 @@+import { reject } from './reject';++export const globalService = reject('globalService');diff --git a/apps/share/app/stubs/loadI18nNamespaceModule.ts b/apps/share/app/stubs/loadI18nNamespaceModule.tsnew file mode 100644index 00000000000..cd1abdedfb0--- /dev/null+++ b/apps/share/app/stubs/loadI18nNamespaceModule.ts@@ -0,0 +1,42 @@+type NamespaceModule = { default: Record<string, unknown> };+type NamespaceLoaderMap = Record<string, () => Promise<NamespaceModule>>;++// SSR renders only the namespaces listed in `shareNamespaces`; the generic+// loader would register every locale x namespace pair as a worker chunk+// (~1000 files). The client build keeps the generic loader β its graph+// legitimately spans the whole conversation stack.+const defaultLoaders = import.meta.glob([+ '../../../../packages/locales/src/default/chat.ts',+ '../../../../packages/locales/src/default/error.ts',+ '../../../../packages/locales/src/default/pageShare.ts',+]) as NamespaceLoaderMap;+const localeLoaders = import.meta.glob([+ '../../../../locales/*/chat.json',+ '../../../../locales/*/error.json',+ '../../../../locales/*/pageShare.json',+]) as NamespaceLoaderMap;++export interface LoadI18nNamespaceModuleParams {+ defaultLang: string;+ lng: string;+ normalizeLocale: (locale?: string) => string;+ ns: string;+}++export const loadI18nNamespaceModule = async (+ params: LoadI18nNamespaceModuleParams,+): Promise<NamespaceModule> => {+ const { defaultLang, normalizeLocale, lng, ns } = params;++ const loadDefault = defaultLoaders[`../../../../packages/locales/src/default/${ns}.ts`];+ if (!loadDefault) throw new Error(`Namespace not bundled for SSR: ${ns}`);++ if (lng !== defaultLang) {+ const loadLocale = localeLoaders[`../../../../locales/${normalizeLocale(lng)}/${ns}.json`];+ if (loadLocale) return loadLocale();+ }++ return loadDefault();+};++export const loadI18nNamespaceModuleWithFallback = loadI18nNamespaceModule;diff --git a/apps/share/app/stubs/reject.ts b/apps/share/app/stubs/reject.tsnew file mode 100644index 00000000000..e38be859a86--- /dev/null+++ b/apps/share/app/stubs/reject.ts@@ -0,0 +1,10 @@+export const reject = (name: string): never =>+ new Proxy(() => {}, {+ apply() {+ throw new Error(`${name} is not available during SSR`);+ },+ get(_target, prop) {+ if (prop === Symbol.toPrimitive || prop === 'then') return undefined;+ return reject(`${name}.${String(prop)}`);+ },+ }) as never;diff --git a/apps/share/app/stubs/shiki.ts b/apps/share/app/stubs/shiki.tsnew file mode 100644index 00000000000..b71eea37300--- /dev/null+++ b/apps/share/app/stubs/shiki.ts@@ -0,0 +1,34 @@+import { reject } from './reject';++interface BundledInfo {+ aliases?: string[];+ displayName: string;+ id: string;+ name: string;+}++// `@lobehub/ui`'s Highlighter reads these catalogs at module scope, and the+// barrel puts it in every graph that touches the package. Importing the real+// `shiki` registers all ~400 bundled grammars as chunks β roughly half the+// worker's upload β for a highlighter the server never renders, since every+// code surface sits behind a `*.client` gate.+export const bundledLanguagesInfo: BundledInfo[] = [];+export const bundledThemesInfo: BundledInfo[] = [];+export const bundledLanguages: Record<string, () => Promise<unknown>> = {};++// Evaluated at module scope by theme setup, so it answers instead of throwing.+export const createCssVariablesTheme = (options?: { name?: string }) => ({+ name: options?.name ?? 'css-variables',+ settings: [],+ type: 'dark' as const,+});++export const getTokenStyleObject = () => ({});+export const stringifyTokenStyle = () => '';++// Only reachable from a render path, so hitting one means a code surface+// escaped the client gate β fail loudly rather than render unhighlighted.+export const codeToHtml = reject('shiki.codeToHtml');+export const createHighlighter = reject('shiki.createHighlighter');+export const createJavaScriptRegexEngine = reject('shiki.createJavaScriptRegexEngine');+export const createOnigurumaEngine = reject('shiki.createOnigurumaEngine');diff --git a/apps/share/app/stubs/shikiWasm.ts b/apps/share/app/stubs/shikiWasm.tsnew file mode 100644index 00000000000..283075b528d--- /dev/null+++ b/apps/share/app/stubs/shikiWasm.ts@@ -0,0 +1,3 @@+// Reached only through `createOnigurumaEngine(import('shiki/wasm'))`, which the+// worker never runs. The real module is a ~600KB wasm payload.+export default null;diff --git a/apps/share/app/stubs/toolSurfaces.ts b/apps/share/app/stubs/toolSurfaces.tsnew file mode 100644index 00000000000..141cd51aa2f--- /dev/null+++ b/apps/share/app/stubs/toolSurfaces.ts@@ -0,0 +1,4 @@+export const ensureBuiltinToolSurfaces = (): Promise<void> => Promise.resolve();++export const loadRouteWithBuiltinToolSurfaces = <T>(loadRoute: () => Promise<T>): Promise<T> =>+ loadRoute();diff --git a/apps/share/app/stubs/trpcClient.ts b/apps/share/app/stubs/trpcClient.tsnew file mode 100644index 00000000000..51d23435965--- /dev/null+++ b/apps/share/app/stubs/trpcClient.ts@@ -0,0 +1,6 @@+import { reject } from './reject';++export const lambdaClient = reject('lambdaClient');+export const asyncClient = reject('asyncClient');+export const toolsClient = reject('toolsClient');+export const lambdaQuery = reject('lambdaQuery');diff --git a/apps/share/app/stubs/userStore.ts b/apps/share/app/stubs/userStore.tsnew file mode 100644index 00000000000..147e2070ba0--- /dev/null+++ b/apps/share/app/stubs/userStore.ts@@ -0,0 +1,11 @@+const emptyState = {} as never;++// Renderable stand-in, not a throwing proxy: shared components read the viewer+// profile during SSR and must see "signed out", not a crash. The client store+// takes over on hydration.+export const useUserStore = <T = unknown>(selector?: (state: never) => T): T =>+ selector ? selector(emptyState) : (emptyState as T);++useUserStore.getState = () => emptyState;++export const getUserStoreState = () => emptyState;diff --git a/apps/share/app/virtual-modules.d.ts b/apps/share/app/virtual-modules.d.tsnew file mode 100644index 00000000000..2c1397cc896--- /dev/null+++ b/apps/share/app/virtual-modules.d.ts@@ -0,0 +1,17 @@+declare module 'virtual:lobehub/antd-static-css' {+ export const css: string;+ export const href: string;+ export const styleKeys: string[];+}++declare module 'virtual:lobehub/theme-vars-css' {+ export const css: string;+ export const href: string;+}++declare module 'virtual:react-router/server-build' {+ import type { ServerBuild } from 'react-router';++ const build: ServerBuild;+ export = build;+}diff --git a/apps/share/index.html b/apps/share/index.htmlnew file mode 100644index 00000000000..dd01f35f855--- /dev/null+++ b/apps/share/index.html@@ -0,0 +1,95 @@+<!doctype html>+<html>+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <link rel="icon" href="/favicon.ico" />+ <link rel="shortcut icon" href="/favicon-32x32.ico" />+ <!--SEO_META-->+ <style>+ html body {+ background: #f8f8f8;+ }+ html[data-theme='dark'] body {+ background-color: #000;+ }+ </style>+ <script>+ (function () {+ function supportsImportMaps() {+ return (+ typeof HTMLScriptElement !== 'undefined' &&+ typeof HTMLScriptElement.supports === 'function' &&+ HTMLScriptElement.supports('importmap')+ );+ }++ function supportsCascadeLayers() {+ var el = document.createElement('div');+ el.className = '__layer_test__';+ el.style.position = 'absolute';+ el.style.left = '-99999px';+ el.style.top = '-99999px';++ var style = document.createElement('style');+ style.textContent =+ '@layer a, b;' ++ '@layer a { .__layer_test__ { color: rgb(1, 2, 3); } }' ++ '@layer b { .__layer_test__ { color: rgb(4, 5, 6); } }';++ document.documentElement.append(style);+ document.documentElement.append(el);++ var color = getComputedStyle(el).color;++ el.remove();+ style.remove();++ return color === 'rgb(4, 5, 6)';+ }++ if (!(supportsImportMaps() && supportsCascadeLayers())) {+ window.location.href = '/not-compatible.html';+ return;+ }++ var theme = 'system';+ try {+ theme = localStorage.getItem('theme') || 'system';+ } catch (_) {}+ var systemTheme =+ window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches+ ? 'dark'+ : 'light';+ var resolvedTheme = theme === 'system' ? systemTheme : theme;+ if (resolvedTheme === 'dark' || resolvedTheme === 'light') {+ document.documentElement.setAttribute('data-theme', resolvedTheme);+ }++ var hl = new URLSearchParams(location.search).get('hl');+ var m = document.cookie.match(/(?:^|;\s*)LOBE_LOCALE=([^;]*)/);+ var cookie = m ? decodeURIComponent(m[1]) : '';+ var locale = hl || cookie || navigator.language || 'en-US';+ if (locale === 'auto') locale = navigator.language || 'en-US';+ if (hl && !cookie) {+ document.cookie =+ 'LOBE_LOCALE=' + encodeURIComponent(hl) + ';path=/;max-age=7776000;SameSite=Lax';+ }+ document.documentElement.lang = locale;+ var rtl = ['ar', 'arc', 'dv', 'fa', 'ha', 'he', 'khw', 'ks', 'ku', 'ps', 'ur', 'yi'];+ document.documentElement.dir =+ rtl.indexOf(locale.split('-')[0].toLowerCase()) >= 0 ? 'rtl' : 'ltr';+ })();+ </script>+ <script>+ window.__SERVER_CONFIG__ = undefined; /* SERVER_CONFIG */+ </script>+ </head>++ <body>+ <div id="root" style="height: 100%"></div>++ <!--ANALYTICS_SCRIPTS-->+ <script type="module" src="/src/entry.tsx"></script>+ </body>+</html>diff --git a/apps/share/package.json b/apps/share/package.jsonnew file mode 100644index 00000000000..951147420bf--- /dev/null+++ b/apps/share/package.json@@ -0,0 +1,24 @@+{+ "name": "@lobehub/share",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "scripts": {+ "build": "vite build",+ "build:rr": "react-router build -c vite.config.rr.mts && node scripts/emit-static-css.mjs",+ "deploy": "bun scripts/deploy.ts",+ "deploy:rr": "wrangler deploy --dry-run",+ "dev": "vite --port 3016",+ "dev:rr": "react-router dev -c vite.config.rr.mts",+ "preview:rr": "vite preview --config vite.config.rr.mts",+ "type-check": "tsc --noEmit"+ },+ "devDependencies": {+ "@ant-design/cssinjs": "^2.1.2",+ "@cloudflare/vite-plugin": "^1.52.1",+ "@react-router/dev": "^8.3.0",+ "isbot": "^5.1.32",+ "vite-tsconfig-paths": "^6.1.1",+ "wrangler": "^4.123.0"+ }+}diff --git a/apps/share/react-router.config.ts b/apps/share/react-router.config.tsnew file mode 100644index 00000000000..20ceb8ebce7--- /dev/null+++ b/apps/share/react-router.config.ts@@ -0,0 +1,10 @@+import type { Config } from '@react-router/dev/config';++export default {+ appDirectory: 'app',+ // Lazy discovery hits /__manifest, which the gateway routes to the default+ // target (app) on the shared lobehub.com origin β the HTML reply breaks+ // client navigations. The route table is tiny; ship it with the document.+ routeDiscovery: { mode: 'initial' },+ ssr: true,+} satisfies Config;diff --git a/apps/share/scripts/deploy.ts b/apps/share/scripts/deploy.tsnew file mode 100644index 00000000000..9118be13162--- /dev/null+++ b/apps/share/scripts/deploy.ts@@ -0,0 +1,78 @@+import { execSync } from 'node:child_process';+import { existsSync } from 'node:fs';+import { resolve } from 'node:path';++import dotenv from 'dotenv';++import { uploadAssets } from '../../../scripts/mobileSpaWorkflow/upload';++const shareRoot = resolve(__dirname, '..');+const repoRoot = resolve(shareRoot, '../..');+const assetsDir = resolve(shareRoot, 'build/client/assets');++// A host repo that builds this app from a submodule keeps its own .env; it+// points SHARE_ENV_FILE at it so local deploys pick up the same credentials.+dotenv.config({ path: process.env.SHARE_ENV_FILE || resolve(repoRoot, '.env') });++const firstEnv = (...names: string[]) => {+ for (const name of names) {+ const value = process.env[name];+ if (value) return value;+ }+ return undefined;+};++const requireEnv = (...names: string[]): string => {+ const value = firstEnv(...names);+ if (!value) throw new Error(`Missing env: ${names.join(' / ')}`);+ return value;+};++async function main() {+ const publicDomain = new URL(requireEnv('ASSET_S3_PUBLIC_DOMAIN', 'MOBILE_S3_PUBLIC_DOMAIN'))+ .origin;+ // Same convention as cloud's resolveViteBase: a stable entry suffix, no version+ // stamp β content-hashed filenames make uploads incremental and cache-immutable.+ // Deliberately not the generic ASSET_S3_KEY_PREFIX: workbench reads that one+ // too, and a shared value would put both apps on the same prefix.+ const keyPrefix = (firstEnv('SHARE_S3_KEY_PREFIX') || 'share').replaceAll(/^\/+|\/+$/g, '');+ const cdnBase = `${publicDomain}/${keyPrefix}/`;++ console.log(`=== Step 1: Build share (VITE_CDN_BASE=${cdnBase}) ===`);+ execSync('bun run build:rr', {+ cwd: shareRoot,+ env: {+ ...process.env,+ NODE_ENV: 'production',+ NODE_OPTIONS: '--max-old-space-size=8192',+ VITE_CDN_BASE: cdnBase,+ },+ stdio: 'inherit',+ });++ if (!existsSync(assetsDir)) throw new Error(`Build output not found at ${assetsDir}`);++ console.log('\n=== Step 2: Upload assets to S3 ===');+ await uploadAssets(assetsDir, {+ accessKeyId: requireEnv('ASSET_S3_ACCESS_KEY_ID', 'MOBILE_S3_ACCESS_KEY_ID'),+ bucket: requireEnv('ASSET_S3_BUCKET', 'MOBILE_S3_BUCKET'),+ endpoint: requireEnv('ASSET_S3_ENDPOINT', 'MOBILE_S3_ENDPOINT'),+ keyPrefix,+ publicDomain,+ region: firstEnv('ASSET_S3_REGION', 'MOBILE_S3_REGION') || 'auto',+ secretAccessKey: requireEnv('ASSET_S3_SECRET_ACCESS_KEY', 'MOBILE_S3_SECRET_ACCESS_KEY'),+ });++ console.log('\n=== Step 3: Deploy worker ===');+ execSync('node_modules/.bin/wrangler deploy --config build/server/wrangler.json', {+ cwd: shareRoot,+ stdio: 'inherit',+ });++ console.log('\n=== Deploy complete ===');+}++main().catch((error) => {+ console.error('Deploy failed:', error);+ process.exit(1);+});diff --git a/apps/share/scripts/emit-static-css.mjs b/apps/share/scripts/emit-static-css.mjsnew file mode 100644index 00000000000..7b6531beb86--- /dev/null+++ b/apps/share/scripts/emit-static-css.mjs@@ -0,0 +1,27 @@+import { mkdir, writeFile } from 'node:fs/promises';+import { fileURLToPath } from 'node:url';++import { antdStaticCssOptions, themeVarsCssOptions } from '../staticCssOptions.mjs';++process.env.NODE_ENV = 'production';++const { buildAntdStaticCss, buildThemeVarsCss } = await import('@lobehub/ui/static-css');++const clientAssetsDir = new URL('../build/client/assets/', import.meta.url);+await mkdir(clientAssetsDir, { recursive: true });++const antd = buildAntdStaticCss(antdStaticCssOptions);+const themeVars = buildThemeVarsCss(themeVarsCssOptions);++for (const payload of [antd, themeVars]) {+ // href may be CDN-absolute; the local mirror always lives at assets/<basename>.+ const fileName = new URL(payload.href, 'https://placeholder.invalid').pathname.split('/').at(-1);+ const target = new URL(fileName, clientAssetsDir);+ await writeFile(target, payload.css, 'utf8');+ console.log(fileURLToPath(target));+}++if (antd.failedProbes.length > 0) {+ console.error('static-css failed probes:', antd.failedProbes);+ process.exit(1);+}diff --git a/apps/share/scripts/should-build.mjs b/apps/share/scripts/should-build.mjsnew file mode 100644index 00000000000..6e4e476741f--- /dev/null+++ b/apps/share/scripts/should-build.mjs@@ -0,0 +1,83 @@+import { execFileSync } from 'node:child_process';+import { appendFileSync, readFileSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');+const manifestPath =+ process.env.SHARE_MANIFEST || path.resolve(repoRoot, 'apps/share/build-inputs.txt');++// Inputs the bundle graph cannot see: build config and its imports, dependency+// versions, and files matched by import.meta.glob patterns that may not have+// existed at the last build.+//+// Matched anywhere in the path, not anchored: a host repo that builds this app+// from a submodule reports the same files under its own prefix+// (`lobehub/apps/share/...`), and both spellings must trigger.+const META_TRIGGER_SEGMENTS = [+ 'apps/share/',+ 'plugins/vite/',+ 'packages/locales/src/default/',+ 'pnpm-lock.yaml',+ 'tsconfig.json',+];+const BUNDLED_LOCALE = /locales\/[^/]+\/(?:chat|error|pageShare)\.json$/;++const META_TRIGGERS = [+ (file) => META_TRIGGER_SEGMENTS.some((segment) => file.includes(segment)),+ (file) => BUNDLED_LOCALE.test(file),+];++const emit = (shouldBuild, reason, hits = []) => {+ console.log(reason);+ for (const hit of hits) console.log(` ${hit}`);+ console.log(`should_build=${shouldBuild}`);+ if (process.env.GITHUB_OUTPUT) {+ appendFileSync(process.env.GITHUB_OUTPUT, `should_build=${shouldBuild}\n`);+ }+};++const args = process.argv.slice(2);+let changed;++if (args[0] === '--files') {+ changed = args.slice(1);+} else {+ const [base, head = 'HEAD'] = args;+ if (!base) {+ emit(true, 'no base commit provided β building');+ process.exit(0);+ }+ try {+ changed = execFileSync('git', ['diff', '--name-only', `${base}...${head}`], {+ cwd: repoRoot,+ encoding: 'utf8',+ })+ .split('\n')+ .filter(Boolean);+ } catch {+ emit(true, `base commit ${base} not resolvable β building`);+ process.exit(0);+ }+}++let manifestText;+try {+ manifestText = readFileSync(manifestPath, 'utf8');+} catch {+ emit(true, `manifest ${manifestPath} not available β building`);+ process.exit(0);+}++const manifest = new Set(manifestText.split('\n').filter(Boolean));+const hits = changed.filter(+ (file) => manifest.has(file) || META_TRIGGERS.some((matches) => matches(file)),+);++emit(+ hits.length > 0,+ hits.length > 0+ ? `${hits.length} share build input(s) changed:`+ : `no share build inputs among ${changed.length} changed file(s)`,+ hits.slice(0, 20),+);diff --git a/apps/share/src/entry.tsx b/apps/share/src/entry.tsxnew file mode 100644index 00000000000..10dee784c8b--- /dev/null+++ b/apps/share/src/entry.tsx@@ -0,0 +1,17 @@+import { RouterProvider } from 'react-router/dom';++import BootErrorBoundary from '@/components/BootErrorBoundary';+import NextThemeProvider from '@/layout/GlobalProvider/NextThemeProvider';+import { createSPABrowserRouter, createSPARoot } from '@/spa/runtime';++import { shareRoutes } from './router';++const router = createSPABrowserRouter(shareRoutes);++createSPARoot(document.getElementById('root')!).render(+ <BootErrorBoundary>+ <NextThemeProvider>+ <RouterProvider router={router} />+ </NextThemeProvider>+ </BootErrorBoundary>,+);diff --git a/src/routes/share/page/[id]/index.tsx b/apps/share/src/features/page/SharedPageView.tsxsimilarity index 67%rename from src/routes/share/page/[id]/index.tsxrename to apps/share/src/features/page/SharedPageView.tsxindex 59eb021e14f..b907f15bf99 100644--- a/src/routes/share/page/[id]/index.tsx+++ b/apps/share/src/features/page/SharedPageView.tsx@@ -8,12 +8,11 @@ import useSWR from 'swr';import PublishedShell from '@/business/client/features/PageShare/PublishedShell';import ReadOnlyPageViewer from '@/business/client/features/PageShare/ReadOnlyPageViewer';import Loading from '@/components/Loading/BrandTextLoading';-import { RouteMetaBridge } from '@/features/RouteMeta';import { shareKeys } from '@/libs/swr/keys';import { lambdaClient } from '@/libs/trpc/client';import { getIdFromIdentifier } from '@/utils/identifier';-const SharePagePage = memo(() => {+const SharedPageView = memo(() => {const { id } = useParams<{ id: string }>();const documentId = getIdFromIdentifier(id ?? '', 'docs');@@ -23,24 +22,23 @@ const SharePagePage = memo(() => {{ revalidateOnFocus: false },);- if (!error && isLoading) {+ // The SSR document already carries the page, and SWR revalidates on mount+ // with it in cache β gating on `isLoading` alone would blank it.+ if (!error && !data && isLoading) {return (<Center height={'100vh'}>- <Loading debugId="SharePagePage" />+ <Loading debugId="SharedPageView" /></Center>);}return (- <>- <RouteMetaBridge />- <PublishedShell data={data} error={error}>- {data ? <ReadOnlyPageViewer data={data} /> : null}- </PublishedShell>- </>+ <PublishedShell data={data} error={error}>+ {data ? <ReadOnlyPageViewer data={data} /> : null}+ </PublishedShell>);});-SharePagePage.displayName = 'SharePagePage';+SharedPageView.displayName = 'SharedPageView';-export default SharePagePage;+export default SharedPageView;diff --git a/src/routes/share/t/[id]/features/Portal/index.tsx b/apps/share/src/features/topic/SharePortal.tsxsimilarity index 100%rename from src/routes/share/t/[id]/features/Portal/index.tsxrename to apps/share/src/features/topic/SharePortal.tsxdiff --git a/src/routes/share/t/[id]/SharedMessageList.tsx b/apps/share/src/features/topic/SharedMessageList.tsxsimilarity index 100%rename from src/routes/share/t/[id]/SharedMessageList.tsxrename to apps/share/src/features/topic/SharedMessageList.tsxdiff --git a/apps/share/src/features/topic/SharedTopicAside.client.tsx b/apps/share/src/features/topic/SharedTopicAside.client.tsxnew file mode 100644index 00000000000..e06795dd4dc--- /dev/null+++ b/apps/share/src/features/topic/SharedTopicAside.client.tsx@@ -0,0 +1 @@+export { default } from './SharePortal';diff --git a/src/routes/share/t/[id]/index.tsx b/apps/share/src/features/topic/SharedTopicBody.client.tsxsimilarity index 56%rename from src/routes/share/t/[id]/index.tsxrename to apps/share/src/features/topic/SharedTopicBody.client.tsxindex e2c3c7285a1..df51680524c 100644--- a/src/routes/share/t/[id]/index.tsx+++ b/apps/share/src/features/topic/SharedTopicBody.client.tsx@@ -1,30 +1,31 @@'use client';import { memo } from 'react';-import { useParams } from 'react-router';import useSWR from 'swr';import { ShareHero } from '@/business/client/features/ShareShell';import { shareKeys } from '@/libs/swr/keys';import { lambdaClient } from '@/libs/trpc/client';-import TopicAvatar from './features/TopicAvatar';import SharedMessageList from './SharedMessageList';+import TopicAvatar from './TopicAvatar';+import { buildTopicByline } from './topicByline';+import { useSyncSharedTopicMeta } from './useSyncSharedTopicMeta';-const ShareTopicPage = memo(() => {- const { id } = useParams<{ id: string }>();+interface SharedTopicBodyProps {+ shareId: string;+}+const SharedTopicBody = memo<SharedTopicBodyProps>(({ shareId }) => {const { data } = useSWR(- id ? shareKeys.topic(id) : null,- () => lambdaClient.share.getSharedTopic.query({ shareId: id! }),+ shareKeys.topic(shareId),+ () => lambdaClient.share.getSharedTopic.query({ shareId }),{ revalidateOnFocus: false },);- if (!data) return null;+ useSyncSharedTopicMeta(data);- const isInboxAgent = !data.groupId && data.agentMeta?.slug === 'inbox';- const agentOrGroupTitle =- data.groupMeta?.title || (isInboxAgent ? 'Lobe AI' : data.agentMeta?.title);+ if (!data) return null;return (<SharedMessageList@@ -35,7 +36,7 @@ const ShareTopicPage = memo(() => {headerSlot={<ShareHeroavatar={<TopicAvatar data={data} size={40} />}- byline={agentOrGroupTitle}+ byline={buildTopicByline(data)}title={data.title}/>}@@ -43,4 +44,6 @@ const ShareTopicPage = memo(() => {);});-export default ShareTopicPage;+SharedTopicBody.displayName = 'SharedTopicBody';++export default SharedTopicBody;diff --git a/apps/share/src/features/topic/SharedTopicView.tsx b/apps/share/src/features/topic/SharedTopicView.tsxnew file mode 100644index 00000000000..3025f0adea3--- /dev/null+++ b/apps/share/src/features/topic/SharedTopicView.tsx@@ -0,0 +1,58 @@+'use client';++import { memo } from 'react';+import { useParams } from 'react-router';+import useSWR from 'swr';++import ShareShell, { ShareHero } from '@/business/client/features/ShareShell';+import { shareKeys } from '@/libs/swr/keys';+import { lambdaClient } from '@/libs/trpc/client';+import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';++import { clientOnly } from '../../shell/clientOnly';+import TopicAvatar from './TopicAvatar';+import { buildTopicByline } from './topicByline';++const SharedTopicBody = clientOnly(() =>+ loadRouteWithBuiltinToolSurfaces(() => import('./SharedTopicBody.client')),+);+const SharedTopicAside = clientOnly(() => import('./SharedTopicAside.client'));++const SharedTopicView = memo(() => {+ const { id } = useParams<{ id: string }>();++ const { data, error, isLoading } = useSWR(+ id ? shareKeys.topic(id) : null,+ () => lambdaClient.share.getSharedTopic.query({ shareId: id! }),+ { revalidateOnFocus: false },+ );++ const marketIdentifier = data?.agentMeta?.marketIdentifier;+ const openUrl = marketIdentifier ? `/community/agent/${marketIdentifier}` : '/community/agent';++ const hero = data ? (+ <ShareHero+ avatar={<TopicAvatar data={data} size={40} />}+ byline={buildTopicByline(data)}+ title={data.title}+ />+ ) : null;++ return (+ <ShareShell+ aside={<SharedTopicAside />}+ error={error}+ // The SSR document already carries the hero, and SWR revalidates on mount+ // with that data in cache β gating on `isLoading` alone would blank it.+ loading={isLoading && !data}+ share={{ avatar: data ? <TopicAvatar data={data} /> : undefined, openUrl }}+ title={data?.title}+ >+ {id && data ? <SharedTopicBody fallback={hero} shareId={id} /> : null}+ </ShareShell>+ );+});++SharedTopicView.displayName = 'SharedTopicView';++export default SharedTopicView;diff --git a/src/routes/share/t/[id]/features/TopicAvatar.tsx b/apps/share/src/features/topic/TopicAvatar.tsxsimilarity index 100%rename from src/routes/share/t/[id]/features/TopicAvatar.tsxrename to apps/share/src/features/topic/TopicAvatar.tsxdiff --git a/apps/share/src/features/topic/topicByline.ts b/apps/share/src/features/topic/topicByline.tsnew file mode 100644index 00000000000..cb6c679d444--- /dev/null+++ b/apps/share/src/features/topic/topicByline.ts@@ -0,0 +1,7 @@+import { type SharedTopicData } from '@/types/topic';++export const buildTopicByline = (data: SharedTopicData) => {+ const isInboxAgent = !data.groupId && data.agentMeta?.slug === 'inbox';++ return data.groupMeta?.title || (isInboxAgent ? 'Lobe AI' : data.agentMeta?.title);+};diff --git a/src/routes/share/t/[id]/useSyncSharedTopicMeta.ts b/apps/share/src/features/topic/useSyncSharedTopicMeta.tssimilarity index 100%rename from src/routes/share/t/[id]/useSyncSharedTopicMeta.tsrename to apps/share/src/features/topic/useSyncSharedTopicMeta.tsdiff --git a/apps/share/src/router.tsx b/apps/share/src/router.tsxnew file mode 100644index 00000000000..0062c5fb46f--- /dev/null+++ b/apps/share/src/router.tsx@@ -0,0 +1,100 @@+import { useTheme } from 'next-themes';+import type { ComponentType, CSSProperties, ReactElement } from 'react';+import { lazy, Suspense, useEffect } from 'react';+import type { RouteObject } from 'react-router';+import { Outlet, useRouteError } from 'react-router';++import { isChunkLoadError, notifyChunkError } from '@/utils/chunkError';++import ShareAppShell, { ShareNamespace } from './shell';+import ShareLoading from './shell/ShareLoading';++const lazyElement = (importFn: () => Promise<{ default: ComponentType }>): ReactElement => {+ const LazyComponent = lazy(importFn);++ return <LazyComponent />;+};++const buttonStyle: CSSProperties = {+ background: 'transparent',+ border: '1px solid currentcolor',+ borderRadius: 6,+ color: 'inherit',+ cursor: 'pointer',+ font: 'inherit',+ padding: '6px 16px',+};++const ShareErrorBoundary = () => {+ const error = useRouteError() as Error;+ const { resolvedTheme } = useTheme();++ if (typeof window !== 'undefined' && isChunkLoadError(error)) notifyChunkError();++ const isDark = resolvedTheme === 'dark';++ return (+ <div+ style={{+ alignItems: 'center',+ background: isDark ? '#000' : '#f8f8f8',+ color: isDark ? '#e6e6e6' : '#1a1a1a',+ display: 'flex',+ flexDirection: 'column',+ fontFamily: 'sans-serif',+ gap: 16,+ justifyContent: 'center',+ minHeight: '100dvh',+ padding: 16,+ }}+ >+ <h2 style={{ margin: 0 }}>Something went wrong</h2>+ <div style={{ display: 'flex', gap: 12 }}>+ <button style={buttonStyle} type={'button'} onClick={() => window.location.reload()}>+ Retry+ </button>+ <button style={buttonStyle} type={'button'} onClick={() => window.location.assign('/')}>+ Back+ </button>+ </div>+ </div>+ );+};++const ExitShare = () => {+ useEffect(() => {+ window.location.replace('/');+ }, []);++ return <ShareLoading />;+};++export const shareRoutes: RouteObject[] = [+ {+ children: [+ {+ element: lazyElement(() => import('./features/topic/SharedTopicView')),+ path: 'share/t/:id',+ },+ {+ element: lazyElement(() => import('./features/page/SharedPageView')),+ path: 'share/page/:id',+ },+ {+ element: <ExitShare />,+ path: '*',+ },+ ],+ element: (+ <ShareAppShell>+ <ShareNamespace namespace="chat">+ <Suspense fallback={<ShareLoading />}>+ <Outlet />+ </Suspense>+ </ShareNamespace>+ </ShareAppShell>+ ),+ errorElement: <ShareErrorBoundary />,+ path: '/',+ },+];diff --git a/apps/share/src/shell/ShareAppShell.tsx b/apps/share/src/shell/ShareAppShell.tsxnew file mode 100644index 00000000000..4fe2cdbc591--- /dev/null+++ b/apps/share/src/shell/ShareAppShell.tsx@@ -0,0 +1,54 @@+'use client';++import { ModalHost, ToastHost, TooltipGroup } from '@lobehub/ui/base-ui';+import { StyleProvider } from 'antd-style';+import { memo, type PropsWithChildren } from 'react';++import { ServerConfigStoreProvider } from '@/store/serverConfig/Provider';+import type { SPAServerConfig } from '@/types/spaServerConfig';++import { type ShareResources } from './createShareI18n';+import ShareLocale from './ShareLocale';+import ShareTheme from './ShareTheme';++interface ShareAppShellProps extends PropsWithChildren {+ locale?: string;+ resources?: ShareResources;+ serverConfig?: SPAServerConfig | null;+}++const ShareAppShell = memo<ShareAppShellProps>((props) => {+ const { children, resources } = props;++ const serverConfig: SPAServerConfig | undefined =+ props.serverConfig === undefined+ ? typeof window === 'undefined'+ ? undefined+ : window.__SERVER_CONFIG__+ : (props.serverConfig ?? undefined);++ const locale =+ props.locale ??+ (typeof document === 'undefined' ? 'en-US' : document.documentElement.lang || 'en-US');++ return (+ <ShareLocale defaultLang={locale} resources={resources}>+ <ShareTheme>+ <ServerConfigStoreProvider+ featureFlags={serverConfig?.featureFlags}+ serverConfig={serverConfig?.config}+ >+ <TooltipGroup layoutAnimation={false}>+ <StyleProvider speedy={import.meta.env.PROD}>{children}</StyleProvider>+ </TooltipGroup>+ <ModalHost />+ <ToastHost />+ </ServerConfigStoreProvider>+ </ShareTheme>+ </ShareLocale>+ );+});++ShareAppShell.displayName = 'ShareAppShell';++export default ShareAppShell;diff --git a/apps/share/src/shell/ShareLoading.tsx b/apps/share/src/shell/ShareLoading.tsxnew file mode 100644index 00000000000..b6dc3618f56--- /dev/null+++ b/apps/share/src/shell/ShareLoading.tsx@@ -0,0 +1,5 @@+import ContentLoading from '@/components/Loading/ContentLoading';++const ShareLoading = () => <ContentLoading />;++export default ShareLoading;diff --git a/apps/share/src/shell/ShareLocale.tsx b/apps/share/src/shell/ShareLocale.tsxnew file mode 100644index 00000000000..0387dad3209--- /dev/null+++ b/apps/share/src/shell/ShareLocale.tsx@@ -0,0 +1,79 @@+'use client';++import { ConfigProvider } from 'antd';+import dayjs from 'dayjs';+import { memo, type PropsWithChildren, useEffect, useState } from 'react';+import { isRtlLang } from 'rtl-detect';++import type { DayjsLocaleGlobEntry } from '@/utils/dayjsLocale';+import { loadDayjsLocaleModule, normalizeDayjsLocale } from '@/utils/dayjsLocale';+import { getAntdLocale } from '@/utils/locale';++import { createShareI18n, type ShareResources } from './createShareI18n';++const dayjsLocaleLoaders: Record<string, DayjsLocaleGlobEntry> = {+ 'ar': () => import('dayjs/locale/ar'),+ 'bg': () => import('dayjs/locale/bg'),+ 'de': () => import('dayjs/locale/de'),+ 'en': () => import('dayjs/locale/en'),+ 'es': () => import('dayjs/locale/es'),+ 'fa': () => import('dayjs/locale/fa'),+ 'fr': () => import('dayjs/locale/fr'),+ 'it': () => import('dayjs/locale/it'),+ 'ja': () => import('dayjs/locale/ja'),+ 'ko': () => import('dayjs/locale/ko'),+ 'nl': () => import('dayjs/locale/nl'),+ 'pl': () => import('dayjs/locale/pl'),+ 'pt-br': () => import('dayjs/locale/pt-br'),+ 'ru': () => import('dayjs/locale/ru'),+ 'tr': () => import('dayjs/locale/tr'),+ 'vi': () => import('dayjs/locale/vi'),+ 'zh-cn': () => import('dayjs/locale/zh-cn'),+ 'zh-tw': () => import('dayjs/locale/zh-tw'),+};++const updateDayjs = async (lang: string) => {+ const locale = normalizeDayjsLocale(lang);+ const loader = dayjsLocaleLoaders[locale] ?? dayjsLocaleLoaders.en;+ const mod = await loadDayjsLocaleModule(loader!);++ dayjs.locale(mod.default);+};++interface ShareLocaleProps extends PropsWithChildren {+ defaultLang?: string;+ resources?: ShareResources;+}++const ShareLocale = memo<ShareLocaleProps>(({ children, defaultLang, resources }) => {+ const [i18n] = useState(() => createShareI18n(defaultLang, resources));+ const [lang, setLang] = useState(defaultLang ?? 'en-US');+ const [antdLocale, setAntdLocale] = useState<any>();++ if (!i18n.instance.isInitialized) void i18n.init({ initAsync: !resources });++ useEffect(() => {+ const applyLocale = async (nextLang: string) => {+ setLang(nextLang);+ const [nextAntdLocale] = await Promise.all([getAntdLocale(nextLang), updateDayjs(nextLang)]);+ setAntdLocale(nextAntdLocale);+ };++ void applyLocale(i18n.instance.language || defaultLang || 'en-US');+ i18n.instance.on('languageChanged', applyLocale);++ return () => {+ i18n.instance.off('languageChanged', applyLocale);+ };+ }, [defaultLang, i18n]);++ return (+ <ConfigProvider direction={isRtlLang(lang) ? 'rtl' : 'ltr'} locale={antdLocale}>+ {children}+ </ConfigProvider>+ );+});++ShareLocale.displayName = 'ShareLocale';++export default ShareLocale;diff --git a/apps/share/src/shell/ShareNamespace.tsx b/apps/share/src/shell/ShareNamespace.tsxnew file mode 100644index 00000000000..2942b4b030a--- /dev/null+++ b/apps/share/src/shell/ShareNamespace.tsx@@ -0,0 +1,36 @@+'use client';++import { memo, type PropsWithChildren } from 'react';+import { useTranslation } from 'react-i18next';++import ShareLoading from './ShareLoading';++interface ShareNamespaceProps extends PropsWithChildren {+ namespace: 'chat';+}++const ShareNamespace = memo<ShareNamespaceProps>(({ children, namespace }) => {+ const { ready } = useTranslation(namespace);++ if (!ready) {+ return (+ <div+ style={{+ alignItems: 'center',+ display: 'flex',+ height: '100dvh',+ justifyContent: 'center',+ width: '100%',+ }}+ >+ <ShareLoading />+ </div>+ );+ }++ return children;+});++ShareNamespace.displayName = 'ShareNamespace';++export default ShareNamespace;diff --git a/apps/share/src/shell/ShareTheme.tsx b/apps/share/src/shell/ShareTheme.tsxnew file mode 100644index 00000000000..953286ce180--- /dev/null+++ b/apps/share/src/shell/ShareTheme.tsx@@ -0,0 +1,42 @@+'use client';++import 'antd/dist/reset.css';++import ConfigProvider from '@lobehub/ui/es/ConfigProvider/index';+import ThemeProvider from '@lobehub/ui/es/ThemeProvider/index';+import { App } from 'antd';+import { domMax, LazyMotion } from 'motion/react';+import * as m from 'motion/react-m';+import { memo, type PropsWithChildren } from 'react';++import AntdStaticMethods from '@/components/AntdStaticMethods';+import { useIsDark } from '@/hooks/useIsDark';+import Image from '@/libs/next/Image';+import Link from '@/libs/next/Link';++const ShareTheme = memo<PropsWithChildren>(({ children }) => {+ const isDark = useIsDark();+ const appearance = isDark ? 'dark' : 'light';++ return (+ <ThemeProvider+ appearance={appearance}+ className={'share-layout'}+ defaultAppearance={appearance}+ defaultThemeMode={appearance}+ style={{ height: '100%', minHeight: '100dvh', width: '100%' }}+ theme={{ cssVar: { key: 'lobe-vars' } }}+ >+ <App style={{ height: '100%' }}>+ <AntdStaticMethods />+ <ConfigProvider config={{ aAs: Link, imgAs: Image, imgUnoptimized: true }} motion={m}>+ <LazyMotion features={domMax}>{children}</LazyMotion>+ </ConfigProvider>+ </App>+ </ThemeProvider>+ );+});++ShareTheme.displayName = 'ShareTheme';++export default ShareTheme;diff --git a/apps/share/src/shell/clientOnly.tsx b/apps/share/src/shell/clientOnly.tsxnew file mode 100644index 00000000000..c818fd95284--- /dev/null+++ b/apps/share/src/shell/clientOnly.tsx@@ -0,0 +1,38 @@+'use client';++import { type ComponentType, lazy, type ReactNode, Suspense, useSyncExternalStore } from 'react';++const noopSubscribe = () => () => {};++const useHydrated = () =>+ useSyncExternalStore(+ noopSubscribe,+ () => true,+ () => false,+ );++/**+ * Keeps a subtree out of the server render. The SSR build resolves `*.client`+ * modules to an empty stub (see `share-client-only-stub` in vite.config.rr.mts),+ * so the gated graph never reaches the worker bundle at all.+ *+ * `fallback` is what the document ships and what hydration matches; pass the+ * static half of the view there so the client takeover is not a visible swap.+ */+export const clientOnly = <P extends object>(+ importFn: () => Promise<{ default: ComponentType<P> }>,+) => {+ const Component = lazy(importFn);++ return function ClientOnly({ fallback, ...props }: P & { fallback?: ReactNode }) {+ const hydrated = useHydrated();++ if (!hydrated) return fallback ?? null;++ return (+ <Suspense fallback={fallback ?? null}>+ <Component {...(props as P)} />+ </Suspense>+ );+ };+};diff --git a/apps/share/src/shell/createShareI18n.ts b/apps/share/src/shell/createShareI18n.tsnew file mode 100644index 00000000000..46ba0d6df15--- /dev/null+++ b/apps/share/src/shell/createShareI18n.ts@@ -0,0 +1,68 @@+import i18next from 'i18next';+import resourcesToBackend from 'i18next-resources-to-backend';+import { initReactI18next } from 'react-i18next';++import { DEFAULT_LANG } from '@/const/locale';+import { normalizeLocale } from '@/locales/resources';+import { unwrapESMModule } from '@/utils/esm/unwrapESMModule';+import { loadI18nNamespaceModule } from '@/utils/i18n/loadI18nNamespaceModule';++export type ShareResources = Record<string, Record<string, string>>;++// `error` is preloaded rather than fetched on demand: the boundary that needs+// it renders when something already failed, and a chunk-load failure is exactly+// the case where the client can never fetch the dictionary to correct itself.+export const shareNamespaces = ['chat', 'error', 'pageShare'] as const;++export const loadShareNamespace = async (lng: string, ns: string) => {+ const locale = normalizeLocale(lng);++ return unwrapESMModule(+ await loadI18nNamespaceModule({+ defaultLang: DEFAULT_LANG,+ lng: locale,+ normalizeLocale,+ ns,+ }),+ );+};++export const loadShareResources = async (lang?: string) => {+ const locale = normalizeLocale(lang);+ const entries = await Promise.all(+ shareNamespaces.map(async (ns) => [ns, await loadShareNamespace(locale, ns)] as const),+ );++ return Object.fromEntries(entries) as ShareResources;+};++export const createShareI18n = (lang?: string, bundledResources?: ShareResources) => {+ const locale = normalizeLocale(lang);+ const resources = bundledResources ? { [locale]: bundledResources } : undefined;++ const instance = i18next+ .createInstance()+ .use(initReactI18next)+ .use(resourcesToBackend(loadShareNamespace));++ return {+ init: (params: { initAsync?: boolean } = {}) =>+ instance.init({+ defaultNS: 'chat',+ fallbackLng: DEFAULT_LANG,+ initAsync: params.initAsync ?? true,+ interpolation: { escapeValue: false },+ keySeparator: false,+ lng: locale,+ ns: [],+ partialBundledLanguages: true,+ react: {+ bindI18nStore: 'added',+ useSuspense: false,+ },+ resources,+ showSupportNotice: false,+ }),+ instance,+ };+};diff --git a/apps/share/src/shell/index.ts b/apps/share/src/shell/index.tsnew file mode 100644index 00000000000..e19c3bc35cf--- /dev/null+++ b/apps/share/src/shell/index.ts@@ -0,0 +1,2 @@+export { default } from './ShareAppShell';+export { default as ShareNamespace } from './ShareNamespace';diff --git a/apps/share/src/vite-env.d.ts b/apps/share/src/vite-env.d.tsnew file mode 100644index 00000000000..11f02fe2a00--- /dev/null+++ b/apps/share/src/vite-env.d.ts@@ -0,0 +1 @@+/// <reference types="vite/client" />diff --git a/apps/share/staticCssOptions.mjs b/apps/share/staticCssOptions.mjsnew file mode 100644index 00000000000..987e0985f9c--- /dev/null+++ b/apps/share/staticCssOptions.mjs@@ -0,0 +1,9 @@+const cdnBase = (process.env.VITE_CDN_BASE || '').replace(/\/+$/, '');++export const antdStaticCssOptions = {+ hrefTemplate: (hash) => `${cdnBase}/assets/antd-${hash}.css`,+};++export const themeVarsCssOptions = {+ hrefTemplate: (hash) => `${cdnBase}/assets/theme-vars-${hash}.css`,+};diff --git a/apps/share/tsconfig.json b/apps/share/tsconfig.jsonnew file mode 100644index 00000000000..7b3b82be5da--- /dev/null+++ b/apps/share/tsconfig.json@@ -0,0 +1,21 @@+{+ "compilerOptions": {+ "plugins": [],+ "types": ["vite/client"]+ },+ "exclude": ["node_modules"],+ "extends": "../../tsconfig.json",+ "include": [+ "src/**/*.ts",+ "src/**/*.tsx",+ "app/**/*.ts",+ "app/**/*.tsx",+ "workers/**/*.ts",+ "vite.config.ts",+ "vite.config.rr.mts",+ "react-router.config.ts",+ "../../src/types/global.d.ts",+ "../../packages/agent-templates/src/templates/claw/raw.d.ts",+ "../../packages/builtin-skills/src/raw.d.ts"+ ]+}diff --git a/apps/share/vite.config.rr.mts b/apps/share/vite.config.rr.mtsnew file mode 100644index 00000000000..55662b56ac4--- /dev/null+++ b/apps/share/vite.config.rr.mts@@ -0,0 +1,41 @@+import path from 'node:path';++import tsconfigPaths from 'vite-tsconfig-paths';++import { antdStaticCssOptions, themeVarsCssOptions } from './staticCssOptions.mjs';+import { createShareRrConfig } from './vite.config.shared.mts';++const appRoot = path.resolve(import.meta.dirname);++// A host repo that overlays this app (lobehub-cloud maps `@/business/*` and+// friends onto its own implementations) points this at its root tsconfig.+// Vite 8's native tsconfigPaths resolves against the tsconfig nearest each+// importer, which for submodule files is this repo's β losing the overlay.+const overlayTsconfig = process.env.SHARE_TSCONFIG_PROJECT;++const parseExtraStubs = (raw: string | undefined): Record<string, string> | undefined => {+ if (!raw) return undefined;++ return Object.fromEntries(+ raw+ .split(',')+ .map((entry) => entry.split('=').map((part) => part.trim()))+ .filter((pair): pair is [string, string] => pair.length === 2 && Boolean(pair[0] && pair[1])),+ );+};++export default createShareRrConfig({+ appRoot,+ extraSsrStubs: parseExtraStubs(process.env.SHARE_EXTRA_SSR_STUBS),+ repoRoot: overlayTsconfig ? path.dirname(overlayTsconfig) : path.resolve(appRoot, '../..'),+ resolvePlugins: overlayTsconfig+ ? [+ tsconfigPaths({+ ignoreConfigErrors: true,+ projects: [overlayTsconfig],+ root: path.dirname(overlayTsconfig),+ }),+ ]+ : undefined,+ staticCss: { antd: antdStaticCssOptions, themeVars: themeVarsCssOptions },+});diff --git a/apps/share/vite.config.shared.mts b/apps/share/vite.config.shared.mtsnew file mode 100644index 00000000000..f72583dce94--- /dev/null+++ b/apps/share/vite.config.shared.mts@@ -0,0 +1,248 @@+import { writeFileSync } from 'node:fs';+import path from 'node:path';++import { cloudflare } from '@cloudflare/vite-plugin';+import { lobeStaticCssPlugin } from '@lobehub/ui/static-css/vite';+import { reactRouter } from '@react-router/dev/vite';+import { defineConfig, type Plugin, type PluginOption } from 'vite';++import { lobeIconImports } from '../../plugins/vite/lobeIconImports';+import { viteMarkdownImport } from '../../plugins/vite/markdownImport';+import { viteNodeModuleStub } from '../../plugins/vite/nodeModuleStub';+import { vitePlatformResolve } from '../../plugins/vite/platformResolve';+import {+ sharedRendererDedupe,+ sharedRendererDefine,+} from '../../plugins/vite/sharedRendererConfig';++interface StaticCssOptions {+ hrefTemplate: (hash: string) => string;+}++export interface ShareRrConfigOptions {+ /** Directory holding `app/` and `src/` β the submodule copy when a host repo overlays this app. */+ appRoot: string;+ /**+ * Extra SSR module stubs, by import specifier. A host repo overlaying this+ * app adds the store hubs only its own code reaches β the worker renders no+ * signed-in surface, so those must not enter its graph.+ */+ extraSsrStubs?: Record<string, string>;+ /** Repo whose files count as build inputs and are allowed by the dev server. */+ repoRoot: string;+ /**+ * Resolution for `@/*`. Vite 8 native tsconfigPaths walks to the tsconfig+ * nearest each importer, which loses a host repo's overlay paths β those+ * hosts pass their own resolver plugin here instead.+ */+ resolvePlugins?: PluginOption[];+ staticCss: { antd: StaticCssOptions; themeVars: StaticCssOptions };+}++const CLIENT_MODULE_RE = /\.client(?:\.[jt]sx?)?$/;++export const createShareRrConfig = ({+ appRoot,+ extraSsrStubs,+ repoRoot,+ resolvePlugins,+ staticCss,+}: ShareRrConfigOptions) => {+ const define = sharedRendererDefine({ isElectron: false, isMobile: false });+ const { 'process.env': _processEnvFallback, ...ssrDefine } = define;++ const stub = (file: string) => path.resolve(appRoot, 'app/stubs', file);++ const ssrStubs: Record<string, string> = {+ '@/libs/trpc/client': stub('trpcClient.ts'),+ '@/services/global': stub('globalService.ts'),+ '@/spa/initialize/toolSurfaces': stub('toolSurfaces.ts'),+ '@/store/electron': stub('electronStore.ts'),+ '@/store/file': stub('fileStore.ts'),+ '@/store/user': stub('userStore.ts'),+ '@/utils/i18n/loadI18nNamespaceModule': stub('loadI18nNamespaceModule.ts'),+ 'shiki': stub('shiki.ts'),+ 'shiki/wasm': stub('shikiWasm.ts'),+ ...extraSsrStubs,+ };++ const shareSsrStubs = (): Plugin => ({+ applyToEnvironment: (environment) => environment.name === 'ssr',+ enforce: 'pre',+ name: 'share-ssr-stubs',+ resolveId(source) {+ return ssrStubs[source];+ },+ });++ // `clientOnly()` gates rendering, but the dynamic import still pulls the gated+ // graph into the worker bundle. Cutting it at resolve time is what actually+ // keeps the conversation stack out of build/server.+ const shareClientOnlyStub = (): Plugin => ({+ applyToEnvironment: (environment) => environment.name === 'ssr',+ name: 'share-client-only-stub',+ async resolveId(source, importer, options) {+ if (!CLIENT_MODULE_RE.test(source)) return null;++ const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });+ if (!resolved || !resolved.id.startsWith(appRoot)) return null;++ return stub('clientOnlyModule.tsx');+ },+ });++ const ssrChunkReport = (): Plugin => ({+ applyToEnvironment: (environment) => environment.name === 'ssr',+ generateBundle(_options, bundle) {+ const report: Record<string, unknown> = {};+ for (const [file, chunk] of Object.entries(bundle)) {+ if (chunk.type !== 'chunk') continue;+ report[file] = {+ dynamicImports: chunk.dynamicImports,+ imports: chunk.imports,+ modules: Object.keys(chunk.modules ?? {}),+ size: chunk.code.length,+ };+ }+ writeFileSync(path.resolve('ssr-chunk-report.json'), JSON.stringify(report));+ },+ name: 'share-ssr-chunk-report',+ });++ const ssrModuleTrace = (needle: string): Plugin => ({+ applyToEnvironment: (environment) =>+ environment.name === (process.env.SHARE_TRACE_ENV || 'ssr'),+ buildEnd() {+ const targets = [...this.getModuleIds()].filter((id) => id.includes(needle));+ for (const target of targets.slice(0, 2)) {+ const parent = new Map<string, string | null>([[target, null]]);+ const queue = [target];+ let found: string | null = null;+ while (queue.length > 0 && !found) {+ const current = queue.shift()!;+ const info = this.getModuleInfo(current);+ for (const importer of [...(info?.importers ?? []), ...(info?.dynamicImporters ?? [])]) {+ if (parent.has(importer)) continue;+ parent.set(importer, current);+ queue.push(importer);+ if (importer.startsWith(appRoot) || importer.includes('virtual:react-router')) {+ found = importer;+ break;+ }+ }+ }+ const chain: string[] = [];+ let cursor: string | null = found;+ while (cursor) {+ chain.push(cursor);+ cursor = parent.get(cursor) ?? null;+ }+ console.info(`\n=== module trace: ${target}`);+ console.info(chain.join('\n -> ') || '(no importer path found)');+ }+ },+ name: 'share-ssr-module-trace',+ });++ const buildInputIds = new Set<string>();++ const buildInputsManifest = (): Plugin => ({+ apply: 'build',+ buildEnd() {+ for (const id of this.getModuleIds()) {+ if (!id.startsWith(repoRoot)) continue;+ if (id.includes('/node_modules/') || id.includes('\0')) continue;+ buildInputIds.add(path.relative(repoRoot, id.split('?')[0]!));+ }+ },+ name: 'share-build-inputs-manifest',+ writeBundle(options) {+ if (!options.dir?.includes('build/server')) return;+ const manifest = [...buildInputIds].sort().join('\n');+ writeFileSync(path.resolve('build-inputs.txt'), `${manifest}\n`);+ },+ });++ const staticCssDevServe = (): Plugin => {+ const cache = new Map<string, string>();+ const serve = async (kind: 'antd' | 'themeVars') => {+ if (!cache.has(kind)) {+ const { buildAntdStaticCss, buildThemeVarsCss } = await import('@lobehub/ui/static-css');+ cache.set(+ kind,+ kind === 'antd'+ ? buildAntdStaticCss(staticCss.antd).css+ : buildThemeVarsCss(staticCss.themeVars).css,+ );+ }+ return cache.get(kind)!;+ };++ return {+ apply: 'serve',+ configureServer(server) {+ server.middlewares.use(async (req, res, next) => {+ const url = req.url ?? '';+ const kind = /^\/assets\/antd-[a-f0-9]+\.css/.test(url)+ ? ('antd' as const)+ : /^\/assets\/theme-vars-[a-f0-9]+\.css/.test(url)+ ? ('themeVars' as const)+ : undefined;+ if (!kind) return next();+ res.setHeader('Content-Type', 'text/css; charset=utf-8');+ res.setHeader('Cache-Control', 'no-cache');+ res.end(await serve(kind));+ });+ },+ name: 'share-static-css-dev-serve',+ };+ };++ const proxyTarget = process.env.SHARE_API_PROXY || 'https://app.lobehub.com';+ const backendProxy = Object.fromEntries(+ ['/api', '/oidc', '/trpc', '/webapi'].map((prefix) => [+ prefix,+ { changeOrigin: true, target: proxyTarget },+ ]),+ );++ const isDev = process.env.NODE_ENV !== 'production';++ return defineConfig({+ base: isDev ? '/' : process.env.VITE_CDN_BASE || '/',+ environments: {+ client: { define },+ ssr: { define: ssrDefine },+ },+ plugins: [+ process.env.SHARE_CHUNK_REPORT ? ssrChunkReport() : undefined,+ process.env.SHARE_TRACE_MODULE ? ssrModuleTrace(process.env.SHARE_TRACE_MODULE) : undefined,+ shareSsrStubs(),+ shareClientOnlyStub(),+ buildInputsManifest(),+ viteMarkdownImport(),+ viteNodeModuleStub(),+ vitePlatformResolve('web'),+ cloudflare({ viteEnvironment: { name: 'ssr' } }),+ lobeStaticCssPlugin({ antd: staticCss.antd, themeVars: staticCss.themeVars }),+ staticCssDevServe(),+ reactRouter(),+ ...lobeIconImports(),+ ...(resolvePlugins ?? []),+ ],+ resolve: {+ // The builtin-tool packages declare `@lobehub/ui: ^5` and resolve to an+ // older copy than the app's; without deduping, their render surfaces fail+ // to import components that only exist in the app's version.+ dedupe: [...sharedRendererDedupe, '@lobehub/ui'],+ tsconfigPaths: !resolvePlugins,+ },+ server: {+ fs: {+ allow: [repoRoot],+ },+ port: Number(process.env.SHARE_SPA_PORT_RR) || 3017,+ proxy: backendProxy,+ },+ });+};diff --git a/apps/share/vite.config.ts b/apps/share/vite.config.tsnew file mode 100644index 00000000000..45b3579a558--- /dev/null+++ b/apps/share/vite.config.ts@@ -0,0 +1,77 @@+import path from 'node:path';++import type { PluginOption } from 'vite';+import { defineConfig, loadEnv } from 'vite';+import tsconfigPaths from 'vite-tsconfig-paths';++import { viteEnvRestartKeys } from '../../plugins/vite/envRestartKeys';+import {+ createSharedRolldownOutput,+ sharedModulePreload,+ sharedOptimizeDeps,+ sharedRendererDedupe,+ sharedRendererDefine,+ sharedRendererPlugins,+} from '../../plugins/vite/sharedRendererConfig';+import { vercelSkewProtection } from '../../plugins/vite/vercelSkewProtection';+import { createViteWatchOptions } from '../../plugins/vite/watchOptions';++const repoRoot = path.resolve(__dirname, '../..');+const mode = process.env.NODE_ENV === 'production' ? 'production' : 'development';++Object.assign(process.env, loadEnv(mode, repoRoot, ''));++const isDev = process.env.NODE_ENV !== 'production';++export default defineConfig({+ base: isDev ? '/' : process.env.VITE_CDN_BASE || '/_spa-share/',+ build: {+ emptyOutDir: true,+ modulePreload: sharedModulePreload,+ outDir: path.resolve(repoRoot, 'dist/share'),+ reportCompressedSize: false,+ rolldownOptions: {+ output: createSharedRolldownOutput({ strictExecutionOrder: true }),+ },+ },+ define: {+ ...sharedRendererDefine({ isElectron: false, isMobile: false }),+ },+ experimental: {+ bundledDev: false,+ },+ optimizeDeps: sharedOptimizeDeps,+ plugins: [+ tsconfigPaths({+ ignoreConfigErrors: true,+ projects: [path.resolve(repoRoot, 'tsconfig.json')],+ root: repoRoot,+ }),+ vercelSkewProtection(),+ viteEnvRestartKeys(['APP_URL']),+ ...sharedRendererPlugins({ platform: 'web' }),+ ].filter(Boolean) as PluginOption[],+ resolve: {+ // The builtin-tool packages declare `@lobehub/ui: ^5` and resolve to an+ // older copy than the app's; without deduping, their render surfaces fail+ // to import components that only exist in the app's version.+ dedupe: [...sharedRendererDedupe, '@lobehub/ui'],+ },+ root: __dirname,+ server: {+ cors: true,+ fs: {+ allow: [repoRoot],+ },+ host: true,+ port: Number(process.env.SHARE_SPA_PORT) || 3016,+ proxy: {+ '/api': `http://localhost:${process.env.PORT || 3010}`,+ '/oidc': `http://localhost:${process.env.PORT || 3010}`,+ '/trpc': `http://localhost:${process.env.PORT || 3010}`,+ '/webapi': `http://localhost:${process.env.PORT || 3010}`,+ },+ strictPort: true,+ watch: createViteWatchOptions([repoRoot]),+ },+});diff --git a/apps/share/workers/app.ts b/apps/share/workers/app.tsnew file mode 100644index 00000000000..c40488199f1--- /dev/null+++ b/apps/share/workers/app.ts@@ -0,0 +1,31 @@+import { createRequestHandler, RouterContextProvider } from 'react-router';++import { cloudflareContext, type WorkerExecutionContext } from '../app/lib/cloudflareContext';++const API_PREFIXES = ['/api', '/oidc', '/trpc', '/webapi'];++const isApiPath = (pathname: string) =>+ API_PREFIXES.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));++const requestHandler = createRequestHandler(+ () => import('virtual:react-router/server-build'),+ import.meta.env.MODE,+);++export default {+ fetch(request: Request, env: Record<string, unknown>, ctx: WorkerExecutionContext) {+ const url = new URL(request.url);++ // Standalone deployments have no reverse proxy in front: forward the SPA's+ // same-origin API calls to the backend, mirroring vite's dev proxy.+ const apiBase = env.SHARE_API_BASE as string | undefined;+ if (apiBase && isApiPath(url.pathname)) {+ const target = new URL(url.pathname + url.search, apiBase);+ return fetch(new Request(target, request));+ }++ const context = new RouterContextProvider();+ context.set(cloudflareContext, { ctx, env });+ return requestHandler(request, context);+ },+};diff --git a/apps/share/wrangler.jsonc b/apps/share/wrangler.jsoncnew file mode 100644index 00000000000..d8745de7cc3--- /dev/null+++ b/apps/share/wrangler.jsonc@@ -0,0 +1,17 @@+{+ "$schema": "../../node_modules/wrangler/config-schema.json",+ "name": "lobehub-share",+ "account_id": "d35842305b91be4b48e06ff9a9ad83f5",+ "main": "./workers/app.ts",+ "compatibility_date": "2026-08-01",+ "compatibility_flags": ["nodejs_compat"],+ "observability": {+ "enabled": true,+ "head_sampling_rate": 1,+ "logs": { "invocation_logs": false }+ },+ "vars": {+ "SHARE_API_BASE": "https://app.lobehub.com",+ "SHARE_APP_HOME": "https://lobehub.com"+ }+}diff --git a/apps/workbench/app/root.tsx b/apps/workbench/app/root.tsxindex a4359b00bc7..6be78dc7709 100644--- a/apps/workbench/app/root.tsx+++ b/apps/workbench/app/root.tsx@@ -16,27 +16,15 @@ import { href as themeVarsCssHref } from 'virtual:lobehub/theme-vars-css';import ErrorCapture, { type ErrorType } from '@/components/Error';import NextThemeProvider from '@/layout/GlobalProvider/NextThemeProvider';-import { normalizeLocale } from '@/locales/resources';+import { resolveRequestLocale } from '@/locales/requestLocale';import { isChunkLoadError, notifyChunkError } from '@/utils/chunkError';import WorkbenchShell from '../src/shell';import { loadWorkbenchResources } from '../src/shell/createWorkbenchI18n';import { buildPageMeta, workbenchMetaDescription } from './lib/seo';-const pickLocale = (request: Request) => {- const url = new URL(request.url);- const hl = url.searchParams.get('hl');- const cookie = request.headers.get('cookie') ?? '';- const cookieLocale = decodeURIComponent(/(?:^|;\s*)LOBE_LOCALE=([^;]*)/.exec(cookie)?.[1] ?? '');- const acceptLocale = request.headers.get('accept-language')?.split(',')[0]?.trim() ?? '';-- const raw = hl || cookieLocale || acceptLocale || 'en-US';-- return normalizeLocale(raw === 'auto' ? acceptLocale || 'en-US' : raw);-};-export const loader = async ({ request }: LoaderFunctionArgs) => {- const locale = pickLocale(request);+ const locale = resolveRequestLocale(request);const resources = await loadWorkbenchResources(locale);return {diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 5f5f2d172e2..c049814ab18 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1258,6 +1258,8 @@"sharePage.menu.goToLobeHub": "Go to LobeHub","sharePage.menu.more": "More","sharePage.menu.report": "Report",+ "sharePage.meta.pageDescription": "A page shared from {{appName}}.",+ "sharePage.meta.topicDescription": "A conversation shared from {{appName}}.","sharePage.pill.edit": "Edit","sharePage.pill.openInApp": "Open in {{appName}}","sharePage.pill.sharedVia": "Shared via {{appName}}",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 67b09a3de78..cb9fb209583 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1258,6 +1258,8 @@"sharePage.menu.goToLobeHub": "εεΎ LobeHub","sharePage.menu.more": "ζ΄ε€","sharePage.menu.report": "δΈΎζ₯",+ "sharePage.meta.pageDescription": "εδΊ«θͺ {{appName}} ηι‘΅ι’γ",+ "sharePage.meta.topicDescription": "εδΊ«θͺ {{appName}} ηε―Ήθ―γ","sharePage.pill.edit": "ηΌθΎ","sharePage.pill.openInApp": "ε¨ {{appName}} δΈζεΌ","sharePage.pill.sharedVia": "εδΊ«θͺ {{appName}}",diff --git a/package.json b/package.jsonindex bbb5ec958c4..0a2a8abaf97 100644--- a/package.json+++ b/package.json@@ -37,20 +37,22 @@"packages/business/*","e2e","apps/desktop/src/main",+ "apps/share","apps/workbench"],"scripts": {- "build": "bun run build:spa && bun run build:spa:auth && bun run build:spa:workbench && bun run build:spa:copy && bun run build:next",+ "build": "bun run build:spa && bun run build:spa:auth && bun run build:spa:workbench && bun run build:spa:share && bun run build:spa:copy && bun run build:next","build:analyze": "cross-env NODE_OPTIONS=--max-old-space-size=81920 next experimental-analyze",- "build:docker": "pnpm run build:spa && pnpm run build:spa:mobile && pnpm run build:spa:auth && pnpm run build:spa:workbench && cross-env WORKBENCH_REQUIRED=1 pnpm run build:spa:copy && cross-env NODE_OPTIONS=--max-old-space-size=8192 DOCKER=true next build",+ "build:docker": "pnpm run build:spa && pnpm run build:spa:mobile && pnpm run build:spa:auth && pnpm run build:spa:workbench && pnpm run build:spa:share && cross-env WORKBENCH_REQUIRED=1 SHARE_REQUIRED=1 pnpm run build:spa:copy && cross-env NODE_OPTIONS=--max-old-space-size=8192 DOCKER=true next build","build:next": "cross-env NODE_OPTIONS=--max-old-space-size=7168 bun run build:next:raw","build:next:raw": "next build",- "build:raw": "bun run build:spa:raw && bun run build:spa:auth && bun run build:spa:workbench && bun run build:spa:copy && bun run build:next:raw",+ "build:raw": "bun run build:spa:raw && bun run build:spa:auth && bun run build:spa:workbench && bun run build:spa:share && bun run build:spa:copy && bun run build:next:raw","build:spa": "cross-env NODE_OPTIONS=--max-old-space-size=8192 pnpm run build:spa:raw","build:spa:auth": "rm -rf public/_spa public/_spa-auth && cross-env NODE_OPTIONS=--max-old-space-size=8192 AUTH=true vite build","build:spa:copy": "tsx scripts/copySpaBuild.mts && tsx scripts/generateSpaTemplates.mts","build:spa:mobile": "cross-env NODE_OPTIONS=--max-old-space-size=8192 MOBILE=true vite build","build:spa:raw": "rm -rf public/_spa && vite build",+ "build:spa:share": "rm -rf dist/share public/_spa-share && cross-env NODE_OPTIONS=--max-old-space-size=8192 pnpm --filter @lobehub/share build","build:spa:workbench": "rm -rf dist/workbench public/_spa-workbench && cross-env NODE_OPTIONS=--max-old-space-size=8192 pnpm --filter @lobehub/workbench build","build:vercel": "cross-env-shell NODE_OPTIONS=--max-old-space-size=8192 \"bun run build:raw && bun run db:migrate\"","build-migrate-db": "bun run db:migrate",@@ -78,6 +80,7 @@"dev:spa": "vite","dev:spa:auth": "cross-env AUTH=true vite","dev:spa:mobile": "cross-env MOBILE=true vite",+ "dev:spa:share": "pnpm --filter @lobehub/share dev","dev:spa:workbench": "pnpm --filter @lobehub/workbench dev","docs:cdn": "npm run workflow:docs-cdn && npm run lint:mdx","docs:i18n": "lobe-i18n md && npm run lint:mdx",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex d866b0b6cf6..00ba2ee1cb4 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1318,6 +1318,8 @@ export default {'sharePage.menu.goToLobeHub': 'Go to LobeHub','sharePage.menu.more': 'More','sharePage.menu.report': 'Report',+ 'sharePage.meta.pageDescription': 'A page shared from {{appName}}.',+ 'sharePage.meta.topicDescription': 'A conversation shared from {{appName}}.','sharePage.pill.edit': 'Edit','sharePage.pill.openInApp': 'Open in {{appName}}','sharePage.pill.sharedVia': 'Shared via {{appName}}',diff --git a/packages/locales/src/requestLocale.test.ts b/packages/locales/src/requestLocale.test.tsnew file mode 100644index 00000000000..43cfe685c1f--- /dev/null+++ b/packages/locales/src/requestLocale.test.ts@@ -0,0 +1,92 @@+import { describe, expect, it } from 'vitest';++import { resolveRequestLocale } from './requestLocale';++const request = ({+ cookie,+ language,+ url,+}: { cookie?: string; language?: string; url?: string } = {}) => {+ const headers = new Headers();+ if (cookie) headers.set('cookie', cookie);+ if (language) headers.set('accept-language', language);++ return new Request(url ?? 'https://lobehub.com/share/t/abc', { headers });+};++describe('resolveRequestLocale', () => {+ it('prefers the hl query over the cookie and the browser', () => {+ expect(+ resolveRequestLocale(+ request({+ cookie: 'LOBE_LOCALE=ja-JP',+ language: 'ko-KR',+ url: 'https://lobehub.com/share/t/abc?hl=zh-CN',+ }),+ ),+ ).toBe('zh-CN');+ });++ it('prefers the cookie over the browser', () => {+ expect(resolveRequestLocale(request({ cookie: 'LOBE_LOCALE=ja-JP', language: 'ko-KR' }))).toBe(+ 'ja-JP',+ );+ });++ it('reads the cookie among other cookies and decodes it', () => {+ expect(+ resolveRequestLocale(request({ cookie: 'foo=1; LOBE_LOCALE=zh-CN; NEXT_LOCALE=en' })),+ ).toBe('zh-CN');+ expect(resolveRequestLocale(request({ cookie: 'LOBE_LOCALE=zh%2DCN' }))).toBe('zh-CN');+ });++ it('survives a cookie with a malformed percent-escape', () => {+ expect(resolveRequestLocale(request({ cookie: 'LOBE_LOCALE=%E0%A4%A' }))).toBe('en-US');+ });++ it('honours Accept-Language quality weights over header order', () => {+ expect(resolveRequestLocale(request({ language: 'zh-CN;q=0.2,en-US;q=0.9' }))).toBe('en-US');+ expect(resolveRequestLocale(request({ language: 'en-US;q=0.2,zh-CN;q=0.9' }))).toBe('zh-CN');+ });++ it('keeps header order when no weights are given', () => {+ expect(resolveRequestLocale(request({ language: 'ja-JP,en-US' }))).toBe('ja-JP');+ });++ it('skips wildcards and unsupported tags to reach a supported one', () => {+ expect(resolveRequestLocale(request({ language: '*,xx-YY;q=0.9,ja-JP;q=0.8' }))).toBe('ja-JP');+ });++ it('matches Accept-Language case-insensitively', () => {+ expect(resolveRequestLocale(request({ language: 'zh-cn' }))).toBe('zh-CN');+ expect(resolveRequestLocale(request({ language: 'zh-Hans-CN' }))).toBe('zh-CN');+ expect(resolveRequestLocale(request({ language: 'zh-Hant-TW' }))).toBe('zh-TW');+ });++ it('falls back to the default for an explicit locale that is not supported', () => {+ expect(+ resolveRequestLocale(+ request({ language: 'zh-CN', url: 'https://lobehub.com/share/t/abc?hl=klingon' }),+ ),+ ).toBe('en-US');+ expect(+ resolveRequestLocale(request({ cookie: 'LOBE_LOCALE=klingon', language: 'zh-CN' })),+ ).toBe('en-US');+ });++ it('defers to the browser when the explicit locale is auto', () => {+ expect(resolveRequestLocale(request({ cookie: 'LOBE_LOCALE=auto', language: 'ja-JP' }))).toBe(+ 'ja-JP',+ );+ expect(+ resolveRequestLocale(+ request({ language: 'ja-JP', url: 'https://lobehub.com/share/t/abc?hl=auto' }),+ ),+ ).toBe('ja-JP');+ });++ it('falls back to the default with no locale signal at all', () => {+ expect(resolveRequestLocale(request())).toBe('en-US');+ expect(resolveRequestLocale(request({ language: '' }))).toBe('en-US');+ });+});diff --git a/packages/locales/src/requestLocale.ts b/packages/locales/src/requestLocale.tsnew file mode 100644index 00000000000..75f6eec3b42--- /dev/null+++ b/packages/locales/src/requestLocale.ts@@ -0,0 +1,73 @@+import { DEFAULT_LANG, LOBE_LOCALE_COOKIE } from '@/const/locale';++import { type Locales, matchLocale, normalizeLocale } from './resources';++const LOCALE_QUERY = 'hl';+const AUTO_LOCALE = 'auto';++const decodeCookieValue = (value: string) => {+ try {+ return decodeURIComponent(value);+ } catch {+ // A cookie carrying a malformed percent-escape must not take an SSR render down.+ return value;+ }+};++const readCookie = (cookieHeader: string | null, name: string): string | undefined => {+ if (!cookieHeader) return undefined;++ for (const part of cookieHeader.split(';')) {+ const separatorIndex = part.indexOf('=');+ if (separatorIndex === -1) continue;++ if (part.slice(0, separatorIndex).trim() !== name) continue;++ return decodeCookieValue(part.slice(separatorIndex + 1).trim());+ }++ return undefined;+};++// Accept-Language is case-insensitive, but the supported list is canonical+// BCP 47 β without this `zh-cn` misses `zh-CN` and silently degrades to English.+const canonicalizeTag = (tag: string) => {+ const [language, ...rest] = tag.split('-');++ return [+ language!.toLowerCase(),+ ...rest.map((part) => (part.length === 2 ? part.toUpperCase() : part)),+ ].join('-');+};++const parseAcceptLanguage = (header: string | null): string[] =>+ (header ?? '')+ .split(',')+ .map((part) => {+ const [tag, ...params] = part.trim().split(';');+ const quality = params.map((param) => param.trim()).find((param) => param.startsWith('q='));+ const weight = quality ? Number(quality.slice(2)) : 1;++ return { tag: tag?.trim() ?? '', weight: Number.isFinite(weight) ? weight : 0 };+ })+ .filter((candidate) => candidate.tag.length > 0 && candidate.tag !== '*')+ .sort((a, b) => b.weight - a.weight)+ .map((candidate) => candidate.tag);++// An explicit choice naming no supported locale falls back to the default instead of+// deferring to the browser, matching the lobehub gateway's `resolveOriginPathVars`: a+// request routed through the gateway and one hitting a worker directly must agree.+export const resolveRequestLocale = (request: Request): Locales => {+ const explicit =+ new URL(request.url).searchParams.get(LOCALE_QUERY) ||+ readCookie(request.headers.get('cookie'), LOBE_LOCALE_COOKIE);++ if (explicit && explicit !== AUTO_LOCALE) return normalizeLocale(canonicalizeTag(explicit));++ for (const tag of parseAcceptLanguage(request.headers.get('accept-language'))) {+ const matched = matchLocale(canonicalizeTag(tag));+ if (matched) return matched;+ }++ return DEFAULT_LANG;+};diff --git a/packages/locales/src/resources.test.ts b/packages/locales/src/resources.test.tsindex cbf74e2624a..e3533863c03 100644--- a/packages/locales/src/resources.test.ts+++ b/packages/locales/src/resources.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { normalizeLocale } from './resources';+import { matchLocale, normalizeLocale } from './resources';describe('normalizeLocale', () => {it('should return "en-US" when locale is undefined', () => {@@ -47,3 +47,17 @@ describe('normalizeLocale', () => {expect(normalizeLocale('fr')).toBe('fr-FR');});});++describe('matchLocale', () => {+ it('should return undefined when nothing is supported', () => {+ expect(matchLocale()).toBeUndefined();+ expect(matchLocale('unknown')).toBeUndefined();+ expect(matchLocale('en-GB')).toBeUndefined();+ });++ it('should return the matched locale', () => {+ expect(matchLocale('en')).toBe('en-US');+ expect(matchLocale('zh-Hant')).toBe('zh-TW');+ expect(matchLocale('ar-EG')).toBe('ar');+ });+});diff --git a/packages/locales/src/resources.ts b/packages/locales/src/resources.tsindex 62d504027f0..a2f240b1672 100644--- a/packages/locales/src/resources.ts+++ b/packages/locales/src/resources.ts@@ -27,8 +27,8 @@ export type DefaultResources = typeof resources;export type NS = keyof DefaultResources;export type Locales = (typeof locales)[number];-export const normalizeLocale = (locale?: string): Locales => {- if (!locale) return DEFAULT_LANG;+export const matchLocale = (locale?: string): Locales | undefined => {+ if (!locale) return undefined;const lowerLocale = locale.toLowerCase();@@ -39,15 +39,11 @@ export const normalizeLocale = (locale?: string): Locales => {if (lowerLocale.startsWith('zh-hans')) return 'zh-CN';if (lowerLocale.startsWith('zh-hant')) return 'zh-TW';- for (const l of locales) {- if (l.startsWith(locale)) {- return l;- }- }-- return DEFAULT_LANG;+ return locales.find((l) => l.startsWith(locale));};+export const normalizeLocale = (locale?: string): Locales => matchLocale(locale) ?? DEFAULT_LANG;+type LocaleOptions = {label: string;value: Locales;diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex cefe61f6349..f9191e2e68d 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -5,6 +5,7 @@ packages:- e2e- apps/desktop/src/main- apps/server+ - apps/share- apps/workbenchminimumReleaseAgeExclude:diff --git a/scripts/copySpaBuildCore.ts b/scripts/copySpaBuildCore.tsindex 8d987354134..c379f7ca4ee 100644--- a/scripts/copySpaBuildCore.ts+++ b/scripts/copySpaBuildCore.ts@@ -14,6 +14,7 @@ const targets = [{ distDir: 'mobile', publicDir: 'public/_spa' },{ distDir: 'auth', publicDir: 'public/_spa-auth' },{ distDir: 'workbench', publicDir: 'public/_spa-workbench' },+ { distDir: 'share', publicDir: 'public/_spa-share' },] as const;export const copySpaBuild = (root = path.resolve(import.meta.dirname, '..')) => {diff --git a/scripts/generateSpaTemplates.mts b/scripts/generateSpaTemplates.mtsindex cdc7a0c180a..b900c1d4655 100644--- a/scripts/generateSpaTemplates.mts+++ b/scripts/generateSpaTemplates.mts@@ -1,7 +1,12 @@import { existsSync, readFileSync, writeFileSync } from 'node:fs';import path from 'node:path';-import { requireWorkbenchHtmlPath, resolveWorkbenchHtmlPath } from './spaHtmlPaths.ts';+import {+ requireShareHtmlPath,+ requireWorkbenchHtmlPath,+ resolveShareHtmlPath,+ resolveWorkbenchHtmlPath,+} from './spaHtmlPaths.ts';const root = path.resolve(import.meta.dirname, '..');@@ -90,3 +95,22 @@ export const workbenchHtmlTemplate = ${JSON.stringify(workbenchHtml)};} else {console.log('Skipped workbenchHtmlTemplate.ts (no dist/workbench build)');}++const resolvedShareHtmlPath =+ process.env.SHARE_REQUIRED === '1' ? requireShareHtmlPath(root) : resolveShareHtmlPath(root);++if (resolvedShareHtmlPath) {+ const shareHtml = readFileSync(resolvedShareHtmlPath, 'utf8');++ const shareOutput = `// Auto-generated by scripts/generateSpaTemplates.mts after vite build+// Do not edit manually++export const shareHtmlTemplate = ${JSON.stringify(shareHtml)};+`;++ writeFileSync(path.resolve(root, 'src/app/spa-share/shareHtmlTemplate.ts'), shareOutput, 'utf8');++ console.log('Generated shareHtmlTemplate.ts');+} else {+ console.log('Skipped shareHtmlTemplate.ts (no dist/share build)');+}diff --git a/scripts/spaDevShells.test.ts b/scripts/spaDevShells.test.tsnew file mode 100644index 00000000000..4237a386cb5--- /dev/null+++ b/scripts/spaDevShells.test.ts@@ -0,0 +1,59 @@+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++const root = path.resolve(import.meta.dirname, '..');++const walk = (dir: string): string[] =>+ readdirSync(dir).flatMap((entry) => {+ const target = path.join(dir, entry);++ if (statSync(target).isDirectory()) return walk(target);++ return target.endsWith('route.ts') ? [target] : [];+ });++const devShells = walk(path.resolve(root, 'src/app'))+ .flatMap((file) => {+ const source = readFileSync(file, 'utf8');++ return [...source.matchAll(/fetchViteDevTemplate\('(\/[^']+\.html)'\)/g)].map((match) => ({+ file: path.relative(root, file),+ template: match[1]!,+ }));+ })+ .sort((a, b) => a.template.localeCompare(b.template));++const entrySrc = (html: string) =>+ html.match(/<script type="module" src="([^"]+)"><\/script>/)?.[1];++describe('dev SPA shells', () => {+ it('finds every route handler that fetches a named dev template', () => {+ expect(devShells.map((shell) => shell.template)).toEqual([+ '/index.auth.html',+ '/index.workbench.html',+ ]);+ });++ // Vite falls back to the main `index.html` for a missing root shell, so a typo+ // or a forgotten file boots the main SPA under the micro app's URL instead of+ // failing β silently, and only in dev.+ it.each(devShells)('$template exists at the repo root for $file', ({ template }) => {+ expect(existsSync(path.resolve(root, `.${template}`))).toBe(true);+ });++ it.each(+ devShells.filter(({ template }) =>+ existsSync(path.resolve(root, `apps/${template.slice(7, -5)}/index.html`)),+ ),+ )('$template points at its own app entry, not the main SPA', ({ template }) => {+ const app = template.slice(7, -5);+ const rootShell = readFileSync(path.resolve(root, `.${template}`), 'utf8');+ const appShell = readFileSync(path.resolve(root, `apps/${app}/index.html`), 'utf8');++ expect(entrySrc(rootShell)).toBe(`/apps/${app}/src/entry.tsx`);+ expect(entrySrc(appShell)).toBe('/src/entry.tsx');+ expect(rootShell.replace(`/apps/${app}/src/entry.tsx`, '/src/entry.tsx')).toBe(appShell);+ });+});diff --git a/scripts/spaHtmlPaths.ts b/scripts/spaHtmlPaths.tsindex a3ab44c035a..1d46dc75b2a 100644--- a/scripts/spaHtmlPaths.ts+++ b/scripts/spaHtmlPaths.ts@@ -19,3 +19,22 @@ export const requireWorkbenchHtmlPath = (root: string) => {'Workbench SPA build is required: missing dist/workbench/index.workbench.html and dist/workbench/index.html',);};++export const resolveShareHtmlPath = (root: string) => {+ const preferred = path.resolve(root, 'dist/share/index.share.html');+ if (existsSync(preferred)) return preferred;++ const fallback = path.resolve(root, 'dist/share/index.html');+ if (existsSync(fallback)) return fallback;++ return undefined;+};++export const requireShareHtmlPath = (root: string) => {+ const resolved = resolveShareHtmlPath(root);+ if (resolved) return resolved;++ throw new Error(+ 'Share SPA build is required: missing dist/share/index.share.html and dist/share/index.html',+ );+};diff --git a/src/app/spa-share/[locale]/[[...path]]/route.ts b/src/app/spa-share/[locale]/[[...path]]/route.tsnew file mode 100644index 00000000000..0248a92d318--- /dev/null+++ b/src/app/spa-share/[locale]/[[...path]]/route.ts@@ -0,0 +1,85 @@+import { BRANDING_NAME, ORG_NAME } from '@lobechat/business-const';+import { OG_URL } from '@lobechat/const';++import { getServerFeatureFlagsValue } from '@/config/featureFlags';+import { OFFICIAL_URL } from '@/const/url';+import { isCustomORG } from '@/const/version';+import { appEnv } from '@/envs/app';+import { fileEnv } from '@/envs/file';+import { pythonEnv } from '@/envs/python';+import { translation } from '@/libs/i18n/serverTranslation';+import { buildAnalyticsConfig, renderSpaHtml } from '@/libs/spaHtml';+import { type Locales, normalizeLocale } from '@/locales/resources';+import { getServerGlobalConfig } from '@/server/globalConfig';+import { type SPAClientEnv, type SPAServerConfig } from '@/types/spaServerConfig';++export function generateStaticParams() {+ const staticLocales: Locales[] = ['en-US', 'zh-CN'];++ return staticLocales.map((locale) => ({ locale }));+}++// No dev branch here: share is developed against its own Vite server+// (`dev:spa:share`), and asking the main one for a shell it doesn't own gets the+// main SPA back through the HTML fallback β silently, since that responds 200.+async function getTemplate(): Promise<string> {+ const { shareHtmlTemplate } = await import('../../shareHtmlTemplate');++ return shareHtmlTemplate;+}++function buildClientEnv(): SPAClientEnv {+ return {+ marketBaseUrl: appEnv.MARKET_BASE_URL,+ pyodideIndexUrl: pythonEnv.NEXT_PUBLIC_PYODIDE_INDEX_URL,+ pyodidePipIndexUrl: pythonEnv.NEXT_PUBLIC_PYODIDE_PIP_INDEX_URL,+ s3FilePath: fileEnv.NEXT_PUBLIC_S3_FILE_PATH,+ };+}++// Self-hosted share pages render client-side, so the document carries the brand+// card rather than the shared topic β the same card `/share/*` got while it was+// part of the main SPA shell. Per-topic OG lives in the Cloudflare worker build.+async function buildSeoMeta(locale: string): Promise<string> {+ const { t } = await translation('metadata', locale);+ const title = t('chat.title', { appName: BRANDING_NAME });+ const description = t('chat.description', { appName: BRANDING_NAME });++ return [+ `<title>${title}</title>`,+ `<meta name="description" content="${description}" />`,+ '<meta name="robots" content="noindex, nofollow" />',+ `<meta property="og:title" content="${title}" />`,+ `<meta property="og:description" content="${description}" />`,+ `<meta property="og:type" content="article" />`,+ `<meta property="og:url" content="${OFFICIAL_URL}" />`,+ `<meta property="og:image" content="${OG_URL}" />`,+ `<meta property="og:site_name" content="${BRANDING_NAME}" />`,+ `<meta property="og:locale" content="${locale}" />`,+ `<meta name="twitter:card" content="summary_large_image" />`,+ `<meta name="twitter:title" content="${title}" />`,+ `<meta name="twitter:description" content="${description}" />`,+ `<meta name="twitter:image" content="${OG_URL}" />`,+ `<meta name="twitter:site" content="${isCustomORG ? `@${ORG_NAME}` : '@lobehub'}" />`,+ ].join('\n ');+}++export async function GET(+ _request: Request,+ { params }: { params: Promise<{ locale: string; path?: string[] }> },+) {+ const { locale: rawLocale } = await params;+ const locale = normalizeLocale(rawLocale);++ const spaConfig: SPAServerConfig = {+ analyticsConfig: buildAnalyticsConfig(),+ clientEnv: buildClientEnv(),+ config: await getServerGlobalConfig(),+ featureFlags: getServerFeatureFlagsValue(),+ isMobile: false,+ };++ const template = await getTemplate();++ return renderSpaHtml(template, { seoMeta: await buildSeoMeta(locale), serverConfig: spaConfig });+}diff --git a/src/app/spa-share/shareHtmlTemplate.d.ts b/src/app/spa-share/shareHtmlTemplate.d.tsnew file mode 100644index 00000000000..45860b6500a--- /dev/null+++ b/src/app/spa-share/shareHtmlTemplate.d.ts@@ -0,0 +1 @@+export declare const shareHtmlTemplate: string;diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsxindex 5988faaed5c..15aa4a6a10d 100644--- a/src/features/Conversation/ChatList/index.tsx+++ b/src/features/Conversation/ChatList/index.tsx@@ -220,7 +220,14 @@ const ChatList = memo<ChatListProps>(}if (feedback.showSkeleton) {- return <SkeletonList />;+ // The header is chrome, not async content: dropping it here blanks a+ // server-rendered title the moment the list mounts to fetch.+ return (+ <Flexbox height={'100%'} style={{ minHeight: 0, overflow: 'hidden' }}>+ {headerSlot}+ <SkeletonList />+ </Flexbox>+ );}const content =diff --git a/src/libs/next/proxy/define-config.test.ts b/src/libs/next/proxy/define-config.test.tsindex c9eeb0449a6..6e6ac30426a 100644--- a/src/libs/next/proxy/define-config.test.ts+++ b/src/libs/next/proxy/define-config.test.ts@@ -88,3 +88,24 @@ describe('defineConfig Workbench SPA rewrite', () => {expect(new URL(index!).pathname).toMatch(/^\/spa\/[^/]+\/agent\/agt_1\/docs$/);});});++describe('defineConfig Share SPA rewrite', () => {+ it('routes share pages through the Share SPA for every user agent', async () => {+ const mobileTopic = await run(+ 'http://localhost:3010/share/t/topic-1?hl=en-US',+ MOBILE_USER_AGENT,+ );+ 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');++ 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');+ });++ it('leaves non-share paths that merely start with the prefix in the main SPA', async () => {+ const rewrite = await run('http://localhost:3010/shared-workspace/settings?hl=en-US');++ expect(new URL(rewrite!).pathname).toMatch(/^\/spa\/[^/]+\/shared-workspace\/settings$/);+ });+});diff --git a/src/libs/next/proxy/define-config.ts b/src/libs/next/proxy/define-config.tsindex 78a4f275ed2..972ec9a4394 100644--- a/src/libs/next/proxy/define-config.ts+++ b/src/libs/next/proxy/define-config.ts@@ -13,6 +13,7 @@ import { parseBrowserLanguage } from '@/utils/locale';import { DEFAULT_LANG, locales, RouteVariants } from '@/utils/server/routeVariants';import { authSpaRoutes, nextjsOnlyRoutes } from '../nextjsOnlyRoutes';+import { isShareSpaRoute } from '../shareRoutes';import { isAlwaysWorkbenchSpaRoute, isWorkbenchSpaRoute } from '../workbenchRoutes';import { createRouteMatcher } from './createRouteMatcher';@@ -90,18 +91,11 @@ export function defineConfig() {locale,});- // These pages are responsive on their own; always serve the desktop bundle- // so mobile UA does not land on mobile-specific routes.- const desktopOnlyPaths = ['/share'];- const isDesktopOnlyPath = desktopOnlyPaths.some(- (path) => url.pathname === path || url.pathname.startsWith(`${path}/`),- );-const safeLocale = toSafeLocale(locale);// 2. Create normalized preference valuesconst route = RouteVariants.serializeVariants({- isMobile: !isDesktopOnlyPath && device.type === 'mobile',+ isMobile: device.type === 'mobile',locale: safeLocale,});@@ -146,6 +140,19 @@ export function defineConfig() {return response;}+ // Share pages are responsive on their own, so they get one bundle for every+ // device rather than a mobile variant.+ if (isShareSpaRoute(url.pathname)) {+ const sharePath = `/spa-share/${safeLocale}${url.pathname}`;+ logDefault('Share SPA route, rewriting to: %s', sharePath);+ url.pathname = sharePath;++ const response = NextResponse.rewrite(url);+ persistLocaleCookie(response, request, explicitlyLocale);++ return response;+ }+if (isAlwaysWorkbenchSpaRoute(url.pathname) ||(device.type === 'mobile' && isWorkbenchSpaRoute(url.pathname))diff --git a/src/libs/next/shareRoutes.test.ts b/src/libs/next/shareRoutes.test.tsnew file mode 100644index 00000000000..6ef86ffe0e6--- /dev/null+++ b/src/libs/next/shareRoutes.test.ts@@ -0,0 +1,24 @@+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',+ '/share/',+ '/share/t',+ '/share/t/abc/extra',+ '/shared/t/abc',+ '/chat',+ '/verify/run-1',+ ])('does not match %s', (pathname) => {+ expect(isShareSpaRoute(pathname)).toBe(false);+ });+});diff --git a/src/libs/next/shareRoutes.ts b/src/libs/next/shareRoutes.tsnew file mode 100644index 00000000000..574f68c7b4a--- /dev/null+++ b/src/libs/next/shareRoutes.ts@@ -0,0 +1,11 @@+const SHARE_TOPIC_ROUTE = /^\/share\/t\/[^/]+\/?$/;+const SHARE_PAGE_ROUTE = /^\/share\/page\/[^/]+\/?$/;++const pathOnly = (pathname: string) => pathname.split(/[?#]/, 1)[0]!;++/** Every path the standalone Share app owns. */+export const isShareSpaRoute = (pathname: string): boolean => {+ const path = pathOnly(pathname);++ return SHARE_TOPIC_ROUTE.test(path) || SHARE_PAGE_ROUTE.test(path);+};diff --git a/src/routes/share/page/[id]/routeMeta.ts b/src/routes/share/page/[id]/routeMeta.tsdeleted file mode 100644index c79b80f0f09..00000000000--- a/src/routes/share/page/[id]/routeMeta.ts+++ /dev/null@@ -1,33 +0,0 @@-import { FileTextIcon } from 'lucide-react';-import useSWR from 'swr';--import { usePublishDynamicRouteMeta } from '@/features/RouteMeta/usePublishDynamicRouteMeta';-import { shareKeys } from '@/libs/swr/keys';-import { lambdaClient } from '@/libs/trpc/client';-import type { DynamicRouteMetaProps } from '@/spa/router/routeMeta';-import { routeMeta } from '@/spa/router/routeMeta';-import { getIdFromIdentifier } from '@/utils/identifier';--const SharePageDynamicMeta = ({ onResolve, params }: DynamicRouteMetaProps) => {- const documentId = getIdFromIdentifier(params.id ?? '', 'docs');- const { data } = useSWR(- documentId ? shareKeys.pageDocument(documentId) : null,- () => lambdaClient.pageShare.getSharedDocument.query({ documentId }),- { revalidateOnFocus: false },- );-- usePublishDynamicRouteMeta(- {- title: data?.document.title || undefined,- },- onResolve,- );-- return null;-};--export const sharePageRouteMeta = routeMeta({- DynamicMeta: SharePageDynamicMeta,- icon: FileTextIcon,- titleKey: 'navigation.pages',-});diff --git a/src/routes/share/t/[id]/_layout/index.tsx b/src/routes/share/t/[id]/_layout/index.tsxdeleted file mode 100644index d4c47cc9cfa..00000000000--- a/src/routes/share/t/[id]/_layout/index.tsx+++ /dev/null@@ -1,48 +0,0 @@-'use client';--import { type PropsWithChildren } from 'react';-import { memo, Suspense } from 'react';-import { Outlet, useParams } from 'react-router';-import useSWR from 'swr';--import ShareShell from '@/business/client/features/ShareShell';-import Loading from '@/components/Loading/BrandTextLoading';-import { RouteMetaBridge } from '@/features/RouteMeta';-import { shareKeys } from '@/libs/swr/keys';-import { lambdaClient } from '@/libs/trpc/client';--import SharePortal from '../features/Portal';-import TopicAvatar from '../features/TopicAvatar';-import { useSyncSharedTopicMeta } from '../useSyncSharedTopicMeta';--const ShareTopicLayout = memo<PropsWithChildren>(({ children }) => {- const { id } = useParams<{ id: string }>();-- const { data, error, isLoading } = useSWR(- id ? shareKeys.topic(id) : null,- () => lambdaClient.share.getSharedTopic.query({ shareId: id! }),- { revalidateOnFocus: false },- );-- useSyncSharedTopicMeta(data);-- const marketIdentifier = data?.agentMeta?.marketIdentifier;- const openUrl = marketIdentifier ? `/community/agent/${marketIdentifier}` : '/community/agent';-- return (- <>- <RouteMetaBridge />- <ShareShell- aside={<SharePortal />}- error={error}- loading={!error && isLoading}- share={{ avatar: data ? <TopicAvatar data={data} /> : undefined, openUrl }}- title={data?.title}- >- <Suspense fallback={<Loading debugId="share layout" />}>{children ?? <Outlet />}</Suspense>- </ShareShell>- </>- );-});--export default ShareTopicLayout;diff --git a/src/routes/share/t/[id]/routeMeta.ts b/src/routes/share/t/[id]/routeMeta.tsdeleted file mode 100644index b46cadfc38c..00000000000--- a/src/routes/share/t/[id]/routeMeta.ts+++ /dev/null@@ -1,32 +0,0 @@-import { MessageSquare } from 'lucide-react';-import useSWR from 'swr';--import { usePublishDynamicRouteMeta } from '@/features/RouteMeta/usePublishDynamicRouteMeta';-import { shareKeys } from '@/libs/swr/keys';-import { lambdaClient } from '@/libs/trpc/client';-import type { DynamicRouteMetaProps } from '@/spa/router/routeMeta';-import { routeMeta } from '@/spa/router/routeMeta';--const ShareTopicDynamicMeta = ({ onResolve, params }: DynamicRouteMetaProps) => {- const shareId = params.id;- const { data } = useSWR(- shareId ? shareKeys.topic(shareId) : null,- () => lambdaClient.share.getSharedTopic.query({ shareId: shareId! }),- { revalidateOnFocus: false },- );-- usePublishDynamicRouteMeta(- {- title: data?.title || undefined,- },- onResolve,- );-- return null;-};--export const shareTopicRouteMeta = routeMeta({- DynamicMeta: ShareTopicDynamicMeta,- icon: MessageSquare,- titleKey: 'navigation.chat',-});diff --git a/src/spa/BootShell/routeScope.test.ts b/src/spa/BootShell/routeScope.test.tsindex 60ab6401a76..dc5c054ee0d 100644--- a/src/spa/BootShell/routeScope.test.ts+++ b/src/spa/BootShell/routeScope.test.ts@@ -23,7 +23,7 @@ describe('isMainLayoutLocation', () => {// The shell would otherwise promise chrome these pages never render β the// exact "logo β app-shell skeleton β logo β page" sequence this guards.it.each([- ['Web', webDesktopRoutes, ['/onboarding', '/share/t/topic-1', '/verify-im']],+ ['Web', webDesktopRoutes, ['/onboarding', '/verify-im']],['Electron', electronDesktopRoutes, ['/desktop-onboarding']],])('%s excludes standalone routes outside the main layout', (_, routes, paths) => {for (const pathname of paths as string[]) {diff --git a/src/spa/BootShell/routeScope.ts b/src/spa/BootShell/routeScope.tsindex b5547f8a086..c80f6978e81 100644--- a/src/spa/BootShell/routeScope.ts+++ b/src/spa/BootShell/routeScope.ts@@ -7,9 +7,9 @@ const MAIN_LAYOUT_PATH = '/';** The shell draws the main-app chrome β nav panel column plus the rounded* container β so it is only an honest placeholder for routes that actually- * render that chrome. `/onboarding` and `/share/t/:id` are siblings- * of the main-layout root, not children: showing them a nav panel that never- * arrives is worse than showing the brand logo they already fall back to.+ * render that chrome. `/onboarding` and `/verify-im` are siblings of the+ * main-layout root, not children: showing them a nav panel that never arrives+ * is worse than showing the brand logo they already fall back to.** Note this is not a "known route" test: the main area carries a* `:workspaceSlug` segment, so an unrecognised path is read as a workspace anddiff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsxindex e19b7b226e0..f666f74f6f5 100644--- a/src/spa/router/desktopRouter.config.tsx+++ b/src/spa/router/desktopRouter.config.tsx@@ -3,9 +3,6 @@import type { RouteObject } from 'react-router';import { acceptanceRouteMeta } from '@/features/Verify/routeMeta';-import { sharePageRouteMeta } from '@/routes/share/page/[id]/routeMeta';-import { shareTopicRouteMeta } from '@/routes/share/t/[id]/routeMeta';-import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';import { dynamicElement, ErrorBoundary } from '@/utils/router';import { createMainAreaRouteFactory, createSharedDesktopRoutes } from './desktopRouter.shared';@@ -20,38 +17,8 @@ export const mainAreaMetaRoutes: RouteObject[] = [{ children: createMainAreaChildren(), path: '/' },];+// `/share/*` is served by the standalone Share app (apps/share), not this router.const webOnlyRoutes: RouteObject[] = [- // Share topic route (outside main layout)- {- children: [- {- element: dynamicElement(- () => loadRouteWithBuiltinToolSurfaces(() => import('@/routes/share/t/[id]')),- 'Desktop > Share > Topic',- ),- handle: { meta: shareTopicRouteMeta },- path: ':id',- },- ],- element: dynamicElement(- () => import('@/routes/share/t/[id]/_layout'),- 'Desktop > Share > Topic > Layout',- ),- path: '/share/t',- },-- // Share page route (outside main layout)- {- children: [- {- element: dynamicElement(() => import('@/routes/share/page/[id]'), 'Desktop > Share > Page'),- handle: { meta: sharePageRouteMeta },- path: ':id',- },- ],- path: '/share/page',- },-{element: dynamicElement(() => import('@/routes/verify-im'), 'Desktop > VerifyIm'),errorElement: <ErrorBoundary />,diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsxindex 6a482adc0ed..03ff3f00c41 100644--- a/src/spa/router/desktopRouter.sync.test.tsx+++ b/src/spa/router/desktopRouter.sync.test.tsx@@ -274,8 +274,9 @@ describe('desktop router shared definition', () => {{ element: null, path: '*' },]);expect(webPaths).toContain('/verify-im');- expect(webPaths).toContain('/share/t');- expect(webPaths).toContain('/share/page');+ // `/share/*` moved to the standalone Share app (apps/share).+ expect(webPaths).not.toContain('/share/t');+ expect(webPaths).not.toContain('/share/page');expect(webPaths).not.toContain('/verify');expect(webPaths).toContain('/acceptance');expect(webPaths).toContain('/onboarding');diff --git a/src/spa/router/mobileRouter.config.tsx b/src/spa/router/mobileRouter.config.tsxindex 71ac16e8e6d..7b42375d1d6 100644--- a/src/spa/router/mobileRouter.config.tsx+++ b/src/spa/router/mobileRouter.config.tsx@@ -10,8 +10,6 @@ import AppsSkeleton from '@/components/Skeleton/Apps';import { mobileAgentSettingsRouteMeta } from '@/features/RouteMeta/mobileRouteMeta';import { acceptanceRouteMeta } from '@/features/Verify/routeMeta';import { agentRouteMeta } from '@/routes/(main)/agent/features/routeMeta';-import { sharePageRouteMeta } from '@/routes/share/page/[id]/routeMeta';-import { shareTopicRouteMeta } from '@/routes/share/t/[id]/routeMeta';import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';import { dynamicElement, dynamicLayout, ErrorBoundary, redirectElement } from '@/utils/router';@@ -588,36 +586,7 @@ export const mobileRoutes: RouteObject[] = [},...BusinessMobileRoutesWithoutMainLayout,- // Share topic route (outside main layout)- {- children: [- {- element: dynamicElement(- () => loadRouteWithBuiltinToolSurfaces(() => import('@/routes/share/t/[id]')),- 'Mobile > Share > Topic',- ),- handle: { meta: shareTopicRouteMeta },- path: ':id',- },- ],- element: dynamicElement(- () => import('@/routes/share/t/[id]/_layout'),- 'Mobile > Share > Topic > Layout',- ),- path: '/share/t',- },-- // Share page route (outside main layout)- {- children: [- {- element: dynamicElement(() => import('@/routes/share/page/[id]'), 'Mobile > Share > Page'),- handle: { meta: sharePageRouteMeta },- path: ':id',- },- ],- path: '/share/page',- },+ // `/share/*` is served by the standalone Share app (apps/share), not this router.// Messenger verify route (outside main layout){diff --git a/tsconfig.json b/tsconfig.jsonindex 7b7af939479..5b317ac6a10 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -40,6 +40,7 @@"node_modules","apps/desktop/**","apps/mobile/**",+ "apps/share/**","apps/workbench/**","scripts/**","tmp",