🤯 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(workbench): React Router framework mode SSR on Cloudflare Workers (#18473)
Innei1001a58a22e0
diff --git a/.agents/skills/split-micro-app/SKILL.md b/.agents/skills/split-micro-app/SKILL.mdnew file mode 100644index 00000000000..de6f9862fd7--- /dev/null+++ b/.agents/skills/split-micro-app/SKILL.md@@ -0,0 +1,152 @@+---+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.'+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.++## Hosting++One 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` |++`generateSpaTemplates` skips a missing `dist/<name>` HTML unless `WORKBENCH_REQUIRED=1`. Cloud must skip. Docker must require.++Do not revive Cloud `SPA_TARGET=workbench` Vite builds or a `/spa-workbench` middleware rewrite.++## Crossing from the main SPA++Only 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).++## 1. Splitting & Artifacts++App layout (`apps/<name>/`):++```+app/ # RR framework mode: root.tsx, routes.ts, entry.server.tsx, routes/, lib/, stubs/+workers/app.ts # worker entry: API reverse proxy + createRequestHandler+src/ # app-owned features/shell (may coexist with a legacy SPA entry)+vite.config.rr.mts # RR pipeline; legacy vite.config.ts can coexist (RR CLI: -c vite.config.rr.mts)+wrangler.jsonc # name, account_id, nodejs_compat, vars (API base / app home)+staticCssOptions.mjs # ONE source for static-css hrefTemplate (vite plugin + emit + dev middleware)+```++Reuse main-src code via `@/*` deep imports + Vite 8 native `resolve.tsconfigPaths: true`+(the vite-tsconfig-paths **plugin** breaks dev SSR module-runner resolution; the app's+tsconfig `include` must cover `app/`). Stack: `@react-router/dev@8` + `@cloudflare/vite-plugin`++- repo Vite 8 (rolldown) — officially compatible.++**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 |+| 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 |+| Decouple dual-use components | Lift store reads to optional props (see AudioPlayer `uploadState`/`onCancelUpload`) |++Products: `build/client` (assets → CDN), `build/server` (worker; deploy with+`wrangler deploy --config build/server/wrangler.json`). Budget: worker gzip ≤ 10MB paid.++**CI affected-detection**: build emits `build-inputs.txt` (module-graph file list, gitignored);+the deploy workflow diffs changed files against the manifest from the **last successful run's+artifact** (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`.++## 2. Deploy: CDN Assets + Worker++Assets 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`) =+build with CDN base → upload `build/client/assets` to R2 (`web-assets` bucket, LobeHub+account) → `wrangler deploy`. R2 creds: 1Password Shared vault item "CI R2 - web-assets", inject via+`op read`, never echo values.++Worker responsibilities beyond SSR: reverse-proxy `/api|/oidc|/trpc|/webapi` to+`WORKBENCH_API_BASE` (standalone mode; behind the gateway the browser hits the apex and the+gateway routes API to `app` instead), and redirect `/` + unknown paths to `WORKBENCH_APP_HOME`.++## 3. SSR++- **Loader-side data**: per-request tRPC client (`httpLink` + superjson + forwarded `cookie`+ header, base from wrangler vars via `cloudflareContext`) — the browser lambdaClient is+ SSR-stubbed. Inject into SWR with `<SWRConfig value={{ fallback: { [unstable_serialize(key)]: data } }}>`;+ key must equal `useClientDataSWR`'s (augmentKey passes through when workspaceId is null).+- **`isLoading && !data`**: with SWRConfig fallback, `isLoading` is true during mount+ revalidation — a bare `if (isLoading)` swaps SSR content for a spinner after hydration.+- **i18n**: narrow to the namespaces the app renders; root loader preloads locale resources,+ i18n inits sync (`initAsync: false`) with bundled resources; SSR env stubs the shared glob+ loader to only its namespaces (full glob = every locale × ns as worker chunks).+- **CSS three layers**: lobe-ui `static-css` (antd probes + theme vars, hrefTemplate from the+ shared options file; emitted as hashed files, dev served by config middleware) →+ antd-style `extractStaticStyle(html, { includeAntd: false })` for emotion →+ `buildInlineAntdStyle(cache, { styleKeys })` fallback. Non-streaming render+ (`await stream.allReady`) so extraction is complete.+- `<html suppressHydrationWarning>` — next-themes stamps `data-theme` pre-hydration.++RR v8 gotchas (docs/templates still say v7):++| v8 change | Symptom |+| -------------------------------------------------- | ------------------------------------------------------- |+| load context must be `new RouterContextProvider()` | template's plain object → 500 |+| `MetaArgs.data` renamed `loaderData` | `{ data }` destructure silently undefined; build passes |+| `*` splat does not match bare `/` | no index route → root falls into ErrorBoundary |+| `vite preview` ignores `server.proxy` | loader self-fetch gets HTML → keep API base explicit |++## 4. SEO++One shared builder (`app/lib/seo.ts` → `buildPageMeta`): title, description, robots,+og:title/description/type/site\_name/locale (underscore form)/image(+alt), twitter card set.+Rules: leaf `meta` **fully replaces** root meta — every leaf returns the whole set;+`og:image` must be an **absolute URL** (reuse landing's `https://lobehub.com/assets/cao-og.webp`);+dynamic title/description come from the route loader (subject title · BRANDING\_NAME,+requirement text truncated \~200 chars).++## 5. Gateway Routing (torii, `../lobehub-gateway`)++Config = KV `config:lobehub.com`, mirrored in `config/entrypoints/lobehub.com/<env>.json`.+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.+3. `rules` — first-match path prefixes (`{ "match": "/acceptance", "target": "<name>" }`).+ Leave `/trpc` unruled: it falls to `default` (app) so browser API calls stay same-origin+ authenticated. `.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.+6. Verify with staging debug headers: `x-torii-target` / `x-torii-decision` per request, and+ test document + `.data` + unaffected routes.++Landmine (fixed 2026-08, stay aware): the lobehub-com `react-router-data` plugin owns `.data`+protocol affinity for the landing pair; it consults `resolveRule` and lets other targets'+`.data` fall through — if a future entrypoint clones that plugin, keep the fall-through.++## 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.diff --git a/.github/workflows/deploy-workbench.yml b/.github/workflows/deploy-workbench.ymlnew file mode 100644index 00000000000..40333494b34--- /dev/null+++ b/.github/workflows/deploy-workbench.yml@@ -0,0 +1,100 @@+name: Deploy Workbench++on:+ push:+ branches: [canary]+ workflow_dispatch: {}++permissions:+ actions: read+ contents: read++concurrency:+ group: deploy-workbench+ cancel-in-progress: false++jobs:+ deploy:+ runs-on: ubuntu-latest+ steps:+ - name: Checkout+ uses: actions/checkout@v4+ with:+ fetch-depth: 0++ - name: Resolve last successful deploy+ id: base+ if: github.event_name == 'push'+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ read -r sha run_id < <(gh run list --repo "${{ github.repository }}" \+ --workflow deploy-workbench.yml --branch "${{ github.ref_name }}" \+ --status success --limit 1 --json headSha,databaseId \+ --jq '.[0] | "\(.headSha) \(.databaseId)"' || true)+ echo "sha=$sha" >> "$GITHUB_OUTPUT"+ echo "run_id=$run_id" >> "$GITHUB_OUTPUT"++ - name: Download last deployed build-inputs manifest+ id: manifest+ if: github.event_name == 'push' && steps.base.outputs.run_id != ''+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ if gh run download "${{ steps.base.outputs.run_id }}" --repo "${{ github.repository }}" \+ -n workbench-build-inputs -D /tmp/workbench-manifest; then+ echo "path=/tmp/workbench-manifest/build-inputs.txt" >> "$GITHUB_OUTPUT"+ else+ echo "no manifest artifact on last successful run"+ fi++ - name: Detect workbench input changes+ id: detect+ env:+ WORKBENCH_MANIFEST: ${{ steps.manifest.outputs.path }}+ run: |+ if [ "${{ github.event_name }}" != "push" ]; then+ echo "manual dispatch — building"+ echo "should_build=true" >> "$GITHUB_OUTPUT"+ elif [ -z "$WORKBENCH_MANIFEST" ]; then+ echo "no previous deploy manifest — building"+ echo "should_build=true" >> "$GITHUB_OUTPUT"+ else+ node apps/workbench/scripts/should-build.mjs "${{ steps.base.outputs.sha }}" "${{ github.sha }}"+ fi++ - name: Setup environment+ if: steps.detect.outputs.should_build == 'true'+ uses: ./.github/actions/setup-env++ - name: Install deps+ if: steps.detect.outputs.should_build == 'true'+ run: pnpm install++ - name: Build workbench+ if: steps.detect.outputs.should_build == 'true'+ run: bun run build:rr+ working-directory: apps/workbench++ - name: Deploy to Cloudflare+ if: steps.detect.outputs.should_build == 'true'+ env:+ CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}+ run: node_modules/.bin/wrangler deploy --config build/server/wrangler.json+ working-directory: apps/workbench++ - name: Upload build-inputs manifest+ if: steps.detect.outputs.should_build == 'true'+ uses: actions/upload-artifact@v4+ with:+ name: workbench-build-inputs+ path: apps/workbench/build-inputs.txt+ retention-days: 90++ - name: Carry forward previous manifest+ if: steps.detect.outputs.should_build != 'true' && steps.manifest.outputs.path != ''+ uses: actions/upload-artifact@v4+ with:+ name: workbench-build-inputs+ path: ${{ steps.manifest.outputs.path }}+ retention-days: 90diff --git a/.github/workflows/verify-workbench.yml b/.github/workflows/verify-workbench.ymlnew file mode 100644index 00000000000..e73c3facd26--- /dev/null+++ b/.github/workflows/verify-workbench.yml@@ -0,0 +1,83 @@+name: Verify Workbench++on:+ pull_request: {}++permissions:+ actions: read+ contents: read++concurrency:+ group: verify-workbench-${{ github.event.pull_request.number }}+ cancel-in-progress: true++jobs:+ verify:+ runs-on: ubuntu-latest+ steps:+ - name: Checkout+ uses: actions/checkout@v4+ with:+ fetch-depth: 0++ - name: Resolve last successful deploy+ id: base+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ run_id=$(gh run list --repo "${{ github.repository }}" \+ --workflow deploy-workbench.yml --status success --limit 1 \+ --json databaseId --jq '.[0].databaseId' || true)+ echo "run_id=$run_id" >> "$GITHUB_OUTPUT"++ - name: Download last deployed build-inputs manifest+ id: manifest+ if: steps.base.outputs.run_id != ''+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ if gh run download "${{ steps.base.outputs.run_id }}" --repo "${{ github.repository }}" \+ -n workbench-build-inputs -D /tmp/workbench-manifest; then+ echo "path=/tmp/workbench-manifest/build-inputs.txt" >> "$GITHUB_OUTPUT"+ else+ echo "no manifest artifact on last successful run"+ fi++ - name: Detect workbench input changes+ id: detect+ env:+ WORKBENCH_MANIFEST: ${{ steps.manifest.outputs.path }}+ run: |+ if [ -z "$WORKBENCH_MANIFEST" ]; then+ echo "no previous deploy manifest — building"+ echo "should_build=true" >> "$GITHUB_OUTPUT"+ else+ node apps/workbench/scripts/should-build.mjs \+ "origin/${{ github.base_ref }}" HEAD+ fi++ - name: Setup environment+ if: steps.detect.outputs.should_build == 'true'+ uses: ./.github/actions/setup-env++ - name: Install deps+ if: steps.detect.outputs.should_build == 'true'+ run: pnpm install++ - name: Build workbench+ if: steps.detect.outputs.should_build == 'true'+ run: bun run build:rr+ working-directory: apps/workbench++ - name: Validate worker bundle+ if: steps.detect.outputs.should_build == 'true'+ run: |+ node_modules/.bin/wrangler deploy --dry-run \+ --config build/server/wrangler.json | tee /tmp/dry-run.log+ gzip_kib=$(grep -Eo 'gzip: [0-9.]+ KiB' /tmp/dry-run.log | grep -Eo '[0-9.]+' | head -1)+ echo "worker gzip size: ${gzip_kib} KiB"+ if [ -n "$gzip_kib" ] && [ "$(printf '%.0f' "$gzip_kib")" -gt 8192 ]; then+ echo "::error::worker bundle ${gzip_kib} KiB gzip exceeds the 8 MiB guard (plan limit is 10 MiB)"+ exit 1+ fi+ working-directory: apps/workbenchdiff --git a/.stylelintignore b/.stylelintignoreindex e1ac30fba16..1d7073e63e2 100644--- a/.stylelintignore+++ b/.stylelintignore@@ -12,6 +12,7 @@ coveragedisteslib+!apps/workbench/app/liblogs# framework specificdiff --git a/Dockerfile b/Dockerfileindex 00813e32754..9bcd2b96b6a 100644--- a/Dockerfile+++ b/Dockerfile@@ -65,8 +65,9 @@ COPY package.json pnpm-workspace.yaml ./COPY .npmrc ./COPY packages ./packagesCOPY patches ./patches-# bring in desktop workspace manifest so pnpm can resolve it+# 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/workbench/package.json ./apps/workbench/package.jsonRUN set -e && \if [ "${USE_CN_MIRROR:-false}" = "true" ]; then \diff --git a/apps/workbench/.gitignore b/apps/workbench/.gitignorenew file mode 100644index 00000000000..5e2212a791d--- /dev/null+++ b/apps/workbench/.gitignore@@ -0,0 +1,5 @@+.react-router/+!app/lib/+.wrangler/+build/+build-inputs.txtdiff --git a/apps/workbench/app/components/agentDocReader.client.tsx b/apps/workbench/app/components/agentDocReader.client.tsxnew file mode 100644index 00000000000..e8106d98490--- /dev/null+++ b/apps/workbench/app/components/agentDocReader.client.tsx@@ -0,0 +1,12 @@+import { useParams } from 'react-router';++import AgentDocumentReader from '@/features/AgentDocumentReader';+import { getIdFromIdentifier } from '@/utils/identifier';++export default function AgentDocReader() {+ const { aid = '', docId = '' } = useParams<{ aid: string; docId: string }>();+ const agentId = getIdFromIdentifier(aid, 'agt');+ const documentId = getIdFromIdentifier(docId, 'docs');++ return <AgentDocumentReader agentId={agentId} documentId={documentId} />;+}diff --git a/apps/workbench/app/components/clientOnlyRoute.tsx b/apps/workbench/app/components/clientOnlyRoute.tsxnew file mode 100644index 00000000000..e4085d32659--- /dev/null+++ b/apps/workbench/app/components/clientOnlyRoute.tsx@@ -0,0 +1,28 @@+import { type ComponentType, lazy, Suspense, useSyncExternalStore } from 'react';++import WorkbenchLoading from '../../src/shell/WorkbenchLoading';++const noopSubscribe = () => () => {};++const useHydrated = () =>+ useSyncExternalStore(+ noopSubscribe,+ () => true,+ () => false,+ );++export const clientOnlyRoute = (importFn: () => Promise<{ default: ComponentType }>) => {+ const Component = lazy(importFn);++ return function ClientOnlyRoute() {+ const hydrated = useHydrated();++ if (!hydrated) return <WorkbenchLoading />;++ return (+ <Suspense fallback={<WorkbenchLoading />}>+ <Component />+ </Suspense>+ );+ };+};diff --git a/apps/workbench/app/components/verifyDetail.client.tsx b/apps/workbench/app/components/verifyDetail.client.tsxnew file mode 100644index 00000000000..67e9a417a7b--- /dev/null+++ b/apps/workbench/app/components/verifyDetail.client.tsx@@ -0,0 +1 @@+export { default } from '../../src/features/verify/VerifyDetail';diff --git a/apps/workbench/app/entry.client.tsx b/apps/workbench/app/entry.client.tsxnew file mode 100644index 00000000000..71b73f5686c--- /dev/null+++ b/apps/workbench/app/entry.client.tsx@@ -0,0 +1,27 @@+import { startTransition, StrictMode } from 'react';+import { hydrateRoot } from 'react-dom/client';+import { HydratedRouter } from 'react-router/dom';++// 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('[workbench] ignored css preload failure:', payload);+ event.preventDefault();+ }+});++startTransition(() => {+ hydrateRoot(+ document,+ <StrictMode>+ <HydratedRouter />+ </StrictMode>,+ );+});diff --git a/apps/workbench/app/entry.server.tsx b/apps/workbench/app/entry.server.tsxnew file mode 100644index 00000000000..e739a4bdc96--- /dev/null+++ b/apps/workbench/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-workbench-antd-uncovered', String(inlineAntd.uncovered.length));++ return new Response(html.replace('</head>', `${inlineAntd.html}${emotionTags}</head>`), {+ headers: responseHeaders,+ status,+ });+}diff --git a/apps/workbench/app/layouts/acceptanceNamespace.tsx b/apps/workbench/app/layouts/acceptanceNamespace.tsxnew file mode 100644index 00000000000..5b9b0733f6e--- /dev/null+++ b/apps/workbench/app/layouts/acceptanceNamespace.tsx@@ -0,0 +1,11 @@+import { Outlet } from 'react-router';++import { WorkbenchNamespace } from '../../src/shell';++export default function AcceptanceNamespace() {+ return (+ <WorkbenchNamespace namespace="verify">+ <Outlet />+ </WorkbenchNamespace>+ );+}diff --git a/apps/workbench/app/layouts/verifyNamespace.tsx b/apps/workbench/app/layouts/verifyNamespace.tsxnew file mode 100644index 00000000000..794c5383b2f--- /dev/null+++ b/apps/workbench/app/layouts/verifyNamespace.tsx@@ -0,0 +1,11 @@+import { Outlet } from 'react-router';++import { WorkbenchNamespace } from '../../src/shell';++export default function VerifyNamespace() {+ return (+ <WorkbenchNamespace namespace="verify">+ <Outlet />+ </WorkbenchNamespace>+ );+}diff --git a/apps/workbench/app/lib/cloudflareContext.ts b/apps/workbench/app/lib/cloudflareContext.tsnew file mode 100644index 00000000000..2d6a6ee068f--- /dev/null+++ b/apps/workbench/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/workbench/app/lib/seo.ts b/apps/workbench/app/lib/seo.tsnew file mode 100644index 00000000000..cdc1aa109bd--- /dev/null+++ b/apps/workbench/app/lib/seo.ts@@ -0,0 +1,53 @@+import { BRANDING_NAME } from '@lobechat/business-const';+import type { MetaDescriptor } from 'react-router';++// Shared with landing-rr: workbench 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';++const FALLBACK_DESCRIPTION = 'Verification runs, delivery reports, and acceptance reviews.';++export const workbenchMetaDescription = (resources: unknown): string => {+ const verify = (resources as Record<string, Record<string, unknown>> | undefined)?.verify;+ const text = verify?.['meta.description'];+ return typeof text === 'string' ? text : FALLBACK_DESCRIPTION;+};++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' },+ { 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/workbench/app/lib/serverTrpc.ts b/apps/workbench/app/lib/serverTrpc.tsnew file mode 100644index 00000000000..9d8f874257f--- /dev/null+++ b/apps/workbench/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/workbench/app/root.tsx b/apps/workbench/app/root.tsxnew file mode 100644index 00000000000..90fa629762f--- /dev/null+++ b/apps/workbench/app/root.tsx@@ -0,0 +1,114 @@+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 { normalizeLocale } from '@/locales/resources';+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 resources = await loadWorkbenchResources(locale);++ return {+ dir: isRtlLang(locale) ? 'rtl' : 'ltr',+ locale,+ resources,+ };+};++export const meta: MetaFunction<typeof loader> = ({ loaderData }) =>+ buildPageMeta({+ description: workbenchMetaDescription(loaderData?.resources),+ 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" />+ <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>+ <WorkbenchShell locale={data?.locale} resources={data?.resources} serverConfig={null}>+ <Outlet />+ </WorkbenchShell>+ </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>+ <WorkbenchShell locale={data?.locale} resources={data?.resources} serverConfig={null}>+ <ErrorCapture error={error} />+ </WorkbenchShell>+ </NextThemeProvider>+ );+};diff --git a/apps/workbench/app/routes.ts b/apps/workbench/app/routes.tsnew file mode 100644index 00000000000..4e2ba62635c--- /dev/null+++ b/apps/workbench/app/routes.ts@@ -0,0 +1,16 @@+import { index, route, type RouteConfig } from '@react-router/dev/routes';++export default [+ index('routes/homeRedirect.tsx'),+ route('agent/:aid/docs/:docId', 'routes/agentDoc.tsx'),+ route('acceptance', 'layouts/acceptanceNamespace.tsx', [+ index('routes/acceptanceList.tsx'),+ route(':acceptanceId', 'routes/acceptanceDetail.tsx'),+ route(':acceptanceId/check/:checkId', 'routes/acceptanceDetailCheck.tsx'),+ ]),+ route('verify', 'layouts/verifyNamespace.tsx', [+ index('routes/verifyList.tsx'),+ route(':runId', 'routes/verifyDetail.tsx'),+ ]),+ route('*', 'routes/catchall.tsx'),+] satisfies RouteConfig;diff --git a/apps/workbench/app/routes/acceptanceDetail.tsx b/apps/workbench/app/routes/acceptanceDetail.tsxnew file mode 100644index 00000000000..ecb266dbc1b--- /dev/null+++ b/apps/workbench/app/routes/acceptanceDetail.tsx@@ -0,0 +1,55 @@+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 { verifyKeys } from '@/libs/swr/keys';++import AcceptanceDetail from '../../src/features/acceptance/AcceptanceDetail';+import { cloudflareContext } from '../lib/cloudflareContext';+import { buildPageMeta, truncateDescription, workbenchMetaDescription } from '../lib/seo';+import { createServerLambdaClient } from '../lib/serverTrpc';++export const loader = async ({ context, params, request }: LoaderFunctionArgs) => {+ const acceptanceId = params.acceptanceId!;+ const apiBase = context.get(cloudflareContext).env.WORKBENCH_API_BASE as string | undefined;++ // 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 bundle = await createServerLambdaClient(request, apiBase)+ .acceptance.getBundle.query({ id: acceptanceId })+ .catch((error) => {+ console.error('[workbench] acceptance bundle SSR fetch failed:', error);+ return null;+ });++ return { acceptanceId, bundle };+};++export const meta: MetaFunction<typeof loader> = ({ loaderData }) => {+ const subjectTitle = loaderData?.bundle?.subject?.title;++ return buildPageMeta({+ description:+ truncateDescription(loaderData?.bundle?.acceptance?.requirement) ??+ workbenchMetaDescription(undefined),+ title: subjectTitle ? `${subjectTitle} · ${BRANDING_NAME}` : BRANDING_NAME,+ type: 'article',+ });+};++export default function AcceptanceDetailRoute() {+ const { acceptanceId, bundle } = useLoaderData<typeof loader>();++ return (+ <SWRConfig+ value={{+ fallback: bundle+ ? { [unstable_serialize(verifyKeys.acceptanceBundle(acceptanceId))]: bundle }+ : {},+ }}+ >+ <AcceptanceDetail />+ </SWRConfig>+ );+}diff --git a/apps/workbench/app/routes/acceptanceDetailCheck.tsx b/apps/workbench/app/routes/acceptanceDetailCheck.tsxnew file mode 100644index 00000000000..b1521b9fefd--- /dev/null+++ b/apps/workbench/app/routes/acceptanceDetailCheck.tsx@@ -0,0 +1 @@+export { default, loader, meta } from './acceptanceDetail';diff --git a/apps/workbench/app/routes/acceptanceList.tsx b/apps/workbench/app/routes/acceptanceList.tsxnew file mode 100644index 00000000000..a9fb247ed74--- /dev/null+++ b/apps/workbench/app/routes/acceptanceList.tsx@@ -0,0 +1 @@+export { default } from '../../src/features/acceptance/AcceptanceList';diff --git a/apps/workbench/app/routes/agentDoc.tsx b/apps/workbench/app/routes/agentDoc.tsxnew file mode 100644index 00000000000..3921dd39f65--- /dev/null+++ b/apps/workbench/app/routes/agentDoc.tsx@@ -0,0 +1,3 @@+import { clientOnlyRoute } from '../components/clientOnlyRoute';++export default clientOnlyRoute(() => import('../components/agentDocReader.client'));diff --git a/apps/workbench/app/routes/catchall.tsx b/apps/workbench/app/routes/catchall.tsxnew file mode 100644index 00000000000..5c3b09d70d2--- /dev/null+++ b/apps/workbench/app/routes/catchall.tsx@@ -0,0 +1,15 @@+import type { LoaderFunctionArgs } from 'react-router';+import { redirect } from 'react-router';++import WorkbenchLoading from '../../src/shell/WorkbenchLoading';+import { cloudflareContext } from '../lib/cloudflareContext';++export const loader = ({ context }: LoaderFunctionArgs) => {+ const appHome = context.get(cloudflareContext).env.WORKBENCH_APP_HOME as string | undefined;++ return redirect(appHome || 'https://lobehub.com');+};++export default function ExitWorkbench() {+ return <WorkbenchLoading />;+}diff --git a/apps/workbench/app/routes/homeRedirect.tsx b/apps/workbench/app/routes/homeRedirect.tsxnew file mode 100644index 00000000000..e6e2a81bcb4--- /dev/null+++ b/apps/workbench/app/routes/homeRedirect.tsx@@ -0,0 +1 @@+export { default, loader } from './catchall';diff --git a/apps/workbench/app/routes/verifyDetail.tsx b/apps/workbench/app/routes/verifyDetail.tsxnew file mode 100644index 00000000000..98df1b473cd--- /dev/null+++ b/apps/workbench/app/routes/verifyDetail.tsx@@ -0,0 +1,3 @@+import { clientOnlyRoute } from '../components/clientOnlyRoute';++export default clientOnlyRoute(() => import('../components/verifyDetail.client'));diff --git a/apps/workbench/app/routes/verifyList.tsx b/apps/workbench/app/routes/verifyList.tsxnew file mode 100644index 00000000000..04b11b9ba90--- /dev/null+++ b/apps/workbench/app/routes/verifyList.tsx@@ -0,0 +1 @@+export { default } from '../../src/features/verify/VerifyList';diff --git a/apps/workbench/app/stubs/electronStore.ts b/apps/workbench/app/stubs/electronStore.tsnew file mode 100644index 00000000000..bdb29e0aa04--- /dev/null+++ b/apps/workbench/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/workbench/app/stubs/fileStore.ts b/apps/workbench/app/stubs/fileStore.tsnew file mode 100644index 00000000000..0e04ff0db36--- /dev/null+++ b/apps/workbench/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/workbench/app/stubs/globalService.ts b/apps/workbench/app/stubs/globalService.tsnew file mode 100644index 00000000000..52674a92a7d--- /dev/null+++ b/apps/workbench/app/stubs/globalService.ts@@ -0,0 +1,3 @@+import { reject } from './reject';++export const globalService = reject('globalService');diff --git a/apps/workbench/app/stubs/loadI18nNamespaceModule.client.ts b/apps/workbench/app/stubs/loadI18nNamespaceModule.client.tsnew file mode 100644index 00000000000..bab4dddefb7--- /dev/null+++ b/apps/workbench/app/stubs/loadI18nNamespaceModule.client.ts@@ -0,0 +1,52 @@+type NamespaceModule = { default: Record<string, unknown> };+type NamespaceLoaderMap = Record<string, () => Promise<NamespaceModule>>;++// The workbench client graph only requests these namespaces (verify UI plus the+// builtin-tool render stack in the gated detail view). The generic loader would+// register every locale x namespace pair (~1000 chunks). The i18n guard in+// vite.config.rr.mts scans the graph and fails the build when a namespace is+// missing here; keep both glob lists in sync when adding one.+const defaultLoaders = import.meta.glob([+ '../../../../packages/locales/src/default/chat.ts',+ '../../../../packages/locales/src/default/common.ts',+ '../../../../packages/locales/src/default/error.ts',+ '../../../../packages/locales/src/default/plugin.ts',+ '../../../../packages/locales/src/default/tool.ts',+ '../../../../packages/locales/src/default/verify.ts',+]) as NamespaceLoaderMap;+const localeLoaders = import.meta.glob([+ '../../../../locales/*/chat.json',+ '../../../../locales/*/common.json',+ '../../../../locales/*/error.json',+ '../../../../locales/*/plugin.json',+ '../../../../locales/*/tool.json',+ '../../../../locales/*/verify.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 workbench client: ${ns} (add it to app/stubs/loadI18nNamespaceModule.client.ts)`,+ );++ 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/workbench/app/stubs/loadI18nNamespaceModule.ts b/apps/workbench/app/stubs/loadI18nNamespaceModule.tsnew file mode 100644index 00000000000..f2048906705--- /dev/null+++ b/apps/workbench/app/stubs/loadI18nNamespaceModule.ts@@ -0,0 +1,37 @@+type NamespaceModule = { default: Record<string, unknown> };+type NamespaceLoaderMap = Record<string, () => Promise<NamespaceModule>>;++// SSR only ever renders the `verify` namespace (see workbenchNamespaces); the+// generic loader would register every locale x namespace pair as a worker+// chunk (~1000 files). The client build uses its own allowlist stub+// (loadI18nNamespaceModule.client.ts).+const defaultLoaders = import.meta.glob(+ '../../../../packages/locales/src/default/verify.ts',+) as NamespaceLoaderMap;+const localeLoaders = import.meta.glob('../../../../locales/*/verify.json') as NamespaceLoaderMap;++const DEFAULT_KEY = '../../../../packages/locales/src/default/verify.ts';++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;++ if (ns !== 'verify') throw new Error(`Namespace not bundled for SSR: ${ns}`);++ if (lng !== defaultLang) {+ const loadLocale = localeLoaders[`../../../../locales/${normalizeLocale(lng)}/verify.json`];+ if (loadLocale) return loadLocale();+ }++ return defaultLoaders[DEFAULT_KEY]!();+};++export const loadI18nNamespaceModuleWithFallback = loadI18nNamespaceModule;diff --git a/apps/workbench/app/stubs/reject.ts b/apps/workbench/app/stubs/reject.tsnew file mode 100644index 00000000000..e38be859a86--- /dev/null+++ b/apps/workbench/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/workbench/app/stubs/trpcClient.ts b/apps/workbench/app/stubs/trpcClient.tsnew file mode 100644index 00000000000..51d23435965--- /dev/null+++ b/apps/workbench/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/workbench/app/virtual-modules.d.ts b/apps/workbench/app/virtual-modules.d.tsnew file mode 100644index 00000000000..2c1397cc896--- /dev/null+++ b/apps/workbench/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/workbench/index.html b/apps/workbench/index.htmlnew file mode 100644index 00000000000..dd01f35f855--- /dev/null+++ b/apps/workbench/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/workbench/package.json b/apps/workbench/package.jsonnew file mode 100644index 00000000000..2eebb9fc5ec--- /dev/null+++ b/apps/workbench/package.json@@ -0,0 +1,23 @@+{+ "name": "@lobehub/workbench",+ "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 3014",+ "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",+ "wrangler": "^4.123.0"+ }+}diff --git a/apps/workbench/react-router.config.ts b/apps/workbench/react-router.config.tsnew file mode 100644index 00000000000..20ba3635fe3--- /dev/null+++ b/apps/workbench/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 (landing) 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/workbench/scripts/deploy.ts b/apps/workbench/scripts/deploy.tsnew file mode 100644index 00000000000..dee08ddd7f3--- /dev/null+++ b/apps/workbench/scripts/deploy.ts@@ -0,0 +1,72 @@+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 workbenchRoot = resolve(__dirname, '..');+const repoRoot = resolve(workbenchRoot, '../..');+const assetsDir = resolve(workbenchRoot, 'build/client/assets');++dotenv.config({ path: resolve(repoRoot, '.env') });++const env = (workbenchName: string, mobileName: string) =>+ process.env[workbenchName] || process.env[mobileName];++const requireEnv = (workbenchName: string, mobileName: string): string => {+ const value = env(workbenchName, mobileName);+ if (!value) throw new Error(`Missing env: ${workbenchName} (or fallback ${mobileName})`);+ return value;+};++async function main() {+ const publicDomain = new URL(requireEnv('WORKBENCH_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.+ const keyPrefix = (process.env.WORKBENCH_S3_KEY_PREFIX || 'workbench').replaceAll(+ /^\/+|\/+$/g,+ '',+ );+ const cdnBase = `${publicDomain}/${keyPrefix}/`;++ console.log(`=== Step 1: Build workbench (VITE_CDN_BASE=${cdnBase}) ===`);+ execSync('bun run build:rr', {+ cwd: workbenchRoot,+ 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('WORKBENCH_S3_ACCESS_KEY_ID', 'MOBILE_S3_ACCESS_KEY_ID'),+ bucket: requireEnv('WORKBENCH_S3_BUCKET', 'MOBILE_S3_BUCKET'),+ endpoint: requireEnv('WORKBENCH_S3_ENDPOINT', 'MOBILE_S3_ENDPOINT'),+ keyPrefix,+ publicDomain,+ region: env('WORKBENCH_S3_REGION', 'MOBILE_S3_REGION') || 'auto',+ secretAccessKey: requireEnv('WORKBENCH_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: workbenchRoot,+ stdio: 'inherit',+ });++ console.log('\n=== Deploy complete ===');+}++main().catch((error) => {+ console.error('Deploy failed:', error);+ process.exit(1);+});diff --git a/apps/workbench/scripts/emit-static-css.mjs b/apps/workbench/scripts/emit-static-css.mjsnew file mode 100644index 00000000000..7b6531beb86--- /dev/null+++ b/apps/workbench/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/workbench/scripts/should-build.mjs b/apps/workbench/scripts/should-build.mjsnew file mode 100644index 00000000000..e1e36677ec4--- /dev/null+++ b/apps/workbench/scripts/should-build.mjs@@ -0,0 +1,76 @@+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.WORKBENCH_MANIFEST || path.resolve(repoRoot, 'apps/workbench/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.+const META_TRIGGERS = [+ (file) => file.startsWith('apps/workbench/'),+ (file) => file.startsWith('plugins/vite/'),+ (file) => file.startsWith('packages/locales/src/default/'),+ (file) => /^locales\/[^/]+\/verify\.json$/.test(file),+ (file) => file === 'pnpm-lock.yaml',+ (file) => file === 'tsconfig.json',+ (file) => file === '.github/workflows/deploy-workbench.yml',+ (file) => file === '.github/workflows/verify-workbench.yml',+];++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} workbench build input(s) changed:`+ : `no workbench build inputs among ${changed.length} changed file(s)`,+ hits.slice(0, 20),+);diff --git a/src/spa/entry.workbench.tsx b/apps/workbench/src/entry.tsxsimilarity index 73%rename from src/spa/entry.workbench.tsxrename to apps/workbench/src/entry.tsxindex 800d287634a..8bee0adf204 100644--- a/src/spa/entry.workbench.tsx+++ b/apps/workbench/src/entry.tsx@@ -1,12 +1,12 @@-import '../initialize';+import '@/spa/initialize';import { RouterProvider } from 'react-router/dom';import BootErrorBoundary from '@/components/BootErrorBoundary';import NextThemeProvider from '@/layout/GlobalProvider/NextThemeProvider';+import { createSPABrowserRouter, createSPARoot } from '@/spa/runtime';-import { workbenchRoutes } from './router/workbenchRouter.config';-import { createSPABrowserRouter, createSPARoot } from './runtime';+import { workbenchRoutes } from './router';const router = createSPABrowserRouter(workbenchRoutes);diff --git a/apps/workbench/src/features/acceptance/AcceptanceDetail.tsx b/apps/workbench/src/features/acceptance/AcceptanceDetail.tsxnew file mode 100644index 00000000000..1b17fe1d9a4--- /dev/null+++ b/apps/workbench/src/features/acceptance/AcceptanceDetail.tsx@@ -0,0 +1,130 @@+'use client';++import { Flexbox } from '@lobehub/ui/es/Flex/index';+import Text from '@lobehub/ui/es/Text/index';+import { createStaticStyles, cssVar } from 'antd-style';+import { Component, lazy, memo, type PropsWithChildren, Suspense } from 'react';+import { useTranslation } from 'react-i18next';+import { useParams, useSearchParams } from 'react-router';+import useSWR from 'swr';++import AcceptanceViewer from '@/features/Verify/Acceptance';+import { useAcceptanceBundle } from '@/features/Verify/hooks';+import { extractUuid } from '@/features/Verify/utils';+import { useIsHydrated } from '@/hooks/useIsHydrated';+import { verifyKeys } from '@/libs/swr/keys';+import { verifyService } from '@/services/verify';++import WorkbenchBrandLink from '../../shell/WorkbenchBrandLink';+import SWRMutateInitializer from './SWRMutateInitializer';++// The sidebar pulls the global store (panel-width preference) and the list+// panel stack — lazy so the SSR graph and anonymous visitors never load it.+const workspaceSidebarMod = () => import('./WorkspaceSidebar');+const WorkspaceSidebar = lazy(workspaceSidebarMod);+const HeaderBrand = lazy(() => workspaceSidebarMod().then((mod) => ({ default: mod.HeaderBrand })));++// The list panel is auxiliary — a crash inside it must degrade to "no+// sidebar", never take the report page down with it.+class SidebarBoundary extends Component<PropsWithChildren, { failed: boolean }> {+ state = { failed: false };++ static getDerivedStateFromError() {+ return { failed: true };+ }++ componentDidCatch(error: unknown) {+ console.warn('[workbench] acceptance sidebar crashed:', error);+ }++ render() {+ return this.state.failed ? null : this.props.children;+ }+}++const styles = createStaticStyles(({ css }) => ({+ body: css`+ overflow: hidden;+ flex: 1;+ min-height: 0;+ `,+ header: css`+ flex: none;++ min-height: 48px;+ padding-inline: 12px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};++ background: ${cssVar.colorBgContainer};+ `,+ main: css`+ flex: 1;+ min-width: 0;+ height: 100%;+ background: ${cssVar.colorBgContainer};+ `,+ page: css`+ position: relative;+ width: 100%;+ height: 100dvh;+ background: ${cssVar.colorBgContainer};+ `,+}));++const WorkbenchAcceptanceDetail = memo(() => {+ const { t } = useTranslation('verify');+ const params = useParams<{ acceptanceId: string; checkId?: string }>();+ const acceptanceId = extractUuid(params.acceptanceId);+ const { data } = useAcceptanceBundle(acceptanceId ?? null);+ const hydrated = useIsHydrated();+ const [searchParams] = useSearchParams();+ const hasFocusedCheck = Boolean(params.checkId || searchParams.get('check'));++ // Signed-in detection without the user store (workbench never initializes+ // it): the owner list is cookie-authed, so a successful fetch IS the login+ // signal. Quiet + swallowed so an anonymous visitor's 401 stays silent.+ const { data: workspaceList } = useSWR(+ hydrated && !hasFocusedCheck ? verifyKeys.acceptances() : null,+ () =>+ verifyService.listAcceptances({ quiet: true }).catch((error) => {+ console.warn('[workbench] acceptance list probe failed:', error);+ return null;+ }),+ { revalidateIfStale: false, revalidateOnFocus: false, revalidateOnReconnect: false },+ );+ const showSidebar = Boolean(workspaceList) && !hasFocusedCheck;++ return (+ <Flexbox horizontal className={styles.page}>+ {showSidebar && (+ <SidebarBoundary>+ <Suspense fallback={null}>+ <WorkspaceSidebar />+ </Suspense>+ </SidebarBoundary>+ )}+ <Flexbox className={styles.main}>+ <SWRMutateInitializer />+ <Flexbox horizontal align={'center'} className={styles.header} gap={8}>+ {showSidebar ? (+ <Suspense fallback={<WorkbenchBrandLink />}>+ <HeaderBrand />+ </Suspense>+ ) : (+ <WorkbenchBrandLink />+ )}+ <Text ellipsis strong style={{ minWidth: 0 }}>+ {data?.subject.title ?? t('acceptance.titleFallback')}+ </Text>+ </Flexbox>+ <div className={styles.body}>+ <AcceptanceViewer />+ </div>+ </Flexbox>+ </Flexbox>+ );+});++WorkbenchAcceptanceDetail.displayName = 'WorkbenchAcceptanceDetail';++export default WorkbenchAcceptanceDetail;diff --git a/src/features/Verify/Acceptance/Workbench/AcceptanceList.tsx b/apps/workbench/src/features/acceptance/AcceptanceList.tsxsimilarity index 95%rename from src/features/Verify/Acceptance/Workbench/AcceptanceList.tsxrename to apps/workbench/src/features/acceptance/AcceptanceList.tsxindex 780a88ab82b..cad10a02e9c 100644--- a/src/features/Verify/Acceptance/Workbench/AcceptanceList.tsx+++ b/apps/workbench/src/features/acceptance/AcceptanceList.tsx@@ -8,21 +8,22 @@ import { Center, Flexbox } from '@lobehub/ui/es/Flex/index';import Icon from '@lobehub/ui/es/Icon/index';import Text from '@lobehub/ui/es/Text/index';import { createStaticStyles, cssVar } from 'antd-style';-import { ArrowLeft, Check, ListFilter, ScrollText, Search, TriangleAlert } from 'lucide-react';+import { Check, ListFilter, ScrollText, Search, TriangleAlert } from 'lucide-react';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';import useSWR from 'swr';-import { useLocalStorageState } from '@/hooks/useLocalStorageState';-import { verifyKeys } from '@/libs/swr/keys';-import { verifyService } from '@/services/verify';-import {type AcceptanceListFilter,DEFAULT_ACCEPTANCE_LIST_FILTER,filterAcceptanceList,normalizeAcceptanceListFilter,-} from '../Workspace/acceptanceListFilter';+} from '@/features/Verify/Acceptance/Workspace/acceptanceListFilter';+import { useLocalStorageState } from '@/hooks/useLocalStorageState';+import { verifyKeys } from '@/libs/swr/keys';+import { verifyService } from '@/services/verify';++import WorkbenchBrandLink from '../../shell/WorkbenchBrandLink';import AcceptanceRow from './AcceptanceRow';const ACCEPTANCE_LIST_FILTER_STORAGE_KEY = 'lobehub-acceptance-list-filter';@@ -113,7 +114,7 @@ const styles = createStaticStyles(({ css }) => ({}));const WorkbenchAcceptanceList = memo(() => {- const { t } = useTranslation(['verify', 'common']);+ const { t } = useTranslation('verify');const { data, error, isLoading, mutate } = useSWR(verifyKeys.acceptances(),() => verifyService.listAcceptances(),@@ -149,11 +150,7 @@ const WorkbenchAcceptanceList = memo(() => {<Flexbox className={styles.page}><Flexbox className={styles.header} gap={12}><Flexbox horizontal align={'center'} gap={8}>- <ActionIcon- icon={ArrowLeft}- title={t('back', { ns: 'common' })}- onClick={() => window.location.assign('/')}- />+ <WorkbenchBrandLink /><Text strong style={{ flex: 1, fontSize: 17 }}>{t('acceptance.workspace.title')}</Text>diff --git a/src/features/Verify/Acceptance/Workbench/AcceptanceRow.tsx b/apps/workbench/src/features/acceptance/AcceptanceRow.tsxsimilarity index 87%rename from src/features/Verify/Acceptance/Workbench/AcceptanceRow.tsxrename to apps/workbench/src/features/acceptance/AcceptanceRow.tsxindex 8fc86837d12..44a2968cc1b 100644--- a/src/features/Verify/Acceptance/Workbench/AcceptanceRow.tsx+++ b/apps/workbench/src/features/acceptance/AcceptanceRow.tsx@@ -28,12 +28,11 @@ import { useTranslation } from 'react-i18next';import { useNavigate } from 'react-router';import { mutate as globalMutate } from 'swr';+import { getAcceptanceStatusActions } from '@/features/Verify/Acceptance/statusActions';import { verifyKeys } from '@/libs/swr/keys';import type { AcceptanceListItem } from '@/services/verify';import { verifyService } from '@/services/verify';-import { getAcceptanceStatusActions } from '../statusActions';-const styles = createStaticStyles(({ css }) => ({content: css`overflow: hidden;@@ -166,7 +165,7 @@ interface AcceptanceRowProps {}const AcceptanceRow = memo<AcceptanceRowProps>(({ item, onChanged }) => {- const { t } = useTranslation(['verify', 'common']);+ const { t } = useTranslation('verify');const { message } = App.useApp();const navigate = useNavigate();const [editing, setEditing] = useState(false);@@ -185,7 +184,7 @@ const AcceptanceRow = memo<AcceptanceRowProps>(({ item, onChanged }) => {if (isSavingRef.current) return;const next = draftTitle.trim();if (!next) {- message.error(t('verify:acceptance.workspace.renameEmpty'));+ message.error(t('acceptance.workspace.renameEmpty'));setDraftTitle(title);setEditing(false);return;@@ -200,11 +199,11 @@ const AcceptanceRow = memo<AcceptanceRowProps>(({ item, onChanged }) => {try {await verifyService.renameAcceptance(item.id, next);await refresh();- message.success(t('verify:acceptance.workspace.renameSuccess'));+ message.success(t('acceptance.workspace.renameSuccess'));setEditing(false);} catch (error) {console.error('[acceptance:rename]', error);- message.error(t('verify:acceptance.workspace.renameError'));+ message.error(t('acceptance.workspace.renameError'));} finally {isSavingRef.current = false;setMutating(false);@@ -216,10 +215,10 @@ const AcceptanceRow = memo<AcceptanceRowProps>(({ item, onChanged }) => {try {await verifyService.updateAcceptanceStatus(item.id, status);await refresh();- message.success(t('verify:acceptance.workspace.statusSuccess'));+ message.success(t('acceptance.workspace.statusSuccess'));} catch (error) {console.error('[acceptance:status]', error);- message.error(t('verify:acceptance.workspace.statusError'));+ message.error(t('acceptance.workspace.statusError'));} finally {setMutating(false);}@@ -230,7 +229,7 @@ const AcceptanceRow = memo<AcceptanceRowProps>(({ item, onChanged }) => {return {icon: <Icon icon={CircleCheck} />,key: action,- label: t('verify:acceptance.workspace.actions.markAccepted'),+ label: t('acceptance.workspace.actions.markAccepted'),onClick: () => void changeStatus('accepted'),};}@@ -238,14 +237,14 @@ const AcceptanceRow = memo<AcceptanceRowProps>(({ item, onChanged }) => {return {icon: <Icon icon={RotateCcw} />,key: action,- label: t('verify:acceptance.workspace.actions.reopen'),+ label: t('acceptance.workspace.actions.reopen'),onClick: () => void changeStatus('delivered'),};}return {icon: <Icon icon={X} />,key: action,- label: t('verify:acceptance.workspace.actions.markClosed'),+ label: t('acceptance.workspace.actions.markClosed'),onClick: () => void changeStatus('closed'),};});@@ -254,7 +253,7 @@ const AcceptanceRow = memo<AcceptanceRowProps>(({ item, onChanged }) => {{icon: <Icon icon={Pencil} />,key: 'rename',- label: t('verify:acceptance.workspace.actions.rename'),+ label: t('acceptance.workspace.actions.rename'),onClick: () => {setDraftTitle(title);setEditing(true);@@ -266,7 +265,7 @@ const AcceptanceRow = memo<AcceptanceRowProps>(({ item, onChanged }) => {children: statusItems,icon: <Icon icon={CircleDashed} />,key: 'status',- label: t('verify:acceptance.workspace.actions.status'),+ label: t('acceptance.workspace.actions.status'),},{ type: 'divider' as const },]@@ -275,27 +274,27 @@ const AcceptanceRow = memo<AcceptanceRowProps>(({ item, onChanged }) => {danger: true,icon: <Icon icon={Trash2} />,key: 'delete',- label: t('verify:acceptance.workspace.actions.delete'),+ label: t('acceptance.workspace.actions.delete'),onClick: () => {confirmModal({- cancelText: t('common:cancel'),- content: t('verify:acceptance.workspace.deleteConfirmDescription', { title }),+ cancelText: t('actions.cancel'),+ content: t('acceptance.workspace.deleteConfirmDescription', { title }),okButtonProps: { danger: true },- okText: t('common:delete'),+ okText: t('actions.delete'),onOk: async () => {setMutating(true);try {await verifyService.deleteAcceptance(item.id);await onChanged();- message.success(t('verify:acceptance.workspace.deleteSuccess'));+ message.success(t('acceptance.workspace.deleteSuccess'));} catch (error) {console.error('[acceptance:delete]', error);- message.error(t('verify:acceptance.workspace.deleteError'));+ message.error(t('acceptance.workspace.deleteError'));} finally {setMutating(false);}},- title: t('verify:acceptance.workspace.deleteConfirmTitle'),+ title: t('acceptance.workspace.deleteConfirmTitle'),});},},@@ -364,7 +363,7 @@ const AcceptanceRow = memo<AcceptanceRowProps>(({ item, onChanged }) => {<ActionIconicon={MoreHorizontal}size={'small'}- title={t('verify:acceptance.workspace.actions.more')}+ title={t('acceptance.workspace.actions.more')}/></DropdownMenu></div>diff --git a/src/features/Verify/Acceptance/Workbench/SWRMutateInitializer.tsx b/apps/workbench/src/features/acceptance/SWRMutateInitializer.tsxsimilarity index 100%rename from src/features/Verify/Acceptance/Workbench/SWRMutateInitializer.tsxrename to apps/workbench/src/features/acceptance/SWRMutateInitializer.tsxdiff --git a/apps/workbench/src/features/acceptance/WorkspaceSidebar.tsx b/apps/workbench/src/features/acceptance/WorkspaceSidebar.tsxnew file mode 100644index 00000000000..f37241b9d25--- /dev/null+++ b/apps/workbench/src/features/acceptance/WorkspaceSidebar.tsx@@ -0,0 +1,132 @@+'use client';++import { Icon } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import dayjs from 'dayjs';+import relativeTime from 'dayjs/plugin/relativeTime';+import { PanelLeftOpen } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import AcceptanceListPanel from '@/features/Verify/Acceptance/Workspace/AcceptanceListPanel';+import { useReportPanelExpand } from '@/features/Verify/Workspace/useReportPanelExpand';++import WorkbenchBrandLink, {+ WorkbenchBrandCluster,+ WorkbenchBrandSlot,+} from '../../shell/WorkbenchBrandLink';++// AcceptanceRow calls dayjs().fromNow(); the main app extends this plugin in+// src/initialize.ts, which workbench never runs.+dayjs.extend(relativeTime);++const styles = createStaticStyles(({ css }) => ({+ brandOverlay: css`+ pointer-events: none;++ position: absolute;+ z-index: 30;+ inset-block-start: 0;+ inset-inline-start: 0;++ display: flex;+ align-items: center;++ height: 48px;+ padding-inline-start: 12px;++ transition: padding-inline-start 200ms ${cssVar.motionEaseOut};++ &[data-expand='true'] {+ padding-inline-start: 16px;+ }++ > * {+ pointer-events: auto;+ }++ @media (prefers-reduced-motion: reduce) {+ transition: none;+ }+ `,+ expandBtn: css`+ cursor: pointer;++ position: absolute;+ z-index: 20;+ inset-block-start: 60px;+ inset-inline-start: 12px;++ display: inline-flex;+ align-items: center;+ justify-content: center;++ width: 28px;+ height: 28px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 6px;++ color: ${cssVar.colorTextTertiary};++ background: ${cssVar.colorBgContainer};++ animation: workbench-expand-btn-in 120ms 200ms ${cssVar.motionEaseOut} both;++ &:hover {+ border-color: ${cssVar.colorBorder};+ color: ${cssVar.colorText};+ }++ @media (prefers-reduced-motion: reduce) {+ animation: none;+ }++ @keyframes workbench-expand-btn-in {+ from {+ pointer-events: none;+ opacity: 0;+ }++ to {+ pointer-events: auto;+ opacity: 1;+ }+ }+ `,+}));++export const HeaderBrand = memo(() => {+ const { expand } = useReportPanelExpand();+ return <WorkbenchBrandCluster collapsed={expand} />;+});++HeaderBrand.displayName = 'HeaderBrand';++const WorkspaceSidebar = memo(() => {+ const { t } = useTranslation('verify');+ const panel = useReportPanelExpand();++ return (+ <>+ <div className={styles.brandOverlay} data-expand={panel.expand}>+ <WorkbenchBrandLink divider={false} />+ </div>+ <AcceptanceListPanel {...panel} headerLeading={<WorkbenchBrandSlot />} />+ {!panel.expand && (+ <button+ aria-label={t('workspace.expand')}+ className={styles.expandBtn}+ title={t('workspace.expand')}+ type={'button'}+ onClick={() => panel.setExpand(true)}+ >+ <Icon icon={PanelLeftOpen} size={16} />+ </button>+ )}+ </>+ );+});++WorkspaceSidebar.displayName = 'WorkspaceSidebar';++export default WorkspaceSidebar;diff --git a/src/features/Verify/Acceptance/Workbench/AcceptanceDetail.tsx b/apps/workbench/src/features/verify/VerifyDetail.tsxsimilarity index 51%rename from src/features/Verify/Acceptance/Workbench/AcceptanceDetail.tsxrename to apps/workbench/src/features/verify/VerifyDetail.tsxindex f0b85218c88..c0958633c25 100644--- a/src/features/Verify/Acceptance/Workbench/AcceptanceDetail.tsx+++ b/apps/workbench/src/features/verify/VerifyDetail.tsx@@ -1,16 +1,18 @@'use client';-import ActionIcon from '@lobehub/ui/es/ActionIcon/index';import { Flexbox } from '@lobehub/ui/es/Flex/index';import Text from '@lobehub/ui/es/Text/index';import { createStaticStyles, cssVar } from 'antd-style';-import { ArrowLeft } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { useNavigate } from 'react-router';+import { useParams } from 'react-router';-import AcceptanceViewer from '..';-import SWRMutateInitializer from './SWRMutateInitializer';+import { useVerifyReportBundle } from '@/features/Verify/hooks';+import ReportViewer from '@/features/Verify/ReportViewer';+import { extractUuid } from '@/features/Verify/utils';++import WorkbenchBrandLink from '../../shell/WorkbenchBrandLink';+import SWRMutateInitializer from '../acceptance/SWRMutateInitializer';const styles = createStaticStyles(({ css }) => ({body: css`@@ -34,28 +36,28 @@ const styles = createStaticStyles(({ css }) => ({`,}));-const WorkbenchAcceptanceDetail = memo(() => {- const { t } = useTranslation(['verify', 'common']);- const navigate = useNavigate();+const WorkbenchVerifyDetail = memo(() => {+ const { t } = useTranslation('verify');+ const params = useParams<{ runId: string }>();+ const runId = extractUuid(params.runId);+ const { data } = useVerifyReportBundle(runId ?? null);return (<Flexbox className={styles.page}><SWRMutateInitializer /><Flexbox horizontal align={'center'} className={styles.header} gap={8}>- <ActionIcon- icon={ArrowLeft}- title={t('back', { ns: 'common' })}- onClick={() => navigate('/acceptance')}- />- <Text strong>{t('acceptance.workspace.title')}</Text>+ <WorkbenchBrandLink />+ <Text ellipsis strong style={{ minWidth: 0 }}>+ {data?.run.title ?? t('report.titleFallback')}+ </Text></Flexbox><div className={styles.body}>- <AcceptanceViewer />+ <ReportViewer /></div></Flexbox>);});-WorkbenchAcceptanceDetail.displayName = 'WorkbenchAcceptanceDetail';+WorkbenchVerifyDetail.displayName = 'WorkbenchVerifyDetail';-export default WorkbenchAcceptanceDetail;+export default WorkbenchVerifyDetail;diff --git a/apps/workbench/src/features/verify/VerifyList.tsx b/apps/workbench/src/features/verify/VerifyList.tsxnew file mode 100644index 00000000000..0bb54047bb8--- /dev/null+++ b/apps/workbench/src/features/verify/VerifyList.tsx@@ -0,0 +1,192 @@+'use client';++import Empty from '@lobehub/ui/es/Empty/index';+import { Center, Flexbox } from '@lobehub/ui/es/Flex/index';+import Icon from '@lobehub/ui/es/Icon/index';+import Text from '@lobehub/ui/es/Text/index';+import { createStaticStyles, cssVar } from 'antd-style';+import { ClipboardCheck, Search, TriangleAlert } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import useSWR from 'swr';++import { verifyKeys } from '@/libs/swr/keys';+import { verifyService } from '@/services/verify';++import WorkbenchBrandLink from '../../shell/WorkbenchBrandLink';+import VerifyRow from './VerifyRow';++const styles = createStaticStyles(({ css }) => ({+ content: css`+ overflow: hidden auto;+ flex: 1;+ min-height: 0;+ `,+ emptyState: css`+ min-height: 280px;+ padding-block: 24px;+ padding-inline: 16px;+ `,+ header: css`+ flex: none;+ padding: 12px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ `,+ list: css`+ display: flex;+ flex-direction: column;+ gap: 2px;++ padding-block: 8px 24px;+ padding-inline: 8px;+ `,+ page: css`+ width: 100%;+ height: 100dvh;+ background: ${cssVar.colorBgLayout};+ `,+ retry: css`+ cursor: pointer;++ padding-block: 6px;+ padding-inline: 12px;+ border: 1px solid ${cssVar.colorBorder};+ border-radius: ${cssVar.borderRadius};++ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorBgContainer};+ `,+ search: css`+ display: flex;+ gap: 8px;+ align-items: center;++ height: 36px;+ padding-inline: 11px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadius};++ background: ${cssVar.colorBgContainer};++ input {+ width: 100%;+ min-width: 0;+ border: 0;++ color: ${cssVar.colorText};++ background: transparent;+ outline: none;+ }+ `,+ searchEmpty: css`+ padding-block: 28px;+ padding-inline: 16px;+ color: ${cssVar.colorTextTertiary};+ `,+ skeleton: css`+ height: 52px;+ margin-block: 2px;+ border-radius: ${cssVar.borderRadiusLG};+ background: ${cssVar.colorFillTertiary};+ `,+ skeletonList: css`+ padding-block: 8px;+ padding-inline: 8px;+ `,+}));++const WorkbenchVerifyList = memo(() => {+ const { t } = useTranslation('verify');+ const [query, setQuery] = useState('');+ const trimmedQuery = query.trim();+ const { data, error, isLoading, mutate } = useSWR(+ verifyKeys.reportSummaries(undefined, trimmedQuery),+ () =>+ verifyService.listReportSummaries({+ limit: 50,+ q: trimmedQuery || undefined,+ }),+ {+ revalidateIfStale: false,+ revalidateOnFocus: false,+ revalidateOnReconnect: false,+ },+ );+ const items = data?.items ?? [];++ return (+ <Flexbox className={styles.page}>+ <Flexbox className={styles.header} gap={12}>+ <Flexbox horizontal align={'center'} gap={8}>+ <WorkbenchBrandLink />+ <Text strong style={{ flex: 1, fontSize: 17 }}>+ {t('workspace.title')}+ </Text>+ </Flexbox>+ <label className={styles.search}>+ <Icon color={cssVar.colorTextQuaternary} icon={Search} size={15} />+ <input+ placeholder={t('workspace.search')}+ type={'search'}+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ />+ </label>+ </Flexbox>++ <div className={styles.content}>+ {error ? (+ <Center className={styles.emptyState} gap={12}>+ <Empty+ description={t('workspace.loadError')}+ icon={TriangleAlert}+ title={t('workspace.loadErrorTitle')}+ />+ <button className={styles.retry} type={'button'} onClick={() => void mutate()}>+ {t('workspace.retry')}+ </button>+ </Center>+ ) : isLoading ? (+ <div className={styles.skeletonList}>+ {Array.from({ length: 8 }).map((_, index) => (+ <div className={styles.skeleton} key={index} />+ ))}+ </div>+ ) : items.length === 0 ? (+ trimmedQuery ? (+ <Flexbox className={styles.searchEmpty} gap={12}>+ <span>+ {t('workspace.searchEmptyPrefix')}+ {trimmedQuery}+ {t('workspace.searchEmptySuffix')}+ </span>+ <button className={styles.retry} type={'button'} onClick={() => setQuery('')}>+ {t('workspace.clearSearch')}+ </button>+ </Flexbox>+ ) : (+ <Center className={styles.emptyState}>+ <Empty+ description={t('workspace.listEmpty')}+ icon={ClipboardCheck}+ title={t('workspace.listEmptyTitle')}+ />+ </Center>+ )+ ) : (+ <div className={styles.list}>+ {items.map((item) => (+ <VerifyRow item={item} key={item.run.id} />+ ))}+ </div>+ )}+ </div>+ </Flexbox>+ );+});++WorkbenchVerifyList.displayName = 'WorkbenchVerifyList';++export default WorkbenchVerifyList;diff --git a/apps/workbench/src/features/verify/VerifyRow.tsx b/apps/workbench/src/features/verify/VerifyRow.tsxnew file mode 100644index 00000000000..22637dd6482--- /dev/null+++ b/apps/workbench/src/features/verify/VerifyRow.tsx@@ -0,0 +1,162 @@+'use client';++import type { VerifyRunStatus, VerifyVerdict } from '@lobechat/types';+import { Flexbox } from '@lobehub/ui/es/Flex/index';+import Icon from '@lobehub/ui/es/Icon/index';+import { createStaticStyles, cssVar } from 'antd-style';+import dayjs from 'dayjs';+import { CircleCheck, CircleHelp, CircleX, LoaderCircle } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router';++import type { VerifyReportSummary } from '@/services/verify';++const styles = createStaticStyles(({ css }) => ({+ counts: css`+ em {+ font-style: normal;+ color: ${cssVar.colorError};+ }+ `,+ itemSub: css`+ overflow: hidden;++ font-size: 12px;+ line-height: 16px;+ color: ${cssVar.colorTextTertiary};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ main: css`+ cursor: pointer;++ overflow: hidden;+ display: flex;+ gap: 10px;+ align-items: center;++ width: 100%;+ padding-block: 10px;+ padding-inline: 10px;+ border: 0;+ border-radius: ${cssVar.borderRadiusLG};++ text-align: start;++ background: transparent;++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }+ `,+ row: css`+ display: flex;+ align-items: stretch;+ `,+ spin: css`+ animation: workbench-verify-spin 0.9s linear infinite;++ @keyframes workbench-verify-spin {+ to {+ transform: rotate(360deg);+ }+ }+ `,+ title: css`+ overflow: hidden;++ font-size: 14px;+ font-weight: 500;+ line-height: 20px;+ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+}));++type Glyph = 'ok' | 'bad' | 'unsure' | 'running';++const runningStatuses = new Set<VerifyRunStatus>(['planned', 'repairing', 'verifying']);++const glyphOf = (+ status: VerifyRunStatus | null,+ verdict: VerifyVerdict | null | undefined,+): Glyph => {+ if (status && runningStatuses.has(status)) return 'running';+ if (verdict === 'passed' || status === 'passed' || status === 'delivered') return 'ok';+ if (verdict === 'failed' || status === 'failed') return 'bad';+ return 'unsure';+};++const glyphMeta: Record<Glyph, { color: string; icon: typeof CircleCheck }> = {+ bad: { color: cssVar.colorError, icon: CircleX },+ ok: { color: cssVar.colorSuccess, icon: CircleCheck },+ running: { color: cssVar.colorInfo, icon: LoaderCircle },+ unsure: { color: cssVar.colorWarning, icon: CircleHelp },+};++const relativeTime = (value?: Date | string | null) => {+ if (!value) return '';+ const d = dayjs(value);+ return dayjs().diff(d, 'day') < 7 ? d.fromNow() : d.format('MMM D');+};++interface VerifyRowProps {+ item: VerifyReportSummary;+}++const VerifyRow = memo<VerifyRowProps>(({ item }) => {+ const { t } = useTranslation('verify');+ const navigate = useNavigate();+ const status = item.run.status ?? null;+ const glyph = glyphOf(status, item.report?.verdict);+ const meta = glyphMeta[glyph];+ const planCount = Array.isArray(item.run.plan) ? item.run.plan.length : 0;+ const total = item.report?.totalChecks ?? planCount;+ const passed = item.report?.passedChecks ?? 0;+ const failed = item.report?.failedChecks ?? 0;+ const title = item.run.title || t('reports.untitled');+ const time =+ glyph === 'running'+ ? t('list.running')+ : relativeTime(item.report?.generatedAt ?? item.run.createdAt);++ return (+ <div className={styles.row}>+ <button+ className={styles.main}+ type={'button'}+ onClick={() => navigate(`/verify/${item.run.id}`)}+ >+ <Icon+ className={glyph === 'running' ? styles.spin : undefined}+ icon={meta.icon}+ size={17}+ style={{ color: meta.color }}+ />+ <span style={{ minWidth: 0 }}>+ <span className={styles.title}>{title}</span>+ <Flexbox horizontal className={styles.itemSub} gap={8}>+ {time ? <span>{time}</span> : null}+ {total > 0 && glyph !== 'running' ? (+ <span className={styles.counts}>+ {passed}/{total}+ {failed > 0 ? (+ <>+ {' · '}+ <em>{t('list.failedCount', { count: failed })}</em>+ </>+ ) : null}+ </span>+ ) : null}+ </Flexbox>+ </span>+ </button>+ </div>+ );+});++VerifyRow.displayName = 'VerifyRow';++export default VerifyRow;diff --git a/src/spa/router/workbenchRouter.config.tsx b/apps/workbench/src/router.tsxsimilarity index 72%rename from src/spa/router/workbenchRouter.config.tsxrename to apps/workbench/src/router.tsxindex 81f90347016..75fdba8f0d2 100644--- a/src/spa/router/workbenchRouter.config.tsx+++ b/apps/workbench/src/router.tsx@@ -4,12 +4,11 @@ import { lazy, Suspense, useEffect } from 'react';import type { RouteObject } from 'react-router';import { Outlet, useRouteError } from 'react-router';-import WorkbenchShell, { WorkbenchNamespace } from '@/features/WorkbenchShell';-import WorkbenchLoading from '@/features/WorkbenchShell/WorkbenchLoading';import { isChunkLoadError, notifyChunkError } from '@/utils/chunkError';-// Keep this helper local. Importing the shared SPA router helper would pull the-// Main SPA provider and global stores into the Workbench entry chunk.+import WorkbenchShell, { WorkbenchNamespace } from './shell';+import WorkbenchLoading from './shell/WorkbenchLoading';+const lazyElement = (importFn: () => Promise<{ default: ComponentType }>): ReactElement => {const LazyComponent = lazy(importFn);@@ -70,35 +69,51 @@ const ExitWorkbench = () => {return <WorkbenchLoading />;};+const VerifyNamespace = () => (+ <WorkbenchNamespace namespace="verify">+ <Outlet />+ </WorkbenchNamespace>+);+export const workbenchRoutes: RouteObject[] = [{children: [{- element: lazyElement(() => import('@/routes/(workbench)/agent/docs/[docId]')),+ element: lazyElement(() => import('./routes/agent/docs/[docId]')),path: 'agent/:aid/docs/:docId',},{children: [{- element: lazyElement(() => import('@/routes/(workbench)/acceptance')),+ element: lazyElement(() => import('./routes/acceptance')),index: true,},{- element: lazyElement(() => import('@/routes/(workbench)/acceptance/[acceptanceId]')),+ element: lazyElement(() => import('./routes/acceptance/[acceptanceId]')),path: ':acceptanceId',},{- element: lazyElement(() => import('@/routes/(workbench)/acceptance/[acceptanceId]')),+ element: lazyElement(() => import('./routes/acceptance/[acceptanceId]')),path: ':acceptanceId/check/:checkId',},],- element: (- <WorkbenchNamespace namespace="verify">- <Outlet />- </WorkbenchNamespace>- ),+ element: <VerifyNamespace />,path: 'acceptance',},+ {+ children: [+ {+ element: lazyElement(() => import('./routes/verify')),+ index: true,+ },+ {+ element: lazyElement(() => import('./routes/verify/[runId]')),+ path: ':runId',+ },+ ],+ element: <VerifyNamespace />,+ path: 'verify',+ },{element: <ExitWorkbench />,path: '*',diff --git a/apps/workbench/src/routes/acceptance/[acceptanceId]/index.tsx b/apps/workbench/src/routes/acceptance/[acceptanceId]/index.tsxnew file mode 100644index 00000000000..3f490a823cc--- /dev/null+++ b/apps/workbench/src/routes/acceptance/[acceptanceId]/index.tsx@@ -0,0 +1,3 @@+'use client';++export { default } from '../../../features/acceptance/AcceptanceDetail';diff --git a/apps/workbench/src/routes/acceptance/index.tsx b/apps/workbench/src/routes/acceptance/index.tsxnew file mode 100644index 00000000000..9efce276093--- /dev/null+++ b/apps/workbench/src/routes/acceptance/index.tsx@@ -0,0 +1,3 @@+'use client';++export { default } from '../../features/acceptance/AcceptanceList';diff --git a/src/routes/(workbench)/agent/docs/[docId]/index.tsx b/apps/workbench/src/routes/agent/docs/[docId]/index.tsxsimilarity index 100%rename from src/routes/(workbench)/agent/docs/[docId]/index.tsxrename to apps/workbench/src/routes/agent/docs/[docId]/index.tsxdiff --git a/apps/workbench/src/routes/verify/[runId]/index.tsx b/apps/workbench/src/routes/verify/[runId]/index.tsxnew file mode 100644index 00000000000..86a73d14c21--- /dev/null+++ b/apps/workbench/src/routes/verify/[runId]/index.tsx@@ -0,0 +1,3 @@+'use client';++export { default } from '../../../features/verify/VerifyDetail';diff --git a/apps/workbench/src/routes/verify/index.tsx b/apps/workbench/src/routes/verify/index.tsxnew file mode 100644index 00000000000..ef043cb230b--- /dev/null+++ b/apps/workbench/src/routes/verify/index.tsx@@ -0,0 +1,3 @@+'use client';++export { default } from '../../features/verify/VerifyList';diff --git a/apps/workbench/src/shell/WorkbenchBrandLink.tsx b/apps/workbench/src/shell/WorkbenchBrandLink.tsxnew file mode 100644index 00000000000..93bac6f0fd6--- /dev/null+++ b/apps/workbench/src/shell/WorkbenchBrandLink.tsx@@ -0,0 +1,165 @@+'use client';++import { BRANDING_NAME } from '@lobechat/business-const';+import { createStaticStyles, cssVar } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { ProductLogo } from '@/components/Branding';++const styles = createStaticStyles(({ css }) => ({+ brand: css`+ display: flex;+ flex: none;+ align-items: center;+ justify-content: center;++ box-sizing: content-box;+ padding: 4px;+ border-radius: ${cssVar.borderRadius};++ line-height: 0;++ transition: background 120ms ease;++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }+ `,+ divider: css`+ flex: none;++ width: 1px;+ height: 16px;++ background: ${cssVar.colorBorderSecondary};++ transition:+ width 200ms ${cssVar.motionEaseOut},+ opacity 200ms ${cssVar.motionEaseOut};++ @media (prefers-reduced-motion: reduce) {+ transition: none;+ }+ `,+ dividerCollapsed: css`+ overflow: hidden;+ flex: none;++ width: 0;+ height: 16px;++ opacity: 0;++ transition:+ width 200ms ${cssVar.motionEaseOut},+ opacity 200ms ${cssVar.motionEaseOut};++ @media (prefers-reduced-motion: reduce) {+ transition: none;+ }+ `,+ slot: css`+ overflow: hidden;+ flex: none;++ width: 30px;+ height: 30px;++ transition: width 200ms ${cssVar.motionEaseOut};++ @media (prefers-reduced-motion: reduce) {+ transition: none;+ }+ `,+ slotCollapsed: css`+ overflow: hidden;+ flex: none;++ width: 0;+ height: 30px;++ transition: width 200ms ${cssVar.motionEaseOut};++ @media (prefers-reduced-motion: reduce) {+ transition: none;+ }+ `,+ cluster: css`+ overflow: hidden;+ display: flex;+ flex: none;+ gap: 8px;+ align-items: center;++ max-width: 39px;++ transition:+ max-width 200ms ${cssVar.motionEaseOut},+ gap 200ms ${cssVar.motionEaseOut};++ @media (prefers-reduced-motion: reduce) {+ transition: none;+ }+ `,+ clusterCollapsed: css`+ overflow: hidden;+ display: flex;+ flex: none;+ gap: 0;+ align-items: center;++ max-width: 0;++ transition:+ max-width 200ms ${cssVar.motionEaseOut},+ gap 200ms ${cssVar.motionEaseOut};++ @media (prefers-reduced-motion: reduce) {+ transition: none;+ }+ `,+}));++export const WorkbenchBrandSlot = memo<{ collapsed?: boolean }>(({ collapsed = false }) => (+ <div className={collapsed ? styles.slotCollapsed : styles.slot} />+));++WorkbenchBrandSlot.displayName = 'WorkbenchBrandSlot';++export const WorkbenchBrandDivider = memo<{ collapsed?: boolean }>(({ collapsed = false }) => (+ <div className={collapsed ? styles.dividerCollapsed : styles.divider} />+));++WorkbenchBrandDivider.displayName = 'WorkbenchBrandDivider';++export const WorkbenchBrandCluster = memo<{ collapsed?: boolean }>(({ collapsed = false }) => (+ <div className={collapsed ? styles.clusterCollapsed : styles.cluster}>+ <WorkbenchBrandSlot />+ <WorkbenchBrandDivider />+ </div>+));++WorkbenchBrandCluster.displayName = 'WorkbenchBrandCluster';++interface WorkbenchBrandLinkProps {+ divider?: boolean;+}++const WorkbenchBrandLink = memo<WorkbenchBrandLinkProps>(({ divider = true }) => {+ const { t } = useTranslation('verify');+ const label = t('actions.backToApp', { name: BRANDING_NAME });++ return (+ <>+ <a aria-label={label} className={styles.brand} href={'/'} title={label}>+ <ProductLogo size={22} />+ </a>+ {divider ? <WorkbenchBrandDivider /> : null}+ </>+ );+});++WorkbenchBrandLink.displayName = 'WorkbenchBrandLink';++export default WorkbenchBrandLink;diff --git a/src/features/WorkbenchShell/WorkbenchLoading.tsx b/apps/workbench/src/shell/WorkbenchLoading.tsxsimilarity index 100%rename from src/features/WorkbenchShell/WorkbenchLoading.tsxrename to apps/workbench/src/shell/WorkbenchLoading.tsxdiff --git a/src/features/WorkbenchShell/WorkbenchLocale.tsx b/apps/workbench/src/shell/WorkbenchLocale.tsxsimilarity index 91%rename from src/features/WorkbenchShell/WorkbenchLocale.tsxrename to apps/workbench/src/shell/WorkbenchLocale.tsxindex 37cddba9eb1..8d23ce4a7e9 100644--- a/src/features/WorkbenchShell/WorkbenchLocale.tsx+++ b/apps/workbench/src/shell/WorkbenchLocale.tsx@@ -42,14 +42,15 @@ const updateDayjs = async (lang: string) => {interface WorkbenchLocaleProps extends PropsWithChildren {defaultLang?: string;+ resources?: Record<string, unknown>;}-const WorkbenchLocale = memo<WorkbenchLocaleProps>(({ children, defaultLang }) => {- const [i18n] = useState(() => createWorkbenchI18n(defaultLang));+const WorkbenchLocale = memo<WorkbenchLocaleProps>(({ children, defaultLang, resources }) => {+ const [i18n] = useState(() => createWorkbenchI18n(defaultLang, resources));const [lang, setLang] = useState(defaultLang ?? 'en-US');const [antdLocale, setAntdLocale] = useState<any>();- if (!i18n.instance.isInitialized) void i18n.init();+ if (!i18n.instance.isInitialized) void i18n.init({ initAsync: !resources });useEffect(() => {const applyLocale = async (nextLang: string) => {diff --git a/src/features/WorkbenchShell/WorkbenchNamespace.tsx b/apps/workbench/src/shell/WorkbenchNamespace.tsxsimilarity index 100%rename from src/features/WorkbenchShell/WorkbenchNamespace.tsxrename to apps/workbench/src/shell/WorkbenchNamespace.tsxdiff --git a/src/features/WorkbenchShell/WorkbenchShell.tsx b/apps/workbench/src/shell/WorkbenchShell.tsxsimilarity index 59%rename from src/features/WorkbenchShell/WorkbenchShell.tsxrename to apps/workbench/src/shell/WorkbenchShell.tsxindex 48f99ea8123..e2713510275 100644--- a/src/features/WorkbenchShell/WorkbenchShell.tsx+++ b/apps/workbench/src/shell/WorkbenchShell.tsx@@ -10,12 +10,28 @@ import type { SPAServerConfig } from '@/types/spaServerConfig';import WorkbenchLocale from './WorkbenchLocale';import WorkbenchTheme from './WorkbenchTheme';-const WorkbenchShell = memo<PropsWithChildren>(({ children }) => {- const serverConfig: SPAServerConfig | undefined = window.__SERVER_CONFIG__;- const locale = document.documentElement.lang || 'en-US';+interface WorkbenchShellProps extends PropsWithChildren {+ locale?: string;+ resources?: Record<string, unknown>;+ serverConfig?: SPAServerConfig | null;+}++const WorkbenchShell = memo<WorkbenchShellProps>((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 (- <WorkbenchLocale defaultLang={locale}>+ <WorkbenchLocale defaultLang={locale} resources={resources}><WorkbenchTheme><ServerConfigStoreProviderisMobilediff --git a/src/features/WorkbenchShell/WorkbenchTheme.tsx b/apps/workbench/src/shell/WorkbenchTheme.tsxsimilarity index 100%rename from src/features/WorkbenchShell/WorkbenchTheme.tsxrename to apps/workbench/src/shell/WorkbenchTheme.tsxdiff --git a/src/features/WorkbenchShell/createWorkbenchI18n.ts b/apps/workbench/src/shell/createWorkbenchI18n.tssimilarity index 61%rename from src/features/WorkbenchShell/createWorkbenchI18n.tsrename to apps/workbench/src/shell/createWorkbenchI18n.tsindex 37390d97a0e..7221d71dfca 100644--- a/src/features/WorkbenchShell/createWorkbenchI18n.ts+++ b/apps/workbench/src/shell/createWorkbenchI18n.ts@@ -3,24 +3,15 @@ import resourcesToBackend from 'i18next-resources-to-backend';import { initReactI18next } from 'react-i18next';import { DEFAULT_LANG } from '@/const/locale';-import defaultCommon from '@/locales/default/common';-import defaultError from '@/locales/default/error';import { normalizeLocale } from '@/locales/resources';import { unwrapESMModule } from '@/utils/esm/unwrapESMModule';import { loadI18nNamespaceModule } from '@/utils/i18n/loadI18nNamespaceModule';-const defaultResources = {- common: defaultCommon,- error: defaultError,-};+export const workbenchNamespaces = ['verify'] as const;-const loadWorkbenchNamespace = async (lng: string, ns: string) => {+export const loadWorkbenchNamespace = async (lng: string, ns: string) => {const locale = normalizeLocale(lng);- if (locale === DEFAULT_LANG && ns in defaultResources) {- return defaultResources[ns as keyof typeof defaultResources];- }-return unwrapESMModule(await loadI18nNamespaceModule({defaultLang: DEFAULT_LANG,@@ -31,7 +22,19 @@ const loadWorkbenchNamespace = async (lng: string, ns: string) => {);};-export const createWorkbenchI18n = (lang?: string) => {+export const loadWorkbenchResources = async (lang?: string) => {+ const locale = normalizeLocale(lang);+ const entries = await Promise.all(+ workbenchNamespaces.map(async (ns) => [ns, await loadWorkbenchNamespace(locale, ns)] as const),+ );++ return Object.fromEntries(entries) as Record<string, unknown>;+};++export const createWorkbenchI18n = (lang?: string, bundledResources?: Record<string, unknown>) => {+ const locale = normalizeLocale(lang);+ const resources = bundledResources ? { [locale]: bundledResources } : undefined;+const instance = i18next.createInstance().use(initReactI18next)@@ -40,19 +43,19 @@ export const createWorkbenchI18n = (lang?: string) => {return {init: (params: { initAsync?: boolean } = {}) =>instance.init({- defaultNS: ['common', 'error'],+ defaultNS: 'verify',fallbackLng: DEFAULT_LANG,initAsync: params.initAsync ?? true,interpolation: { escapeValue: false },keySeparator: false,- lng: normalizeLocale(lang),+ lng: locale,ns: [],partialBundledLanguages: true,react: {bindI18nStore: 'added',useSuspense: false,},- resources: { [DEFAULT_LANG]: defaultResources },+ resources,showSupportNotice: false,}),instance,diff --git a/src/features/WorkbenchShell/index.ts b/apps/workbench/src/shell/index.tssimilarity index 100%rename from src/features/WorkbenchShell/index.tsrename to apps/workbench/src/shell/index.tsdiff --git a/apps/workbench/src/vite-env.d.ts b/apps/workbench/src/vite-env.d.tsnew file mode 100644index 00000000000..11f02fe2a00--- /dev/null+++ b/apps/workbench/src/vite-env.d.ts@@ -0,0 +1 @@+/// <reference types="vite/client" />diff --git a/apps/workbench/staticCssOptions.mjs b/apps/workbench/staticCssOptions.mjsnew file mode 100644index 00000000000..987e0985f9c--- /dev/null+++ b/apps/workbench/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/workbench/tsconfig.json b/apps/workbench/tsconfig.jsonnew file mode 100644index 00000000000..7c7c06579da--- /dev/null+++ b/apps/workbench/tsconfig.json@@ -0,0 +1,19 @@+{+ "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"+ ]+}diff --git a/apps/workbench/vite.config.rr.mts b/apps/workbench/vite.config.rr.mtsnew file mode 100644index 00000000000..a308a4a3e1a--- /dev/null+++ b/apps/workbench/vite.config.rr.mts@@ -0,0 +1,277 @@+import { readFileSync, 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 } 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 { sharedRendererDefine } from '../../plugins/vite/sharedRendererConfig';+import { antdStaticCssOptions, themeVarsCssOptions } from './staticCssOptions.mjs';++const repoRoot = path.resolve(import.meta.dirname, '../..');++const define = {+ ...sharedRendererDefine({ isElectron: false, isMobile: true }),+ __WORKBENCH__: 'true',+};++const { 'process.env': _processEnvFallback, ...ssrDefine } = define;++const ssrStubs: Record<string, string> = {+ '@/libs/trpc/client': path.resolve(import.meta.dirname, 'app/stubs/trpcClient.ts'),+ '@/services/global': path.resolve(import.meta.dirname, 'app/stubs/globalService.ts'),+ '@/store/electron': path.resolve(import.meta.dirname, 'app/stubs/electronStore.ts'),+ '@/store/file': path.resolve(import.meta.dirname, 'app/stubs/fileStore.ts'),+ '@/utils/i18n/loadI18nNamespaceModule': path.resolve(+ import.meta.dirname,+ 'app/stubs/loadI18nNamespaceModule.ts',+ ),+};++const workbenchSsrStubs = (): Plugin => ({+ applyToEnvironment: (environment) => environment.name === 'ssr',+ enforce: 'pre',+ name: 'workbench-ssr-stubs',+ resolveId(source) {+ return ssrStubs[source];+ },+});++const i18nClientStub = path.resolve(+ import.meta.dirname,+ 'app/stubs/loadI18nNamespaceModule.client.ts',+);++const clientStubs: Record<string, string> = {+ '@/utils/i18n/loadI18nNamespaceModule': i18nClientStub,+};++const workbenchClientStubs = (): Plugin => ({+ applyToEnvironment: (environment) => environment.name === 'client',+ enforce: 'pre',+ name: 'workbench-client-stubs',+ resolveId(source) {+ return clientStubs[source];+ },+});++// Referenced in the client graph only from store tails that never execute in+// workbench flows; requesting one at runtime degrades to raw keys instead of+// bundling 18 locale files each.+const I18N_DEAD_NS = new Set(['electron', 'file', 'modelProvider', 'setting', 'topic', 'video']);++const I18N_NS_PATTERNS = [+ /useTranslation\(\s*['"]([A-Za-z]+)['"]/g,+ /\bns\s*[:=]\s*(?:\{\s*)?['"]([A-Za-z]+)['"]/g,+ /\bt\(\s*['"]([A-Za-z]+):/g,+];+const I18N_NS_ARRAY_PATTERN = /useTranslation\(\s*\[([^\]]*)\]/g;++const clientI18nNsGuard = (): Plugin => ({+ apply: 'build',+ applyToEnvironment: (environment) => environment.name === 'client',+ buildEnd() {+ const bundled = new Set(+ [...readFileSync(i18nClientStub, 'utf8').matchAll(/locales\/\*\/([A-Za-z]+)\.json/g)].map(+ (m) => m[1]!,+ ),+ );+ const offenders = new Map<string, Set<string>>();+ for (const id of this.getModuleIds()) {+ if (!id.startsWith(repoRoot) || id.includes('/node_modules/') || id.includes('\0')) continue;+ const file = id.split('?')[0]!;+ if (!/\.tsx?$/.test(file)) continue;+ const rel = path.relative(repoRoot, file);+ if (rel.startsWith('locales/') || rel.startsWith('packages/locales/')) continue;+ let source: string;+ try {+ source = readFileSync(file, 'utf8');+ } catch {+ continue;+ }+ const found = new Set<string>();+ for (const pattern of I18N_NS_PATTERNS) {+ for (const match of source.matchAll(pattern)) found.add(match[1]!);+ }+ for (const match of source.matchAll(I18N_NS_ARRAY_PATTERN)) {+ for (const inner of match[1]!.matchAll(/['"]([A-Z]+)['"]/gi)) found.add(inner[1]!);+ }+ for (const ns of found) {+ if (bundled.has(ns) || I18N_DEAD_NS.has(ns)) continue;+ if (!offenders.has(ns)) offenders.set(ns, new Set());+ offenders.get(ns)!.add(rel);+ }+ }+ if (offenders.size > 0) {+ const lines = [...offenders].map(([ns, files]) => ` ${ns}: ${[...files].join(', ')}`);+ this.error(+ `i18n namespaces referenced in the client graph but not bundled:\n${lines.join('\n')}\n` ++ `Add glob entries in app/stubs/loadI18nNamespaceModule.client.ts, ` ++ `or add to I18N_DEAD_NS in vite.config.rr.mts if the code path never runs in workbench.`,+ );+ }+ },+ name: 'workbench-client-i18n-ns-guard',+});++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(import.meta.dirname, 'ssr-chunk-report.json'),+ JSON.stringify(report),+ );+ },+ name: 'workbench-ssr-chunk-report',+});++const ssrModuleTrace = (needle: string): Plugin => ({+ applyToEnvironment: (environment) =>+ environment.name === (process.env.WORKBENCH_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.includes('apps/workbench') || 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: 'workbench-ssr-module-trace',+});++const proxyTarget = process.env.WORKBENCH_API_PROXY || 'https://app.lobehub.com';++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: 'workbench-build-inputs-manifest',+ writeBundle(options) {+ if (!options.dir?.includes('build/server')) return;+ const manifest = [...buildInputIds].sort().join('\n');+ writeFileSync(path.resolve(import.meta.dirname, '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(antdStaticCssOptions).css+ : buildThemeVarsCss(themeVarsCssOptions).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: 'workbench-static-css-dev-serve',+ };+};++const backendProxy = Object.fromEntries(+ ['/api', '/oidc', '/trpc', '/webapi'].map((prefix) => [+ prefix,+ { changeOrigin: true, target: proxyTarget },+ ]),+);++const isDev = process.env.NODE_ENV !== 'production';++export default defineConfig({+ base: isDev ? '/' : process.env.VITE_CDN_BASE || '/',+ environments: {+ client: { define },+ ssr: { define: ssrDefine },+ },+ plugins: [+ process.env.WORKBENCH_CHUNK_REPORT ? ssrChunkReport() : undefined,+ process.env.WORKBENCH_TRACE_MODULE+ ? ssrModuleTrace(process.env.WORKBENCH_TRACE_MODULE)+ : undefined,+ workbenchSsrStubs(),+ workbenchClientStubs(),+ clientI18nNsGuard(),+ buildInputsManifest(),+ viteMarkdownImport(),+ viteNodeModuleStub(),+ vitePlatformResolve('mobile'),+ cloudflare({ viteEnvironment: { name: 'ssr' } }),+ lobeStaticCssPlugin({ antd: antdStaticCssOptions, themeVars: themeVarsCssOptions }),+ staticCssDevServe(),+ reactRouter(),+ ...lobeIconImports(),+ ],+ resolve: {+ tsconfigPaths: true,+ },+ server: {+ fs: {+ allow: [repoRoot],+ },+ port: Number(process.env.WORKBENCH_SPA_PORT) || 3015,+ proxy: backendProxy,+ },+});diff --git a/apps/workbench/vite.config.ts b/apps/workbench/vite.config.tsnew file mode 100644index 00000000000..c5384955965--- /dev/null+++ b/apps/workbench/vite.config.ts@@ -0,0 +1,74 @@+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-workbench/',+ build: {+ emptyOutDir: true,+ modulePreload: sharedModulePreload,+ outDir: path.resolve(repoRoot, 'dist/workbench'),+ reportCompressedSize: false,+ rolldownOptions: {+ output: createSharedRolldownOutput({ strictExecutionOrder: true }),+ },+ },+ define: {+ ...sharedRendererDefine({ isElectron: false, isMobile: true }),+ },+ experimental: {+ bundledDev: false,+ },+ optimizeDeps: sharedOptimizeDeps,+ plugins: [+ tsconfigPaths({+ ignoreConfigErrors: true,+ projects: [path.resolve(repoRoot, 'tsconfig.json')],+ root: repoRoot,+ }),+ vercelSkewProtection(),+ viteEnvRestartKeys(['APP_URL']),+ ...sharedRendererPlugins({ platform: 'mobile' }),+ ].filter(Boolean) as PluginOption[],+ resolve: {+ dedupe: sharedRendererDedupe,+ },+ root: __dirname,+ server: {+ cors: true,+ fs: {+ allow: [repoRoot],+ },+ host: true,+ port: Number(process.env.WORKBENCH_SPA_PORT) || 3014,+ 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/workbench/workers/app.ts b/apps/workbench/workers/app.tsnew file mode 100644index 00000000000..242805fecba--- /dev/null+++ b/apps/workbench/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.WORKBENCH_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/workbench/wrangler.jsonc b/apps/workbench/wrangler.jsoncnew file mode 100644index 00000000000..a7020a90004--- /dev/null+++ b/apps/workbench/wrangler.jsonc@@ -0,0 +1,17 @@+{+ "$schema": "../../node_modules/wrangler/config-schema.json",+ "name": "lobehub-workbench",+ "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": {+ "WORKBENCH_API_BASE": "https://app.lobehub.com",+ "WORKBENCH_APP_HOME": "https://lobehub.com"+ }+}diff --git a/index.workbench.html b/index.workbench.htmlindex 7ba864bb7d9..c8c4d3c3eef 100644--- a/index.workbench.html+++ b/index.workbench.html@@ -90,6 +90,6 @@<div id="root" style="height: 100%"></div><!--ANALYTICS_SCRIPTS-->- <script type="module" src="/src/spa/entry.workbench.tsx"></script>+ <script type="module" src="/apps/workbench/src/entry.tsx"></script></body></html>diff --git a/locales/en-US/verify.json b/locales/en-US/verify.jsonindex aebca155f79..e56e3e20cad 100644--- a/locales/en-US/verify.json+++ b/locales/en-US/verify.json@@ -281,6 +281,9 @@"acceptance.workspace.statusError": "Failed to update status","acceptance.workspace.statusSuccess": "Status updated","acceptance.workspace.title": "Deliveries",+ "actions.backToApp": "Back to {{name}}",+ "actions.cancel": "Cancel",+ "actions.delete": "Delete","badge.errored": "Check could not run","badge.failed": "Check failed","badge.passed": "Check passed",@@ -348,6 +351,7 @@"input.placeholder": "e.g. run type-check first; if it still fails, just add a risk note.","list.failedCount": "{{count}} failed","list.running": "Verifying…",+ "meta.description": "Verification runs, delivery reports, and acceptance reviews.","report.actions.copyLink": "Copy link","report.actions.copyLinkSuccess": "Link copied","report.actions.openInBrowser": "Open in browser",diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.jsonindex 808ee7b3bbd..13c9cf046f6 100644--- a/locales/zh-CN/verify.json+++ b/locales/zh-CN/verify.json@@ -281,6 +281,9 @@"acceptance.workspace.statusError": "状态更新失败","acceptance.workspace.statusSuccess": "状态已更新","acceptance.workspace.title": "交付",+ "actions.backToApp": "返回 {{name}}",+ "actions.cancel": "取消",+ "actions.delete": "删除","badge.errored": "检查无法运行","badge.failed": "检查未通过","badge.passed": "检查通过",@@ -348,6 +351,7 @@"input.placeholder": "例如:先跑 type-check;若仍失败,补一条风险说明即可。","list.failedCount": "{{count}} 项未通过","list.running": "验证中…",+ "meta.description": "验证运行、交付报告与验收评审。","report.actions.copyLink": "复制链接","report.actions.copyLinkSuccess": "链接已复制","report.actions.openInBrowser": "在浏览器中打开",diff --git a/package.json b/package.jsonindex 811f6be3c78..91c548bc0c1 100644--- a/package.json+++ b/package.json@@ -30,19 +30,19 @@"./src/spa/entry.desktop.tsx","./src/spa/entry.mobile.tsx","./src/spa/entry.popup.tsx",- "./src/spa/entry.workbench.tsx","./src/spa/entry.web.tsx"],"workspaces": ["packages/*","packages/business/*","e2e",- "apps/desktop/src/main"+ "apps/desktop/src/main",+ "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: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 && 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 && cross-env WORKBENCH_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",@@ -51,7 +51,7 @@"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:workbench": "rm -rf dist/workbench public/_spa-workbench && cross-env NODE_OPTIONS=--max-old-space-size=8192 SPA_TARGET=workbench vite 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","check": "bun run .agents/scripts/check/cli.ts",@@ -78,7 +78,7 @@"dev:spa": "vite","dev:spa:auth": "cross-env AUTH=true vite","dev:spa:mobile": "cross-env MOBILE=true vite",- "dev:spa:workbench": "cross-env SPA_TARGET=workbench vite --port 3014",+ "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","docs:seo": "lobe-seo && npm run lint:mdx",@@ -304,7 +304,7 @@"@lobehub/icons": "^5.15.0","@lobehub/market-sdk": "0.39.2","@lobehub/tts": "^5.1.2",- "@lobehub/ui": "^5.30.0",+ "@lobehub/ui": "^5.32.0","@modelcontextprotocol/sdk": "^1.30.0","@neondatabase/serverless": "^1.1.0","@next/third-parties": "^16.3.0",@@ -576,7 +576,8 @@"pnpm": {"onlyBuiltDependencies": ["@lobehub/editor",- "ffmpeg-static"+ "ffmpeg-static",+ "workerd"],"overrides": {"@react-pdf/image": "3.0.4",diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.tsindex fc9fe9f01c9..c06cbc5f375 100644--- a/packages/locales/src/default/verify.ts+++ b/packages/locales/src/default/verify.ts@@ -316,6 +316,10 @@ export default {'acceptance.workspace.statusError': 'Failed to update status','acceptance.workspace.statusSuccess': 'Status updated','acceptance.workspace.title': 'Deliveries',+ 'actions.backToApp': 'Back to {{name}}',+ 'meta.description': 'Verification runs, delivery reports, and acceptance reviews.',+ 'actions.cancel': 'Cancel',+ 'actions.delete': 'Delete','report.actions.copyLink': 'Copy link','report.actions.copyLinkSuccess': 'Link copied','report.actions.openInBrowser': 'Open in browser',diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 287c2fa2fa7..cefe61f6349 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -5,6 +5,7 @@ packages:- e2e- apps/desktop/src/main- apps/server+ - apps/workbenchminimumReleaseAgeExclude:- '@lobehub/[email protected]'diff --git a/scripts/dockerWorkspaceManifests.test.ts b/scripts/dockerWorkspaceManifests.test.tsnew file mode 100644index 00000000000..e0782a0376b--- /dev/null+++ b/scripts/dockerWorkspaceManifests.test.ts@@ -0,0 +1,17 @@+import { readFileSync } from 'node:fs';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++const dockerfile = readFileSync(path.resolve(import.meta.dirname, '../Dockerfile'), 'utf8');++describe('Docker workspace manifests', () => {+ it('copies the Workbench package manifest before pnpm i', () => {+ const copyIdx = dockerfile.indexOf('COPY apps/workbench/package.json');+ const installIdx = dockerfile.indexOf('\n pnpm i &&');++ expect(copyIdx).toBeGreaterThan(-1);+ expect(installIdx).toBeGreaterThan(-1);+ expect(copyIdx).toBeLessThan(installIdx);+ });+});diff --git a/scripts/generateSpaTemplates.mts b/scripts/generateSpaTemplates.mtsindex 327e5e22f00..cdc7a0c180a 100644--- a/scripts/generateSpaTemplates.mts+++ b/scripts/generateSpaTemplates.mts@@ -1,6 +1,8 @@import { existsSync, readFileSync, writeFileSync } from 'node:fs';import path from 'node:path';+import { requireWorkbenchHtmlPath, resolveWorkbenchHtmlPath } from './spaHtmlPaths.ts';+const root = path.resolve(import.meta.dirname, '..');const desktopHtml = readFileSync(path.resolve(root, 'dist/desktop/index.html'), 'utf8');@@ -64,10 +66,13 @@ export const authHtmlTemplate = ${JSON.stringify(authHtml)};console.log('Skipped authHtmlTemplate.ts (no dist/auth build)');}-const workbenchHtmlPath = path.resolve(root, 'dist/workbench/index.workbench.html');+const resolvedWorkbenchHtmlPath =+ process.env.WORKBENCH_REQUIRED === '1'+ ? requireWorkbenchHtmlPath(root)+ : resolveWorkbenchHtmlPath(root);-if (existsSync(workbenchHtmlPath)) {- const workbenchHtml = readFileSync(workbenchHtmlPath, 'utf8');+if (resolvedWorkbenchHtmlPath) {+ const workbenchHtml = readFileSync(resolvedWorkbenchHtmlPath, 'utf8');const workbenchOutput = `// Auto-generated by scripts/generateSpaTemplates.mts after vite build// Do not edit manuallydiff --git a/scripts/spaHtmlPaths.test.ts b/scripts/spaHtmlPaths.test.tsnew file mode 100644index 00000000000..d79718395e1--- /dev/null+++ b/scripts/spaHtmlPaths.test.ts@@ -0,0 +1,54 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it } from 'vitest';++import { requireWorkbenchHtmlPath, resolveWorkbenchHtmlPath } from './spaHtmlPaths';++const testRoots: string[] = [];++afterEach(() => {+ for (const root of testRoots.splice(0)) rmSync(root, { force: true, recursive: true });+});++describe('resolveWorkbenchHtmlPath', () => {+ it('prefers dist/workbench/index.workbench.html when both files exist', () => {+ const root = mkdtempSync(path.join(tmpdir(), 'spa-html-workbench-'));+ testRoots.push(root);++ mkdirSync(path.join(root, 'dist/workbench'), { recursive: true });+ writeFileSync(path.join(root, 'dist/workbench/index.workbench.html'), 'preferred');+ writeFileSync(path.join(root, 'dist/workbench/index.html'), 'fallback');++ expect(resolveWorkbenchHtmlPath(root)).toBe(+ path.resolve(root, 'dist/workbench/index.workbench.html'),+ );+ });++ it('falls back to dist/workbench/index.html', () => {+ const root = mkdtempSync(path.join(tmpdir(), 'spa-html-workbench-fallback-'));+ testRoots.push(root);++ mkdirSync(path.join(root, 'dist/workbench'), { recursive: true });+ writeFileSync(path.join(root, 'dist/workbench/index.html'), 'fallback');++ expect(resolveWorkbenchHtmlPath(root)).toBe(path.resolve(root, 'dist/workbench/index.html'));+ });++ it('returns undefined when the Workbench HTML is missing', () => {+ const root = mkdtempSync(path.join(tmpdir(), 'spa-html-workbench-missing-'));+ testRoots.push(root);++ expect(resolveWorkbenchHtmlPath(root)).toBeUndefined();+ });+});++describe('requireWorkbenchHtmlPath', () => {+ it('throws when the Workbench HTML is missing', () => {+ const root = mkdtempSync(path.join(tmpdir(), 'spa-html-workbench-required-'));+ testRoots.push(root);++ expect(() => requireWorkbenchHtmlPath(root)).toThrow(/Workbench SPA build is required/);+ });+});diff --git a/scripts/spaHtmlPaths.ts b/scripts/spaHtmlPaths.tsnew file mode 100644index 00000000000..a3ab44c035a--- /dev/null+++ b/scripts/spaHtmlPaths.ts@@ -0,0 +1,21 @@+import { existsSync } from 'node:fs';+import path from 'node:path';++export const resolveWorkbenchHtmlPath = (root: string) => {+ const preferred = path.resolve(root, 'dist/workbench/index.workbench.html');+ if (existsSync(preferred)) return preferred;++ const fallback = path.resolve(root, 'dist/workbench/index.html');+ if (existsSync(fallback)) return fallback;++ return undefined;+};++export const requireWorkbenchHtmlPath = (root: string) => {+ const resolved = resolveWorkbenchHtmlPath(root);+ if (resolved) return resolved;++ throw new Error(+ 'Workbench SPA build is required: missing dist/workbench/index.workbench.html and dist/workbench/index.html',+ );+};diff --git a/src/features/AgentDocumentReader/index.tsx b/src/features/AgentDocumentReader/index.tsxindex ecef41cdf38..f2faf6937ee 100644--- a/src/features/AgentDocumentReader/index.tsx+++ b/src/features/AgentDocumentReader/index.tsx@@ -11,7 +11,7 @@ import { memo } from 'react';import { useTranslation } from 'react-i18next';import useSWR from 'swr';-import WorkbenchLoading from '@/features/WorkbenchShell/WorkbenchLoading';+import ContentLoading from '@/components/Loading/ContentLoading';import { agentDocumentService, agentDocumentSWRKeys } from '@/services/agentDocument';const styles = createStaticStyles(({ css }) => ({@@ -70,7 +70,7 @@ const AgentDocumentReader = memo<AgentDocumentReaderProps>(({ agentId, documentI<div className={styles.body}>{!error && isLoading ? (<Center height={'100%'}>- <WorkbenchLoading />+ <ContentLoading /></Center>) : error ? (<Center gap={16} height={'100%'} padding={24}>diff --git a/src/features/AudioPlayer/index.tsx b/src/features/AudioPlayer/index.tsxindex 255c6a364b3..3f9ae771910 100644--- a/src/features/AudioPlayer/index.tsx+++ b/src/features/AudioPlayer/index.tsx@@ -6,7 +6,7 @@ import { DownloadIcon, PauseIcon, PlayIcon, RotateCcwIcon, XIcon } from 'lucide-import { memo, type MouseEvent, useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { useChatStore } from '@/store/chat';+import type { VoiceMessageUploadState } from '@/store/chat/slices/voiceMessage/initialState';import { useAudioElementSource } from './useAudioElementSource';import { useWaveform } from './useWaveform';@@ -225,18 +225,24 @@ interface AudioPlayerProps {* surfaces render the player as a block, not an inline attachment.*/fullWidth?: boolean;- messageId?: string;+ onCancelUpload?: () => void;+ onRetryUpload?: () => void;+ uploadState?: VoiceMessageUploadState;url: string;}const AudioPlayer = memo<AudioPlayerProps>(- ({ url, alt, downloadFileName, durationMs, fullWidth, messageId }) => {+ ({+ url,+ alt,+ downloadFileName,+ durationMs,+ fullWidth,+ onCancelUpload,+ onRetryUpload,+ uploadState,+ }) => {const { t } = useTranslation('chat');- const [uploadState, cancelVoiceMessage, retryVoiceMessage] = useChatStore((s) => [- messageId ? s.voiceMessageUploadMap[messageId] : undefined,- s.cancelVoiceMessage,- s.retryVoiceMessage,- ]);const audioRef = useRef<HTMLAudioElement>(null);const [isPlaying, setIsPlaying] = useState(false);const [currentTime, setCurrentTime] = useState(0);@@ -375,7 +381,7 @@ const AudioPlayer = memo<AudioPlayerProps>(<Icon icon={DownloadIcon} size={15} /></button>)}- {uploadState && messageId && (+ {uploadState && (<div className={styles.actionGroup}>{isFailed && (<button@@ -383,7 +389,7 @@ const AudioPlayer = memo<AudioPlayerProps>(className={styles.miniButton}title={t('voiceMessage.retry')}type="button"- onClick={() => retryVoiceMessage(messageId)}+ onClick={() => onRetryUpload?.()}><Icon icon={RotateCcwIcon} size={14} /></button>@@ -394,7 +400,7 @@ const AudioPlayer = memo<AudioPlayerProps>(className={styles.miniButton}title={t(isFailed ? 'voiceMessage.delete' : 'voiceMessage.cancelUpload')}type="button"- onClick={() => void cancelVoiceMessage(messageId)}+ onClick={() => onCancelUpload?.()}><Icon icon={XIcon} size={14} /></button>diff --git a/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityLink.tsx b/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityLink.tsxindex ce9e73b1a3c..3859c196cff 100644--- a/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityLink.tsx+++ b/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityLink.tsx@@ -103,10 +103,12 @@ export const InternalEntityLink = memo<InternalEntityLinkProps>(({ href, label,event.preventDefault();if (- (reference.type === 'acceptance' || reference.type === 'document') &&+ (reference.type === 'acceptance' ||+ reference.type === 'document' ||+ reference.type === 'verify') &&shouldHardNavigateToWorkbench(reference.pathname)) {- navigate(reference.pathname, { escape: true });+ window.location.assign(reference.pathname);return;}diff --git a/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx b/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsxindex 247201c7b18..4bfe458455b 100644--- a/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx+++ b/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx@@ -93,6 +93,7 @@ afterEach(() => {mockShowIcon = true;mockIsDesktop = false;mockEnableInAppBrowser = false;+ vi.restoreAllMocks();});beforeEach(() => {@@ -171,7 +172,9 @@ describe('Link Render — message link icon toggle', () => {});describe('Link Render — internal entities', () => {- it('opens acceptance links in the conversation portal, never a full-page navigation', () => {+ it('hard-navigates acceptance pages into the Workbench runtime', () => {+ const assign = vi.spyOn(window.location, 'assign').mockImplementation(() => undefined);+const { getByRole } = renderLink({linkHref: '/acceptance/acceptance-1',linkKind: 'generic',@@ -180,8 +183,9 @@ describe('Link Render — internal entities', () => {fireEvent.click(getByRole('link', { name: 'Acceptance' }));- expect(mockOpenAcceptance).toHaveBeenCalledWith('acceptance-1');+ expect(assign).toHaveBeenCalledWith('/acceptance/acceptance-1');expect(mockNavigate).not.toHaveBeenCalled();+ expect(mockOpenAcceptance).not.toHaveBeenCalled();});it('opens official document links in the conversation portal', () => {@@ -220,6 +224,22 @@ describe('Link Render — internal entities', () => {expect(mockOpenAgentDetail).toHaveBeenCalledWith('agt_1');});+ it('hard-navigates personal verify pages into the Workbench runtime', () => {+ const assign = vi.spyOn(window.location, 'assign').mockImplementation(() => undefined);++ const { getByRole } = renderLink({+ linkHref: '/verify/run-1',+ linkKind: 'generic',+ linkLabel: 'Verify report',+ });++ fireEvent.click(getByRole('link', { name: 'Verify report' }));++ expect(assign).toHaveBeenCalledWith('/verify/run-1');+ expect(mockNavigate).not.toHaveBeenCalled();+ expect(mockOpenVerifyReport).not.toHaveBeenCalled();+ });+it('opens a verify link for the active workspace in the report portal', () => {const { getByRole } = renderLink({linkHref: '/lobe-team/verify/run-1',diff --git a/src/features/Conversation/Messages/User/components/AudioFileListViewer.tsx b/src/features/Conversation/Messages/User/components/AudioFileListViewer.tsxindex b5f0cadd4ad..447260898db 100644--- a/src/features/Conversation/Messages/User/components/AudioFileListViewer.tsx+++ b/src/features/Conversation/Messages/User/components/AudioFileListViewer.tsx@@ -2,6 +2,7 @@ import { Flexbox } from '@lobehub/ui';import { memo } from 'react';import AudioPlayer from '@/features/AudioPlayer';+import { useChatStore } from '@/store/chat';import { type ChatAudioItem } from '@/types/index';interface AudioFileListViewerProps {@@ -10,6 +11,12 @@ interface AudioFileListViewerProps {}const AudioFileListViewer = memo<AudioFileListViewerProps>(({ items, messageId }) => {+ const [uploadState, cancelVoiceMessage, retryVoiceMessage] = useChatStore((s) => [+ s.voiceMessageUploadMap[messageId],+ s.cancelVoiceMessage,+ s.retryVoiceMessage,+ ]);+return (<Flexbox gap={8}>{items.map((item) => (@@ -17,8 +24,10 @@ const AudioFileListViewer = memo<AudioFileListViewerProps>(({ items, messageId }alt={item.alt}durationMs={item.durationMs}key={item.id}- messageId={messageId}+ uploadState={uploadState}url={item.url}+ onCancelUpload={() => void cancelVoiceMessage(messageId)}+ onRetryUpload={() => retryVoiceMessage(messageId)}/>))}</Flexbox>diff --git a/src/features/Portal/Acceptance/Body.test.tsx b/src/features/Portal/Acceptance/Body.test.tsxindex dbe719b7394..92d0f86a9d7 100644--- a/src/features/Portal/Acceptance/Body.test.tsx+++ b/src/features/Portal/Acceptance/Body.test.tsx@@ -37,8 +37,16 @@ vi.mock('@/features/Verify', () => ({mocks.captured.onDraftToComposer = props.onDraftToComposer;return null;},+ OriginConversationProvider: ({ children }: { children?: React.ReactNode }) => children,}));+vi.mock('@/store/task', () => ({+ useTaskStore: (selector: (s: unknown) => unknown) =>+ selector({ closeTopicDrawer: () => {}, openTopicDrawer: () => {} }),+}));++vi.mock('./TopicPanel', () => ({ default: () => null }));+describe('Portal Acceptance Body — draftToComposer via the global bus', () => {beforeEach(() => {useComposerDraftBus.setState({ attached: false, draft: null });diff --git a/src/features/Portal/Acceptance/Body.tsx b/src/features/Portal/Acceptance/Body.tsxindex 57649994b06..c2e04798edd 100644--- a/src/features/Portal/Acceptance/Body.tsx+++ b/src/features/Portal/Acceptance/Body.tsx@@ -1,19 +1,37 @@-import { memo } from 'react';+import { memo, useMemo } from 'react';import { draftToMainComposer } from '@/features/Conversation/composerDraftBus';-import { AcceptanceViewer } from '@/features/Verify';+import {+ AcceptanceViewer,+ OriginConversationProvider,+ type OriginConversationSlot,+} from '@/features/Verify';import { useChatStore } from '@/store/chat';import { chatPortalSelectors } from '@/store/chat/selectors';+import { useTaskStore } from '@/store/task';++import TopicPanel from './TopicPanel';const Body = memo(() => {const acceptanceId = useChatStore(chatPortalSelectors.acceptancePortalId);+ const openTopicDrawer = useTaskStore((s) => s.openTopicDrawer);+ const closeTopicDrawer = useTaskStore((s) => s.closeTopicDrawer);++ const originConversation = useMemo<OriginConversationSlot>(+ () => ({ TopicPanel, closeTopicDrawer, openTopicDrawer }),+ [closeTopicDrawer, openTopicDrawer],+ );// The portal pane is a layout SIBLING of the conversation column, not a// descendant of its ConversationProvider — reading useConversationStore here// throws ("no zustand provider as an ancestor") and blanks the page. Drafts// go through the global composerDraftBus; ComposerDraftReceiver applies them// inside the provider (setDocument + inputMessage sync + focus).- return <AcceptanceViewer acceptanceId={acceptanceId} onDraftToComposer={draftToMainComposer} />;+ return (+ <OriginConversationProvider value={originConversation}>+ <AcceptanceViewer acceptanceId={acceptanceId} onDraftToComposer={draftToMainComposer} />+ </OriginConversationProvider>+ );});export default Body;diff --git a/src/features/Verify/Acceptance/TopicPanel.test.ts b/src/features/Portal/Acceptance/TopicPanel.test.tssimilarity index 100%rename from src/features/Verify/Acceptance/TopicPanel.test.tsrename to src/features/Portal/Acceptance/TopicPanel.test.tsdiff --git a/src/features/Portal/Acceptance/TopicPanel.tsx b/src/features/Portal/Acceptance/TopicPanel.tsxnew file mode 100644index 00000000000..b23702dc34d--- /dev/null+++ b/src/features/Portal/Acceptance/TopicPanel.tsx@@ -0,0 +1,63 @@+'use client';++import { ActionIcon, Flexbox, Icon, Text } from '@lobehub/ui';+import { cssVar } from 'antd-style';+import { ArrowLeft, MessagesSquare, PanelRightClose } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { TopicChatDrawerBody } from '@/features/AgentTasks/AgentTaskDetail/TopicChatDrawer';+import type { OriginTopicPanelProps } from '@/features/Verify';++/**+ * The origin conversation rendered in the acceptance workspace's existing+ * right rail. It deliberately reuses the drawer's conversation body without+ * mounting the floating drawer chrome.+ */+const TopicPanel = memo<OriginTopicPanelProps>(+ ({ agentId, onBack, onCollapse, title, topicId }) => {+ const { t } = useTranslation('verify');++ return (+ <Flexbox height={'100%'} style={{ minHeight: 0, overflow: 'hidden' }}>+ <Flexbox+ horizontal+ align={'center'}+ gap={8}+ paddingBlock={12}+ paddingInline={12}+ style={{ borderBlockEnd: `1px solid ${cssVar.colorBorderSecondary}`, flexShrink: 0 }}+ >+ <ActionIcon+ icon={ArrowLeft}+ size={'small'}+ title={t('acceptance.origin.backToRuns')}+ onClick={onBack}+ />+ <Icon color={cssVar.colorTextSecondary} icon={MessagesSquare} size={16} />+ <Text ellipsis strong style={{ flex: 1, minWidth: 0, fontSize: 13 }}>+ {title}+ </Text>+ <ActionIcon+ icon={PanelRightClose}+ size={'small'}+ title={t('acceptance.ledger.collapse')}+ onClick={onCollapse}+ />+ </Flexbox>+ <Flexbox flex={1} style={{ minHeight: 0, overflow: 'hidden' }}>+ <TopicChatDrawerBody+ defaultInputExpanded+ disableInputCollapse+ agentId={agentId}+ topicId={topicId}+ />+ </Flexbox>+ </Flexbox>+ );+ },+);++TopicPanel.displayName = 'TopicPanel';++export default TopicPanel;diff --git a/src/features/Verify/Acceptance/CheckList.tsx b/src/features/Verify/Acceptance/CheckList.tsxindex 5d1ca8d27d7..7c8f1ee01a2 100644--- a/src/features/Verify/Acceptance/CheckList.tsx+++ b/src/features/Verify/Acceptance/CheckList.tsx@@ -48,6 +48,7 @@ import { Fragment, memo, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import AudioPlayer from '@/features/AudioPlayer';+import { useIsHydrated } from '@/hooks/useIsHydrated';import type { AcceptanceBundle } from '@/services/verify';import {@@ -609,12 +610,13 @@ const EvidenceList = memo<{*/const AcceptedNote = memo<{ review: AcceptanceCheckReviewEntry }>(({ review }) => {const { t } = useTranslation('verify');+ const hydrated = useIsHydrated();return (<Flexbox horizontal align={'center'} gap={6}><Icon color={cssVar.colorTextQuaternary} icon={BadgeCheck} size={13} /><Text fontSize={12} type={'secondary'}>{t('acceptance.review.acceptedNote', {- time: dayjs(review.createdAt).format('MM-DD HH:mm'),+ time: hydrated ? dayjs(review.createdAt).format('MM-DD HH:mm') : '',})}</Text></Flexbox>@@ -623,12 +625,13 @@ const AcceptedNote = memo<{ review: AcceptanceCheckReviewEntry }>(({ review }) =const IgnoredNote = memo<{ review: AcceptanceCheckReviewEntry }>(({ review }) => {const { t } = useTranslation('verify');+ const hydrated = useIsHydrated();return (<Flexbox horizontal align={'center'} gap={6}><Icon color={cssVar.colorTextQuaternary} icon={Ban} size={13} /><Text fontSize={12} type={'secondary'}>{t('acceptance.review.ignoredNote', {- time: dayjs(review.createdAt).format('MM-DD HH:mm'),+ time: hydrated ? dayjs(review.createdAt).format('MM-DD HH:mm') : '',})}</Text></Flexbox>@@ -645,6 +648,7 @@ const FeedbackCard = memo<{review: AcceptanceCheckReviewEntry;}>(({ evidenceById, review }) => {const { t } = useTranslation('verify');+ const hydrated = useIsHydrated();if (review.action === 'accept') return <AcceptedNote review={review} />;if (review.action === 'ignore') return <IgnoredNote review={review} />;@@ -666,7 +670,7 @@ const FeedbackCard = memo<{{t('acceptance.review.feedbackLabel')}</Text><Text fontSize={12} type={'secondary'}>- {dayjs(review.createdAt).format('MM-DD HH:mm')}+ {hydrated ? dayjs(review.createdAt).format('MM-DD HH:mm') : null}</Text></Flexbox>{review.comment && <Text style={{ fontSize: 12 }}>{review.comment}</Text>}@@ -1731,6 +1735,7 @@ const CheckList = memo<CheckListProps>(round,}) => {const { t } = useTranslation('verify');+ const hydrated = useIsHydrated();const [acceptingGroup, setAcceptingGroup] = useState<string | null>(null);const visible = (check: AcceptanceCheck) =>@@ -2031,7 +2036,7 @@ const CheckList = memo<CheckListProps>({t('acceptance.group.feedbackLabel')}</Text><Text fontSize={12} type={'secondary'}>- {dayjs(entry.createdAt).format('MM-DD HH:mm')}+ {hydrated ? dayjs(entry.createdAt).format('MM-DD HH:mm') : null}</Text></Flexbox><Text style={{ fontSize: 12 }}>{entry.comment}</Text>diff --git a/src/features/Verify/Acceptance/LedgerPanel.tsx b/src/features/Verify/Acceptance/LedgerPanel.tsxindex e7edf3de1a5..e42166f7da9 100644--- a/src/features/Verify/Acceptance/LedgerPanel.tsx+++ b/src/features/Verify/Acceptance/LedgerPanel.tsx@@ -17,6 +17,7 @@ import {import { memo } from 'react';import { useTranslation } from 'react-i18next';+import { useIsHydrated } from '@/hooks/useIsHydrated';import type { AcceptanceBundle } from '@/services/verify';export type AcceptanceRound = AcceptanceBundle['rounds'][number];@@ -110,6 +111,7 @@ interface LedgerPanelProps {const LedgerPanel = memo<LedgerPanelProps>(({ hideCollapse, highlight, onCollapse, onOpenReport, reviewByRound, rounds }) => {const { t } = useTranslation('verify');+ const hydrated = useIsHydrated();const latestIndex = rounds.at(-1)?.run.roundIndex;return (@@ -215,7 +217,7 @@ const LedgerPanel = memo<LedgerPanelProps>(</Flexbox><Flexbox flex={1} /><Text fontSize={12} type={'secondary'}>- {dayjs(round.run.createdAt).format('MM-DD HH:mm')}+ {hydrated ? dayjs(round.run.createdAt).format('MM-DD HH:mm') : null}</Text>{openable && (<Icondiff --git a/src/features/Verify/Acceptance/TopicPanel.tsx b/src/features/Verify/Acceptance/TopicPanel.tsxdeleted file mode 100644index e4eeb466952..00000000000--- a/src/features/Verify/Acceptance/TopicPanel.tsx+++ /dev/null@@ -1,68 +0,0 @@-'use client';--import { ActionIcon, Flexbox, Icon, Text } from '@lobehub/ui';-import { cssVar } from 'antd-style';-import { ArrowLeft, MessagesSquare, PanelRightClose } from 'lucide-react';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import { TopicChatDrawerBody } from '@/features/AgentTasks/AgentTaskDetail/TopicChatDrawer';--interface TopicPanelProps {- agentId: string;- onBack: () => void;- onCollapse: () => void;- title: string;- topicId: string;-}--/**- * The origin conversation rendered in the acceptance workspace's existing- * right rail. It deliberately reuses the drawer's conversation body without- * mounting the floating drawer chrome.- */-const TopicPanel = memo<TopicPanelProps>(({ agentId, onBack, onCollapse, title, topicId }) => {- const { t } = useTranslation('verify');-- return (- <Flexbox height={'100%'} style={{ minHeight: 0, overflow: 'hidden' }}>- <Flexbox- horizontal- align={'center'}- gap={8}- paddingBlock={12}- paddingInline={12}- style={{ borderBlockEnd: `1px solid ${cssVar.colorBorderSecondary}`, flexShrink: 0 }}- >- <ActionIcon- icon={ArrowLeft}- size={'small'}- title={t('acceptance.origin.backToRuns')}- onClick={onBack}- />- <Icon color={cssVar.colorTextSecondary} icon={MessagesSquare} size={16} />- <Text ellipsis strong style={{ flex: 1, minWidth: 0, fontSize: 13 }}>- {title}- </Text>- <ActionIcon- icon={PanelRightClose}- size={'small'}- title={t('acceptance.ledger.collapse')}- onClick={onCollapse}- />- </Flexbox>- <Flexbox flex={1} style={{ minHeight: 0, overflow: 'hidden' }}>- <TopicChatDrawerBody- defaultInputExpanded- disableInputCollapse- agentId={agentId}- topicId={topicId}- />- </Flexbox>- </Flexbox>- );-});--TopicPanel.displayName = 'TopicPanel';--export default TopicPanel;diff --git a/src/features/Verify/Acceptance/Workspace/AcceptanceListPanel.tsx b/src/features/Verify/Acceptance/Workspace/AcceptanceListPanel.tsxindex 8394a463cdc..eaec80617df 100644--- a/src/features/Verify/Acceptance/Workspace/AcceptanceListPanel.tsx+++ b/src/features/Verify/Acceptance/Workspace/AcceptanceListPanel.tsx@@ -15,18 +15,11 @@ import type { DropdownItem } from '@lobehub/ui/base-ui';import { DropdownMenu } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';import isEqual from 'fast-deep-equal';-import {- ArrowLeft,- Check,- ListFilter,- PanelLeftClose,- ScrollText,- Search,- TriangleAlert,-} from 'lucide-react';+import { Check, ListFilter, PanelLeftClose, ScrollText, Search, TriangleAlert } from 'lucide-react';+import type { ReactNode } from 'react';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { useNavigate, useParams } from 'react-router';+import { useParams } from 'react-router';import { SkeletonList } from '@/features/NavPanel/components/SkeletonList';import { useLocalStorageState } from '@/hooks/useLocalStorageState';@@ -35,7 +28,6 @@ import { systemStatusSelectors } from '@/store/global/selectors';import { useAcceptanceList } from '../../hooks';import type { ReportPanelExpand } from '../../Workspace/useReportPanelExpand';-import { acceptanceHomePath } from '../routes';import {type AcceptanceListFilter,DEFAULT_ACCEPTANCE_LIST_FILTER,@@ -62,12 +54,25 @@ const styles = createStaticStyles(({ css }) => ({padding-block: 14px 6px;padding-inline: 12px;`,+ headWithBrand: css`+ flex: none;+ padding-block: 0 6px;+ padding-inline: 12px;+ `,titleRow: css`display: flex;align-items: center;justify-content: space-between;padding-inline: 4px;`,+ titleRowWithBrand: css`+ display: flex;+ align-items: center;+ justify-content: space-between;++ min-height: 48px;+ padding-inline: 4px;+ `,collapseBtn: css`cursor: pointer;@@ -187,178 +192,178 @@ const styles = createStaticStyles(({ css }) => ({`,}));+interface AcceptanceListPanelProps extends ReportPanelExpand {+ headerLeading?: ReactNode;+}+/*** Master list of the caller's acceptance aggregates — the acceptance twin of* the verify workspace's ReportListPanel, sharing its visual language and the* same persisted panel-width preference so the two surfaces read as one family.*/-const AcceptanceListPanel = memo<ReportPanelExpand>(({ expand, isNarrow, setExpand }) => {- const { t } = useTranslation(['verify', 'common']);- const navigate = useNavigate();- const { acceptanceId } = useParams<{ acceptanceId: string }>();-- const { data, error, isLoading, mutate } = useAcceptanceList(true);-- // Client-side filter: the list endpoint returns the caller's full recent set- // (bounded, no pagination), so filtering the loaded rows IS filtering the set.- const [query, setQuery] = useState('');- const [storedFilter, setStoredFilter] = useLocalStorageState<AcceptanceListFilter>(- ACCEPTANCE_LIST_FILTER_STORAGE_KEY,- DEFAULT_ACCEPTANCE_LIST_FILTER,- );- const filter = normalizeAcceptanceListFilter(storedFilter);- const filtered = filterAcceptanceList(data ?? [], filter, query);- const trimmedQuery = query.trim();-- const filterItems: DropdownItem[] = (- [- ['active', t('acceptance.workspace.filters.active')],- ['all', t('acceptance.workspace.filters.all')],- ['completed', t('acceptance.workspace.filters.completed')],- ] as const- ).map(([key, label]) => ({- icon: <Icon icon={Check} style={{ opacity: filter === key ? 1 : 0 }} />,- key,- label,- onClick: () => setStoredFilter(key),- }));-- const [panelWidth, updateSystemStatus] = useGlobalStore((s) => [- systemStatusSelectors.verifyReportPanelWidth(s),- s.updateSystemStatus,- ]);-- const handleSizeChange: DraggablePanelProps['onSizeChange'] = (_, size) => {- if (!size) return;- const w = typeof size.width === 'string' ? Number.parseInt(size.width) : size.width;- if (!w || isEqual(w, panelWidth)) return;- updateSystemStatus({ verifyReportPanelWidth: w });- };-- return (- <DraggablePanel- className={styles.panel}- defaultSize={{ width: panelWidth }}- expand={expand}- maxWidth={PANEL_MAX}- minWidth={PANEL_MIN}- mode={isNarrow ? 'float' : 'fixed'}- placement={'left'}- size={{ height: '100%', width: panelWidth }}- onExpandChange={setExpand}- onSizeChange={handleSizeChange}- >- <DraggablePanelContainer style={{ flex: 'none', height: '100%', minWidth: PANEL_MIN }}>- <div className={styles.head}>- <div className={styles.titleRow}>- <Flexbox horizontal align={'center'} gap={4}>- <ActionIcon- icon={ArrowLeft}- size={'small'}- title={t('back', { ns: 'common' })}- onClick={() => navigate(acceptanceHomePath())}- />- <Text strong style={{ fontSize: 15 }}>- {t('acceptance.workspace.title')}- </Text>- </Flexbox>- <button- aria-label={t('workspace.collapse')}- className={styles.collapseBtn}- title={t('workspace.collapse')}- type={'button'}- onClick={() => setExpand(false)}- >- <Icon icon={PanelLeftClose} size={16} />- </button>- </div>- <div className={styles.searchRow}>- <label className={styles.search}>- <Icon icon={Search} size={13} />- <input- placeholder={t('workspace.search')}- type={'search'}- value={query}- onChange={(e) => setQuery(e.target.value)}- />- </label>- <DropdownMenu items={filterItems} placement={'bottomRight'}>- <ActionIcon- active={filter !== 'all'}- className={styles.filterButton}- icon={ListFilter}- size={'small'}- title={t('acceptance.workspace.filters.title')}- />- </DropdownMenu>- </div>- </div>-- <Flexbox flex={1} style={{ minHeight: 0, overflowX: 'hidden', overflowY: 'auto' }}>- {error ? (- // A failed fetch must read as an error with a retry — never as an- // empty "no acceptances" page.- <Center className={styles.emptyState} gap={12}>- <Empty- description={t('workspace.loadError')}- icon={TriangleAlert}- title={t('workspace.loadErrorTitle')}- />- <button className={styles.retryBtn} type={'button'} onClick={() => void mutate()}>- {t('workspace.retry')}+const AcceptanceListPanel = memo<AcceptanceListPanelProps>(+ ({ expand, headerLeading, isNarrow, setExpand }) => {+ const { t } = useTranslation('verify');+ const { acceptanceId } = useParams<{ acceptanceId: string }>();++ const { data, error, isLoading, mutate } = useAcceptanceList(true);++ // Client-side filter: the list endpoint returns the caller's full recent set+ // (bounded, no pagination), so filtering the loaded rows IS filtering the set.+ const [query, setQuery] = useState('');+ const [storedFilter, setStoredFilter] = useLocalStorageState<AcceptanceListFilter>(+ ACCEPTANCE_LIST_FILTER_STORAGE_KEY,+ DEFAULT_ACCEPTANCE_LIST_FILTER,+ );+ const filter = normalizeAcceptanceListFilter(storedFilter);+ const filtered = filterAcceptanceList(data ?? [], filter, query);+ const trimmedQuery = query.trim();++ const filterItems: DropdownItem[] = (+ [+ ['active', t('acceptance.workspace.filters.active')],+ ['all', t('acceptance.workspace.filters.all')],+ ['completed', t('acceptance.workspace.filters.completed')],+ ] as const+ ).map(([key, label]) => ({+ icon: <Icon icon={Check} style={{ opacity: filter === key ? 1 : 0 }} />,+ key,+ label,+ onClick: () => setStoredFilter(key),+ }));++ const [panelWidth, updateSystemStatus] = useGlobalStore((s) => [+ systemStatusSelectors.verifyReportPanelWidth(s),+ s.updateSystemStatus,+ ]);++ const handleSizeChange: DraggablePanelProps['onSizeChange'] = (_, size) => {+ if (!size) return;+ const w = typeof size.width === 'string' ? Number.parseInt(size.width) : size.width;+ if (!w || isEqual(w, panelWidth)) return;+ updateSystemStatus({ verifyReportPanelWidth: w });+ };++ return (+ <DraggablePanel+ className={styles.panel}+ defaultSize={{ width: panelWidth }}+ expand={expand}+ maxWidth={PANEL_MAX}+ minWidth={PANEL_MIN}+ mode={isNarrow ? 'float' : 'fixed'}+ placement={'left'}+ size={{ height: '100%', width: panelWidth }}+ onExpandChange={setExpand}+ onSizeChange={handleSizeChange}+ >+ <DraggablePanelContainer style={{ flex: 'none', height: '100%', minWidth: PANEL_MIN }}>+ <div className={headerLeading ? styles.headWithBrand : styles.head}>+ <div className={headerLeading ? styles.titleRowWithBrand : styles.titleRow}>+ <Flexbox horizontal align={'center'} flex={1} gap={8} style={{ minWidth: 0 }}>+ {headerLeading}+ <Text ellipsis strong style={{ fontSize: 15, minWidth: 0 }}>+ {t('acceptance.workspace.title')}+ </Text>+ </Flexbox>+ <button+ aria-label={t('workspace.collapse')}+ className={styles.collapseBtn}+ title={t('workspace.collapse')}+ type={'button'}+ onClick={() => setExpand(false)}+ >+ <Icon icon={PanelLeftClose} size={16} /></button>- </Center>- ) : isLoading ? (- <SkeletonList rows={6} style={{ paddingBlock: 6, paddingInline: 8 }} />- ) : filtered.length === 0 ? (- trimmedQuery || filter !== 'all' ? (- // A zero-result FILTER must read as "no match for this query",- // never as the first-run empty state.- <div className={styles.searchEmpty}>- <span className={styles.searchEmptyMsg}>- {trimmedQuery- ? t('acceptance.workspace.filters.noSearchResults', { query: trimmedQuery })- : filter === 'all'- ? null- : t(EMPTY_FILTER_KEYS[filter])}- </span>- <button- className={styles.retryBtn}- type={'button'}- onClick={() => {- setQuery('');- setStoredFilter('all');- }}- >- {t('acceptance.workspace.filters.showAll')}- </button>- </div>- ) : (- <Center className={styles.emptyState}>- <Empty- description={t('acceptance.workspace.listEmpty')}- icon={ScrollText}- title={t('acceptance.workspace.listEmptyTitle')}+ </div>+ <div className={styles.searchRow}>+ <label className={styles.search}>+ <Icon icon={Search} size={13} />+ <input+ placeholder={t('workspace.search')}+ type={'search'}+ value={query}+ onChange={(e) => setQuery(e.target.value)}/>- </Center>- )- ) : (- <div className={styles.list}>- {filtered.map((item) => (- <AcceptanceRow- active={item.id === acceptanceId}- item={item}- key={item.id}- onChanged={mutate}+ </label>+ <DropdownMenu items={filterItems} placement={'bottomRight'}>+ <ActionIcon+ active={filter !== 'all'}+ className={styles.filterButton}+ icon={ListFilter}+ size={'small'}+ title={t('acceptance.workspace.filters.title')}/>- ))}+ </DropdownMenu></div>- )}- </Flexbox>- </DraggablePanelContainer>- </DraggablePanel>- );-});+ </div>++ <Flexbox flex={1} style={{ minHeight: 0, overflowX: 'hidden', overflowY: 'auto' }}>+ {error ? (+ // A failed fetch must read as an error with a retry — never as an+ // empty "no acceptances" page.+ <Center className={styles.emptyState} gap={12}>+ <Empty+ description={t('workspace.loadError')}+ icon={TriangleAlert}+ title={t('workspace.loadErrorTitle')}+ />+ <button className={styles.retryBtn} type={'button'} onClick={() => void mutate()}>+ {t('workspace.retry')}+ </button>+ </Center>+ ) : isLoading ? (+ <SkeletonList rows={6} style={{ paddingBlock: 6, paddingInline: 8 }} />+ ) : filtered.length === 0 ? (+ trimmedQuery || filter !== 'all' ? (+ // A zero-result FILTER must read as "no match for this query",+ // never as the first-run empty state.+ <div className={styles.searchEmpty}>+ <span className={styles.searchEmptyMsg}>+ {trimmedQuery+ ? t('acceptance.workspace.filters.noSearchResults', { query: trimmedQuery })+ : filter === 'all'+ ? null+ : t(EMPTY_FILTER_KEYS[filter])}+ </span>+ <button+ className={styles.retryBtn}+ type={'button'}+ onClick={() => {+ setQuery('');+ setStoredFilter('all');+ }}+ >+ {t('acceptance.workspace.filters.showAll')}+ </button>+ </div>+ ) : (+ <Center className={styles.emptyState}>+ <Empty+ description={t('acceptance.workspace.listEmpty')}+ icon={ScrollText}+ title={t('acceptance.workspace.listEmptyTitle')}+ />+ </Center>+ )+ ) : (+ <div className={styles.list}>+ {filtered.map((item) => (+ <AcceptanceRow+ active={item.id === acceptanceId}+ item={item}+ key={item.id}+ onChanged={mutate}+ />+ ))}+ </div>+ )}+ </Flexbox>+ </DraggablePanelContainer>+ </DraggablePanel>+ );+ },+);AcceptanceListPanel.displayName = 'AcceptanceListPanel';diff --git a/src/features/Verify/Acceptance/Workspace/AcceptanceRow.tsx b/src/features/Verify/Acceptance/Workspace/AcceptanceRow.tsxindex 6b30b4e2cd2..d2fff20fb25 100644--- a/src/features/Verify/Acceptance/Workspace/AcceptanceRow.tsx+++ b/src/features/Verify/Acceptance/Workspace/AcceptanceRow.tsx@@ -119,7 +119,7 @@ const AcceptanceRow = memo<{item: AcceptanceListItem;onChanged: () => Promise<unknown> | unknown;}>(({ active, item, onChanged }) => {- const { t } = useTranslation(['verify', 'common']);+ const { t } = useTranslation('verify');const navigate = useNavigate();const [editing, setEditing] = useState(false);const [mutating, setMutating] = useState(false);@@ -148,7 +148,7 @@ const AcceptanceRow = memo<{if (isSavingRef.current) return;const next = draftTitle.trim();if (!next) {- toast.error(t('verify:acceptance.workspace.renameEmpty'));+ toast.error(t('acceptance.workspace.renameEmpty'));setDraftTitle(title);setEditing(false);return;@@ -162,11 +162,11 @@ const AcceptanceRow = memo<{try {await verifyService.renameAcceptance(item.id, next);await refresh();- toast.success(t('verify:acceptance.workspace.renameSuccess'));+ toast.success(t('acceptance.workspace.renameSuccess'));setEditing(false);} catch (error) {console.error('[acceptance:rename]', error);- toast.error(t('verify:acceptance.workspace.renameError'));+ toast.error(t('acceptance.workspace.renameError'));} finally {isSavingRef.current = false;setMutating(false);@@ -178,10 +178,10 @@ const AcceptanceRow = memo<{try {await verifyService.updateAcceptanceStatus(item.id, status);await refresh();- toast.success(t('verify:acceptance.workspace.statusSuccess'));+ toast.success(t('acceptance.workspace.statusSuccess'));} catch (error) {console.error('[acceptance:status]', error);- toast.error(t('verify:acceptance.workspace.statusError'));+ toast.error(t('acceptance.workspace.statusError'));} finally {setMutating(false);}@@ -189,25 +189,25 @@ const AcceptanceRow = memo<{const removeAcceptance = () => {confirmModal({- cancelText: t('common:cancel'),- content: t('verify:acceptance.workspace.deleteConfirmDescription', { title }),+ cancelText: t('actions.cancel'),+ content: t('acceptance.workspace.deleteConfirmDescription', { title }),okButtonProps: { danger: true },- okText: t('common:delete'),+ okText: t('actions.delete'),onOk: async () => {setMutating(true);try {await verifyService.deleteAcceptance(item.id);if (active) navigate('/acceptance', { replace: true });await onChanged();- toast.success(t('verify:acceptance.workspace.deleteSuccess'));+ toast.success(t('acceptance.workspace.deleteSuccess'));} catch (error) {console.error('[acceptance:delete]', error);- toast.error(t('verify:acceptance.workspace.deleteError'));+ toast.error(t('acceptance.workspace.deleteError'));} finally {setMutating(false);}},- title: t('verify:acceptance.workspace.deleteConfirmTitle'),+ title: t('acceptance.workspace.deleteConfirmTitle'),});};@@ -216,7 +216,7 @@ const AcceptanceRow = memo<{return {icon: <Icon icon={CircleCheck} />,key: action,- label: t('verify:acceptance.workspace.actions.markAccepted'),+ label: t('acceptance.workspace.actions.markAccepted'),onClick: () => void changeStatus('accepted'),};}@@ -224,14 +224,14 @@ const AcceptanceRow = memo<{return {icon: <Icon icon={RotateCcw} />,key: action,- label: t('verify:acceptance.workspace.actions.reopen'),+ label: t('acceptance.workspace.actions.reopen'),onClick: () => void changeStatus('delivered'),};}return {icon: <Icon icon={X} />,key: action,- label: t('verify:acceptance.workspace.actions.markClosed'),+ label: t('acceptance.workspace.actions.markClosed'),onClick: () => void changeStatus('closed'),};});@@ -240,7 +240,7 @@ const AcceptanceRow = memo<{{icon: <Icon icon={Pencil} />,key: 'rename',- label: t('verify:acceptance.workspace.actions.rename'),+ label: t('acceptance.workspace.actions.rename'),onClick: startRename,},...(statusItems.length > 0@@ -249,7 +249,7 @@ const AcceptanceRow = memo<{children: statusItems,icon: <Icon icon={CircleDashed} />,key: 'status',- label: t('verify:acceptance.workspace.actions.status'),+ label: t('acceptance.workspace.actions.status'),},{ type: 'divider' as const },]@@ -258,7 +258,7 @@ const AcceptanceRow = memo<{danger: true,icon: <Icon icon={Trash2} />,key: 'delete',- label: t('verify:acceptance.workspace.actions.delete'),+ label: t('acceptance.workspace.actions.delete'),onClick: removeAcceptance,},];@@ -306,7 +306,7 @@ const AcceptanceRow = memo<{<ActionIconicon={MoreHorizontal}size={'small'}- title={t('verify:acceptance.workspace.actions.more')}+ title={t('acceptance.workspace.actions.more')}/></DropdownMenu>}diff --git a/src/features/Verify/Acceptance/index.tsx b/src/features/Verify/Acceptance/index.tsxindex 75914e4860a..ef217f5dfc3 100644--- a/src/features/Verify/Acceptance/index.tsx+++ b/src/features/Verify/Acceptance/index.tsx@@ -48,10 +48,10 @@ import { useTranslation } from 'react-i18next';import { useNavigate, useParams, useSearchParams } from 'react-router';import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';-import AgentProfilePopup from '@/features/AgentProfileCard/AgentProfilePopup';import { openCheckEditModal } from '@/features/Conversation/ChatInput/VerifyTray/EditModal';import { openGoalModal } from '@/features/Conversation/ChatInput/VerifyTray/GoalModal';import NavItem from '@/features/NavPanel/components/NavItem';+import { useIsHydrated } from '@/hooks/useIsHydrated';import { useLocalStorageState } from '@/hooks/useLocalStorageState';import { useSingleton } from '@/hooks/useSingleton';// The workspace-scoped mutate — a bare `import { mutate } from 'swr'` misses@@ -59,7 +59,6 @@ import { useSingleton } from '@/hooks/useSingleton';import { mutate as globalMutate } from '@/libs/swr';import { verifyKeys } from '@/libs/swr/keys';import { verifyService } from '@/services/verify';-import { useTaskStore } from '@/store/task';import { useAcceptanceBundle } from '../hooks';import ReportViewer from '../ReportViewer';@@ -87,9 +86,9 @@ import FeedbackDrawer, { type FeedbackListEntry } from './FeedbackDrawer';import { acceptanceFocusedLayout, acceptanceScrollLayout } from './layout';import LedgerPanel, { type AcceptanceRound } from './LedgerPanel';import { openAcceptModal, openGroupFeedbackModal, openRejectModal } from './modals';+import { useOriginConversation } from './originConversation';import { acceptanceCheckPath, acceptanceOverviewPath } from './routes';import { getAcceptanceStatusActions } from './statusActions';-import TopicPanel from './TopicPanel';import { canViewAcceptanceHistory, resolveAcceptanceHistoryNavigation } from './visibility';const styles = createStaticStyles(({ css }) => ({@@ -158,8 +157,6 @@ const styles = createStaticStyles(({ css }) => ({overflow: hidden;- /* AppTheme's root is a centered flex column — without an explicit width the page- shrinks to content width and the ledger hugs the shrunken edge, not the viewport */width: 100%;height: 100%;@@ -315,9 +312,12 @@ const AcceptancePage = memo<AcceptancePageProps>(const isEmbedded = Boolean(explicitAcceptanceId);const navigate = useNavigate();const { t } = useTranslation('verify');- const { data, error, isLoading, mutate } = useAcceptanceBundle(acceptanceId ?? null);- const openTopicDrawer = useTaskStore((s) => s.openTopicDrawer);- const closeTopicDrawer = useTaskStore((s) => s.closeTopicDrawer);+ const hydrated = useIsHydrated();+ const { data, isLoading, mutate } = useAcceptanceBundle(acceptanceId ?? null);+ const originConversation = useOriginConversation();+ const openTopicDrawer = originConversation?.openTopicDrawer;+ const closeTopicDrawer = originConversation?.closeTopicDrawer;+ const OriginTopicPanel = originConversation?.TopicPanel;// Below `lg` the report body and a 300px+ in-flow ledger cannot share the// viewport — the ledger switches to a float overlay, closed by default (the// same narrow regime the list panel uses).@@ -332,7 +332,7 @@ const AcceptancePage = memo<AcceptancePageProps>(// later task/home surface that also mounts TopicChatDrawer.useEffect(() => () => {- if (!isEmbedded) closeTopicDrawer();+ if (!isEmbedded) closeTopicDrawer?.();},[closeTopicDrawer, isEmbedded],);@@ -429,11 +429,11 @@ const AcceptancePage = memo<AcceptancePageProps>(}const closeTopicPanel = useCallback(() => {setTopicPanelOpen(false);- closeTopicDrawer();+ closeTopicDrawer?.();}, [closeTopicDrawer]);const openTopicPanel = useCallback(() => {- if (!data?.origin?.topic) return;+ if (!openTopicDrawer || !data?.origin?.topic) return;openTopicDrawer(data.origin.topic.id, {agentId: data.origin.agent?.id,title: data.origin.topic.title ?? data.subject.title ?? data.origin.topic.id,@@ -450,6 +450,7 @@ const AcceptancePage = memo<AcceptancePageProps>(*/const openVerifierTrace = useCallback(async (verifierOperationId: string) => {+ if (!openTopicDrawer) return;const resolved = await verifyService.getVerifierThread(verifierOperationId);const topicId = resolved?.topicId;if (!topicId) return;@@ -748,14 +749,14 @@ const AcceptancePage = memo<AcceptancePageProps>([data],);- if (isLoading)+ if (isLoading && !data)return (<Center height={'100%'}><NeuralNetworkLoading size={48} /></Center>);- if (error || !data)+ if (!data)return (<Center height={'100%'}><Empty@@ -1013,9 +1014,10 @@ const AcceptancePage = memo<AcceptancePageProps>(const barTexts = {accepted: {statusText: t('acceptance.banner.accepted', {- time: acceptance.completedAt- ? dayjs(acceptance.completedAt).format('YYYY-MM-DD HH:mm')- : '',+ time:+ hydrated && acceptance.completedAt+ ? dayjs(acceptance.completedAt).format('YYYY-MM-DD HH:mm')+ : '',}),subText: `${countsText} · ${t('acceptance.banner.acceptedHint', { count: rounds.length })}`,},@@ -1268,7 +1270,7 @@ const AcceptancePage = memo<AcceptancePageProps>(<Text fontSize={12} type={'secondary'}>{[countsText,- currentRound+ hydrated && currentRound? t('acceptance.verdict.latestAt', {time: dayjs(currentRound.run.createdAt).format('MM-DD HH:mm'),})@@ -1293,32 +1295,22 @@ const AcceptancePage = memo<AcceptancePageProps>({!isEmbedded && (originAgent || originTopic || scope?.pullRequest?.number) && (<Flexbox horizontal align={'center'} gap={16} wrap={'wrap'}>{originAgent && (- <AgentProfilePopup- agentId={originAgent.id}- trigger={'hover'}- agent={{- avatar: originAgent.avatar ?? undefined,- backgroundColor: originAgent.backgroundColor ?? undefined,- title: originAgent.title ?? undefined,- }}+ <Flexbox+ horizontal+ align={'center'}+ className={styles.scopeChip}+ gap={6}+ style={{ cursor: 'default', fontSize: 14 }}>- <Flexbox- horizontal- align={'center'}- className={styles.scopeChip}- gap={6}- style={{ cursor: 'default', fontSize: 14 }}- >- <Avatar- avatar={originAgent.avatar ?? undefined}- background={originAgent.backgroundColor ?? undefined}- size={18}- />- {originAgent.title ?? t('acceptance.origin.agentFallback')}- </Flexbox>- </AgentProfilePopup>+ <Avatar+ avatar={originAgent.avatar ?? undefined}+ background={originAgent.backgroundColor ?? undefined}+ size={18}+ />+ {originAgent.title ?? t('acceptance.origin.agentFallback')}+ </Flexbox>)}- {originTopic && (+ {originTopic && originConversation && (<ButtonclassName={cx(styles.scopeChip, styles.scopeLink)}icon={MessagesSquare}@@ -1908,7 +1900,7 @@ const AcceptancePage = memo<AcceptancePageProps>(round={roundFilter}onDismissProposal={handleDismissProposal}onGroupFeedback={handleGroupFeedback}- onOpenTrace={openVerifierTrace}+ onOpenTrace={originConversation ? openVerifierTrace : undefined}onReview={handleReview}onRound={historyNavigation}onToggleGroup={handleToggleGroup}@@ -1974,8 +1966,8 @@ const AcceptancePage = memo<AcceptancePageProps>(width={'min(340px, 88vw)'}onClose={() => setLedgerExpand(false)}>- {topicPanelOpen && origin?.agent?.id && origin.topic ? (- <TopicPanel+ {topicPanelOpen && origin?.agent?.id && origin.topic && OriginTopicPanel ? (+ <OriginTopicPanelagentId={origin.agent.id}title={origin.topic.title ?? subject.title ?? origin.topic.id}topicId={origin.topic.id}@@ -2003,8 +1995,8 @@ const AcceptancePage = memo<AcceptancePageProps>(onExpandChange={setLedgerExpand}><Flexbox style={{ height: '100%', minHeight: 0, overflow: 'hidden' }}>- {topicPanelOpen && origin?.agent?.id && origin.topic ? (- <TopicPanel+ {topicPanelOpen && origin?.agent?.id && origin.topic && OriginTopicPanel ? (+ <OriginTopicPanelagentId={origin.agent.id}title={origin.topic.title ?? subject.title ?? origin.topic.id}topicId={origin.topic.id}diff --git a/src/features/Verify/Acceptance/originConversation.tsx b/src/features/Verify/Acceptance/originConversation.tsxnew file mode 100644index 00000000000..8fda93e1332--- /dev/null+++ b/src/features/Verify/Acceptance/originConversation.tsx@@ -0,0 +1,27 @@+'use client';++import { type ComponentType, createContext, use } from 'react';++// Seam that keeps the acceptance viewer free of the conversation universe+// (TopicChatDrawer, task store): hosts that can show the origin conversation+// (the app portal) inject it; hosts that cannot (workbench) leave it null and+// every origin-conversation affordance stays hidden.+export interface OriginTopicPanelProps {+ agentId: string;+ onBack: () => void;+ onCollapse: () => void;+ title: string;+ topicId: string;+}++export interface OriginConversationSlot {+ closeTopicDrawer: () => void;+ openTopicDrawer: (topicId: string, topic?: { agentId?: string; title?: string }) => void;+ TopicPanel: ComponentType<OriginTopicPanelProps>;+}++const OriginConversationContext = createContext<OriginConversationSlot | null>(null);++export const OriginConversationProvider = OriginConversationContext.Provider;++export const useOriginConversation = () => use(OriginConversationContext);diff --git a/src/features/Verify/Workspace/ReportListPanel.tsx b/src/features/Verify/Workspace/ReportListPanel.tsxindex 094bf15c11e..b1313a4ee5f 100644--- a/src/features/Verify/Workspace/ReportListPanel.tsx+++ b/src/features/Verify/Workspace/ReportListPanel.tsx@@ -269,7 +269,7 @@ const ReportListItem = memo<{item: VerifyReportSummary;onReportsChanged: () => Promise<unknown> | unknown;}>(({ active, item, onReportsChanged }) => {- const { t } = useTranslation(['verify', 'common']);+ const { t } = useTranslation('verify');const navigate = useNavigate();const [editing, setEditing] = useState(false);@@ -285,10 +285,10 @@ const ReportListItem = memo<{const total = item.report?.totalChecks ?? planCount;const passed = item.report?.passedChecks ?? 0;const failed = item.report?.failedChecks ?? 0;- const title = item.run.title || t('verify:reports.untitled');+ const title = item.run.title || t('reports.untitled');const time =glyph === 'running'- ? t('verify:list.running')+ ? t('list.running'): relativeTime(item.report?.generatedAt ?? item.run.createdAt);const refreshRelatedReports = async () => {@@ -311,7 +311,7 @@ const ReportListItem = memo<{const nextTitle = draftTitle.trim();if (!nextTitle) {- toast.error(t('verify:workspace.renameEmpty'));+ toast.error(t('workspace.renameEmpty'));setDraftTitle(item.run.title || '');setEditing(false);return;@@ -327,11 +327,11 @@ const ReportListItem = memo<{try {await verifyService.updateRunTitle(item.run.id, nextTitle);await refreshRelatedReports();- toast.success(t('verify:workspace.renameSuccess'));+ toast.success(t('workspace.renameSuccess'));setEditing(false);} catch (error) {console.error('[verify:renameReport]', error);- toast.error(t('verify:workspace.renameError'));+ toast.error(t('workspace.renameError'));} finally {isSavingRef.current = false;setMutating(false);@@ -340,10 +340,10 @@ const ReportListItem = memo<{const deleteReport = () => {confirmModal({- cancelText: t('common:cancel'),- content: t('verify:workspace.deleteConfirmDescription', { title }),+ cancelText: t('actions.cancel'),+ content: t('workspace.deleteConfirmDescription', { title }),okButtonProps: { danger: true },- okText: t('common:delete'),+ okText: t('actions.delete'),onOk: async () => {setMutating(true);try {@@ -353,15 +353,15 @@ const ReportListItem = memo<{onReportsChanged(),mutate(verifyKeys.reportBundle(item.run.id), null, { revalidate: false }),]);- toast.success(t('verify:workspace.deleteSuccess'));+ toast.success(t('workspace.deleteSuccess'));} catch (error) {console.error('[verify:deleteReport]', error);- toast.error(t('verify:workspace.deleteError'));+ toast.error(t('workspace.deleteError'));} finally {setMutating(false);}},- title: t('verify:workspace.deleteConfirmTitle'),+ title: t('workspace.deleteConfirmTitle'),});};@@ -369,14 +369,14 @@ const ReportListItem = memo<{{icon: <Icon icon={Pencil} />,key: 'rename',- label: t('verify:workspace.actions.rename'),+ label: t('workspace.actions.rename'),onClick: startRename,},{danger: true,icon: <Icon icon={Trash2} />,key: 'delete',- label: t('verify:workspace.actions.delete'),+ label: t('workspace.actions.delete'),onClick: deleteReport,},];@@ -418,7 +418,7 @@ const ReportListItem = memo<{{failed > 0 ? (<>{' · '}- <em>{t('verify:list.failedCount', { count: failed })}</em>+ <em>{t('list.failedCount', { count: failed })}</em></>) : null}</span>@@ -440,11 +440,7 @@ const ReportListItem = memo<{placement={'bottomRight'}popupProps={{ style: { minWidth: 140 } }}>- <ActionIcon- icon={MoreHorizontal}- size={'small'}- title={t('verify:workspace.actions.more')}- />+ <ActionIcon icon={MoreHorizontal} size={'small'} title={t('workspace.actions.more')} /></DropdownMenu>}icon={diff --git a/src/features/Verify/Workspace/useReportPanelExpand.test.ts b/src/features/Verify/Workspace/useReportPanelExpand.test.tsindex 9f9ad24fb02..02825b2d9d8 100644--- a/src/features/Verify/Workspace/useReportPanelExpand.test.ts+++ b/src/features/Verify/Workspace/useReportPanelExpand.test.ts@@ -60,6 +60,20 @@ describe('useReportPanelExpand', () => {expect(showPanel()).toBe(true);});+ it('still toggles on a wide viewport when system status is not initialized', () => {+ useGlobalStore.setState({ isStatusInit: false });+ setViewport(true);+ const { result } = renderHook(() => useReportPanelExpand());++ act(() => result.current.setExpand(false));+ expect(result.current.expand).toBe(false);+ expect(showPanel()).toBe(false);++ act(() => result.current.setExpand(true));+ expect(result.current.expand).toBe(true);+ expect(showPanel()).toBe(true);+ });+it('restores the preferred layout when the viewport widens again', () => {setViewport(false);const { rerender, result } = renderHook(() => useReportPanelExpand());diff --git a/src/features/Verify/Workspace/useReportPanelExpand.ts b/src/features/Verify/Workspace/useReportPanelExpand.tsindex 76ad187c120..fd322c1f8ea 100644--- a/src/features/Verify/Workspace/useReportPanelExpand.ts+++ b/src/features/Verify/Workspace/useReportPanelExpand.ts@@ -46,9 +46,19 @@ export const useReportPanelExpand = (): ReportPanelExpand => {// Not memoized on purpose: it closes over `isNarrow`, and a stale closure here// would route a wide-layout toggle into the transient overlay state, silently// dropping the user's preference.+ const isStatusInit = useGlobalStore((s) => s.isStatusInit);const setExpand = (next: boolean) => {- if (isNarrow) setFloatOpen(next);- else updateSystemStatus({ showVerifyReportPanel: next });+ if (isNarrow) {+ setFloatOpen(next);+ return;+ }+ if (isStatusInit) {+ updateSystemStatus({ showVerifyReportPanel: next });+ return;+ }+ useGlobalStore.setState((s) => ({+ status: { ...s.status, showVerifyReportPanel: next },+ }));};return { expand: isNarrow ? floatOpen : showPanel, isNarrow, setExpand };diff --git a/src/features/Verify/index.ts b/src/features/Verify/index.tsindex fc0c9509a8f..580958b9a08 100644--- a/src/features/Verify/index.ts+++ b/src/features/Verify/index.ts@@ -6,6 +6,11 @@ export {groupChecks,shouldGroupChecks,} from './Acceptance/CheckList';+export {+ OriginConversationProvider,+ type OriginConversationSlot,+ type OriginTopicPanelProps,+} from './Acceptance/originConversation';export { default as AcceptanceWorkspace } from './Acceptance/Workspace';export { default as AcceptanceEmptyDetail } from './Acceptance/Workspace/EmptyDetail';export { default as CheckerDock } from './CheckerDock';diff --git a/src/features/Workspace/useWorkspaceAwareNavigate.ts b/src/features/Workspace/useWorkspaceAwareNavigate.tsindex f052827d4c9..e64e99162e5 100644--- a/src/features/Workspace/useWorkspaceAwareNavigate.ts+++ b/src/features/Workspace/useWorkspaceAwareNavigate.ts@@ -4,7 +4,6 @@ import { useCallback } from 'react';import { type NavigateFunction, type NavigateOptions, type To, useNavigate } from 'react-router';import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';-import { shouldHardNavigateToWorkbench } from '@/libs/next/workbenchNavigation';import { buildWorkspaceAwarePath, type WorkspaceAwareNavigateOptions } from './workspaceAwarePath';@@ -44,10 +43,6 @@ export const useWorkspaceAwareNavigate = (): WorkspaceAwareNavigateFunction => {const target = buildWorkspaceAwarePath(to, getActiveWorkspaceSlug(), options);const { escape: _escape, ...rest } = options ?? {};void _escape;- if (shouldHardNavigateToWorkbench(target)) {- window.location.assign(target);- return;- }// Stay a transparent drop-in for `useNavigate`: only forward a second arg// when real react-router options remain, so `navigate(path)` calls don't// turn into `navigate(path, {})`.diff --git a/src/hooks/useIsHydrated.ts b/src/hooks/useIsHydrated.tsnew file mode 100644index 00000000000..60c2e56727f--- /dev/null+++ b/src/hooks/useIsHydrated.ts@@ -0,0 +1,10 @@+import { useSyncExternalStore } from 'react';++const noopSubscribe = () => () => {};+const getSnapshot = () => true;+const getServerSnapshot = () => false;++// False during SSR and the hydration render, true after mount — for+// viewer-timezone-dependent output that must not be part of hydrated HTML.+export const useIsHydrated = () =>+ useSyncExternalStore(noopSubscribe, getSnapshot, getServerSnapshot);diff --git a/src/libs/next/Link.tsx b/src/libs/next/Link.tsxindex 0b0617b98a7..41bb283a964 100644--- a/src/libs/next/Link.tsx+++ b/src/libs/next/Link.tsx@@ -7,7 +7,6 @@ import { type AnchorHTMLAttributes } from 'react';import { Link as RRLink } from 'react-router';import { authSpaRoutes, nextjsOnlyRoutes } from './nextjsOnlyRoutes';-import { shouldHardNavigateToWorkbench } from './workbenchNavigation';export interface LinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> {href: string;@@ -35,7 +34,7 @@ const Link = ({children,...rest}: LinkProps & { ref?: React.RefObject<HTMLAnchorElement | null> }) => {- if (isExternalOrNextOnly(href) || shouldHardNavigateToWorkbench(href)) {+ if (isExternalOrNextOnly(href)) {return (<a href={href} ref={ref} {...rest}>{children}diff --git a/src/libs/next/proxy/define-config.test.ts b/src/libs/next/proxy/define-config.test.tsindex 37db814cbad..693458c5b11 100644--- a/src/libs/next/proxy/define-config.test.ts+++ b/src/libs/next/proxy/define-config.test.ts@@ -53,19 +53,26 @@ describe('defineConfig locale path-traversal hardening', () => {});describe('defineConfig Workbench SPA rewrite', () => {- it('routes Workbench-owned paths only for mobile devices', async () => {+ it('routes verify and acceptance through Workbench for every user agent', async () => {const mobileAcceptance = await run('http://localhost:3010/acceptance/acceptance-1?hl=en-US',MOBILE_USER_AGENT,);const desktopAcceptance = await run('http://localhost:3010/acceptance/acceptance-1?hl=en-US');+ const mobileVerify = await run(+ 'http://localhost:3010/verify/run-1?hl=en-US',+ MOBILE_USER_AGENT,+ );+ const desktopVerify = await run('http://localhost:3010/verify/run-1?hl=en-US');expect(new URL(mobileAcceptance!).pathname).toBe('/spa-workbench/en-US/acceptance/acceptance-1',);- expect(new URL(desktopAcceptance!).pathname).toMatch(- /^\/spa\/[^/]+\/acceptance\/acceptance-1$/,+ expect(new URL(desktopAcceptance!).pathname).toBe(+ '/spa-workbench/en-US/acceptance/acceptance-1',);+ expect(new URL(mobileVerify!).pathname).toBe('/spa-workbench/en-US/verify/run-1');+ expect(new URL(desktopVerify!).pathname).toBe('/spa-workbench/en-US/verify/run-1');});it('keeps the agent documents index in the Main Mobile SPA', async () => {diff --git a/src/libs/next/proxy/define-config.ts b/src/libs/next/proxy/define-config.tsindex 20366a4e1f6..78a4f275ed2 100644--- a/src/libs/next/proxy/define-config.ts+++ b/src/libs/next/proxy/define-config.ts@@ -13,7 +13,7 @@ import { parseBrowserLanguage } from '@/utils/locale';import { DEFAULT_LANG, locales, RouteVariants } from '@/utils/server/routeVariants';import { authSpaRoutes, nextjsOnlyRoutes } from '../nextjsOnlyRoutes';-import { isWorkbenchSpaRoute } from '../workbenchRoutes';+import { isAlwaysWorkbenchSpaRoute, isWorkbenchSpaRoute } from '../workbenchRoutes';import { createRouteMatcher } from './createRouteMatcher';// Create debug logger instances@@ -92,7 +92,7 @@ export function defineConfig() {// 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', '/verify', '/acceptance'];+ const desktopOnlyPaths = ['/share'];const isDesktopOnlyPath = desktopOnlyPaths.some((path) => url.pathname === path || url.pathname.startsWith(`${path}/`),);@@ -146,7 +146,10 @@ export function defineConfig() {return response;}- if (device.type === 'mobile' && isWorkbenchSpaRoute(url.pathname)) {+ if (+ isAlwaysWorkbenchSpaRoute(url.pathname) ||+ (device.type === 'mobile' && isWorkbenchSpaRoute(url.pathname))+ ) {const workbenchPath = `/spa-workbench/${safeLocale}${url.pathname}`;logDefault('Workbench SPA route, rewriting to: %s', workbenchPath);url.pathname = workbenchPath;diff --git a/src/libs/next/workbenchNavigation.test.ts b/src/libs/next/workbenchNavigation.test.tsnew file mode 100644index 00000000000..f5756f78ad6--- /dev/null+++ b/src/libs/next/workbenchNavigation.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from 'vitest';++import { shouldHardNavigateToWorkbench } from './workbenchNavigation';++describe('shouldHardNavigateToWorkbench', () => {+ it.each(['/verify', '/verify/run-1', '/acceptance', '/acceptance/a-1?r=2'])(+ 'hard-navigates verify and acceptance out of the main web SPA: %s',+ (pathname) => {+ expect(shouldHardNavigateToWorkbench(pathname)).toBe(true);+ },+ );++ it.each(['/verify-im', '/agent/agt_1/docs/doc_1', '/settings/profile'])(+ 'keeps other main-SPA destinations in-router: %s',+ (pathname) => {+ expect(shouldHardNavigateToWorkbench(pathname)).toBe(false);+ },+ );+});diff --git a/src/libs/next/workbenchNavigation.ts b/src/libs/next/workbenchNavigation.tsindex cdcf4d8e126..5c9b6faf7e8 100644--- a/src/libs/next/workbenchNavigation.ts+++ b/src/libs/next/workbenchNavigation.ts@@ -1,11 +1,8 @@-import { isWorkbenchSpaRoute } from './workbenchRoutes';+import { isAlwaysWorkbenchSpaRoute, isWorkbenchSpaRoute } from './workbenchRoutes';-/**- * Main Mobile SPA routes that cross into the independent Workbench runtime must- * perform a document navigation. Inside Workbench, React Router remains local.- */-export const shouldHardNavigateToWorkbench = (pathname: string): boolean =>- typeof __MOBILE__ !== 'undefined' &&- __MOBILE__ &&- (typeof __WORKBENCH__ === 'undefined' || !__WORKBENCH__) &&- isWorkbenchSpaRoute(pathname);+export const shouldHardNavigateToWorkbench = (pathname: string): boolean => {+ if (typeof __ELECTRON__ !== 'undefined' && __ELECTRON__) return false;+ if (isAlwaysWorkbenchSpaRoute(pathname)) return true;++ return typeof __MOBILE__ !== 'undefined' && __MOBILE__ && isWorkbenchSpaRoute(pathname);+};diff --git a/src/libs/next/workbenchRoutes.test.ts b/src/libs/next/workbenchRoutes.test.tsindex 396f715fcb5..e30f1d96e56 100644--- a/src/libs/next/workbenchRoutes.test.ts+++ b/src/libs/next/workbenchRoutes.test.ts@@ -1,6 +1,22 @@import { describe, expect, it } from 'vitest';-import { isWorkbenchSpaRoute } from './workbenchRoutes';+import { isAlwaysWorkbenchSpaRoute, isWorkbenchSpaRoute } from './workbenchRoutes';++describe('isAlwaysWorkbenchSpaRoute', () => {+ it.each(['/acceptance', '/acceptance/acceptance-1', '/verify', '/verify/run-1'])(+ 'owns verify and acceptance for every UA: %s',+ (pathname) => {+ expect(isAlwaysWorkbenchSpaRoute(pathname)).toBe(true);+ },+ );++ it.each(['/agent/agt_1/docs/doc_1', '/verify-im', '/share/t/topic-1'])(+ 'leaves other Workbench-or-SPA routes alone: %s',+ (pathname) => {+ expect(isAlwaysWorkbenchSpaRoute(pathname)).toBe(false);+ },+ );+});describe('isWorkbenchSpaRoute', () => {it.each([@@ -11,6 +27,9 @@ describe('isWorkbenchSpaRoute', () => {'/acceptance/acceptance-1','/acceptance/acceptance-1?round=2','/acceptance/acceptance-1/check/check-1',+ '/verify',+ '/verify/',+ '/verify/run-1',])('matches a Workbench-owned route: %s', (pathname) => {expect(isWorkbenchSpaRoute(pathname)).toBe(true);});@@ -22,6 +41,8 @@ describe('isWorkbenchSpaRoute', () => {'/acceptance-preview','/acceptance/acceptance-1/history','/workspace/acceptance/acceptance-1',+ '/verify-im',+ '/verify-email',])('does not broaden ownership beyond the declared routes: %s', (pathname) => {expect(isWorkbenchSpaRoute(pathname)).toBe(false);});diff --git a/src/libs/next/workbenchRoutes.ts b/src/libs/next/workbenchRoutes.tsindex e5f2d9c0df9..a0f358a9fb2 100644--- a/src/libs/next/workbenchRoutes.ts+++ b/src/libs/next/workbenchRoutes.ts@@ -1,9 +1,19 @@const AGENT_DOCUMENT_ROUTE = /^\/agent\/[^/]+\/docs\/[^/]+\/?$/;const ACCEPTANCE_ROUTE = /^\/acceptance(?:\/[^/]+(?:\/check\/[^/]+)?)?\/?$/;+const VERIFY_ROUTE = /^\/verify(?:\/[^/]+)?\/?$/;-/** Routes owned by the mobile Workbench SPA at the public URL boundary. */+const pathOnly = (pathname: string) => pathname.split(/[?#]/, 1)[0]!;++/** `/verify` and `/acceptance` — Workbench for every user agent. */+export const isAlwaysWorkbenchSpaRoute = (pathname: string): boolean => {+ const path = pathOnly(pathname);++ return ACCEPTANCE_ROUTE.test(path) || VERIFY_ROUTE.test(path);+};++/** Every path Workbench can own, including mobile-only agent documents. */export const isWorkbenchSpaRoute = (pathname: string): boolean => {- const pathOnly = pathname.split(/[?#]/, 1)[0]!;+ const path = pathOnly(pathname);- return AGENT_DOCUMENT_ROUTE.test(pathOnly) || ACCEPTANCE_ROUTE.test(pathOnly);+ return AGENT_DOCUMENT_ROUTE.test(path) || isAlwaysWorkbenchSpaRoute(path);};diff --git a/src/routes/(main)/acceptance/empty.tsx b/src/routes/(main)/acceptance/empty.tsxdeleted file mode 100644index 267e0dc69fa..00000000000--- a/src/routes/(main)/acceptance/empty.tsx+++ /dev/null@@ -1,3 +0,0 @@-'use client';--export { AcceptanceEmptyDetail as default } from '@/features/Verify';diff --git a/src/routes/(main)/acceptance/index.tsx b/src/routes/(main)/acceptance/index.tsxdeleted file mode 100644index 7e55fd7c5ce..00000000000--- a/src/routes/(main)/acceptance/index.tsx+++ /dev/null@@ -1,3 +0,0 @@-'use client';--export { AcceptanceWorkspace as default } from '@/features/Verify';diff --git a/src/routes/(main)/verify/empty.tsx b/src/routes/(main)/verify/empty.tsxdeleted file mode 100644index fa27ec42897..00000000000--- a/src/routes/(main)/verify/empty.tsx+++ /dev/null@@ -1,3 +0,0 @@-'use client';--export { VerifyEmptyDetail as default } from '@/features/Verify';diff --git a/src/routes/(main)/verify/index.tsx b/src/routes/(main)/verify/index.tsxdeleted file mode 100644index aa7f98b21fd..00000000000--- a/src/routes/(main)/verify/index.tsx+++ /dev/null@@ -1,3 +0,0 @@-'use client';--export { VerifyWorkspace as default } from '@/features/Verify';diff --git a/src/routes/(workbench)/acceptance/[acceptanceId]/index.tsx b/src/routes/(workbench)/acceptance/[acceptanceId]/index.tsxdeleted file mode 100644index 6b1ba5852cf..00000000000--- a/src/routes/(workbench)/acceptance/[acceptanceId]/index.tsx+++ /dev/null@@ -1,3 +0,0 @@-'use client';--export { default } from '@/features/Verify/Acceptance/Workbench/AcceptanceDetail';diff --git a/src/routes/(workbench)/acceptance/index.tsx b/src/routes/(workbench)/acceptance/index.tsxdeleted file mode 100644index 1ccb2a5eeaf..00000000000--- a/src/routes/(workbench)/acceptance/index.tsx+++ /dev/null@@ -1,3 +0,0 @@-'use client';--export { default } from '@/features/Verify/Acceptance/Workbench/AcceptanceList';diff --git a/src/routes/acceptance/[acceptanceId]/index.tsx b/src/routes/acceptance/[acceptanceId]/index.tsxdeleted file mode 100644index 4078ac686cd..00000000000--- a/src/routes/acceptance/[acceptanceId]/index.tsx+++ /dev/null@@ -1,3 +0,0 @@-'use client';--export { AcceptanceViewer as default } from '@/features/Verify';diff --git a/src/routes/verify/[runId]/index.tsx b/src/routes/verify/[runId]/index.tsxdeleted file mode 100644index cd95683d94c..00000000000--- a/src/routes/verify/[runId]/index.tsx+++ /dev/null@@ -1,3 +0,0 @@-'use client';--export { ReportViewer as default } from '@/features/Verify';diff --git a/src/services/verify.ts b/src/services/verify.tsindex 844bda85dde..70d9e739201 100644--- a/src/services/verify.ts+++ b/src/services/verify.ts@@ -167,7 +167,11 @@ export class VerifyService {requirement: string,) => lambdaClient.acceptance.saveGoal.mutate({ requirement, subjectId, subjectType });- listAcceptances = (): Promise<AcceptanceListItem[]> => lambdaClient.acceptance.list.query();+ listAcceptances = (options?: { quiet?: boolean }): Promise<AcceptanceListItem[]> =>+ lambdaClient.acceptance.list.query(+ undefined,+ options?.quiet ? { context: { showNotification: false } } : undefined,+ );/*** Acceptance status for a known set of subjects. `listAcceptances` is cappeddiff --git a/src/spa/BootShell/routeScope.test.ts b/src/spa/BootShell/routeScope.test.tsindex de8016dba74..60ab6401a76 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', '/verify-im']],+ ['Web', webDesktopRoutes, ['/onboarding', '/share/t/topic-1', '/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 70b4cf59df3..b5547f8a086 100644--- a/src/spa/BootShell/routeScope.ts+++ b/src/spa/BootShell/routeScope.ts@@ -7,7 +7,7 @@ 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`, `/share/t/:id` and `/verify` are siblings+ * 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.*diff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsxindex 69850394a00..1da9395ea86 100644--- a/src/spa/router/desktopRouter.config.tsx+++ b/src/spa/router/desktopRouter.config.tsx@@ -2,11 +2,6 @@import type { RouteObject } from 'react-router';-import {- acceptanceRouteMeta,- verifyReportsRouteMeta,- verifyRouteMeta,-} 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';@@ -61,62 +56,6 @@ const webOnlyRoutes: RouteObject[] = [errorElement: <ErrorBoundary />,path: '/verify-im',},-- // Verify report workspace — standalone master-detail (outside main layout)- {- children: [- {- element: dynamicElement(- () => import('@/routes/(main)/verify/empty'),- 'Desktop > Verify Empty',- ),- index: true,- },- {- element: dynamicElement(() => import('@/routes/verify/[runId]'), 'Desktop > VerifyReport'),- handle: { meta: verifyRouteMeta },- path: ':runId',- },- ],- element: dynamicElement(() => import('@/routes/(main)/verify'), 'Desktop > Verify'),- errorElement: <ErrorBoundary />,- handle: { meta: verifyReportsRouteMeta },- path: '/verify',- },-- // Subject-level delivery acceptance — the verify workspace's twin: a- // master-detail with the acceptance list on the left.- {- children: [- {- element: dynamicElement(- () => import('@/routes/(main)/acceptance/empty'),- 'Desktop > Acceptance Empty',- ),- index: true,- },- {- element: dynamicElement(- () => import('@/routes/acceptance/[acceptanceId]'),- 'Desktop > AcceptanceReport',- ),- handle: { meta: acceptanceRouteMeta },- path: ':acceptanceId',- },- {- element: dynamicElement(- () => import('@/routes/acceptance/[acceptanceId]'),- 'Desktop > AcceptanceCheck',- ),- handle: { meta: acceptanceRouteMeta },- path: ':acceptanceId/check/:checkId',- },- ],- element: dynamicElement(() => import('@/routes/(main)/acceptance'), 'Desktop > Acceptance'),- errorElement: <ErrorBoundary />,- handle: { meta: acceptanceRouteMeta },- path: '/acceptance',- },];export const desktopRoutes: RouteObject[] = createSharedDesktopRoutes({diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsxindex a11c8da84e2..1df5edfc5be 100644--- a/src/spa/router/desktopRouter.sync.test.tsx+++ b/src/spa/router/desktopRouter.sync.test.tsx@@ -97,17 +97,6 @@ describe('desktop router shared definition', () => {);});- it('matches the nested acceptance check route on Web only', () => {- const matches = matchRoutes(webDesktopRoutes, '/acceptance/acceptance-1/check/check-1');-- expect(matches?.at(-1)?.route.path).toBe(':acceptanceId/check/:checkId');- expect(matches?.at(-1)?.params).toMatchObject({- acceptanceId: 'acceptance-1',- checkId: 'check-1',- });- expect(electronDesktopRoutes.some((route) => route.path === '/acceptance')).toBe(false);- });-it.each(mainAreaVariants)('%s agent sub-pages declare route meta so tab titles are not bare branding',(_, createMainAreaChildren) => {@@ -287,8 +276,8 @@ describe('desktop router shared definition', () => {expect(webPaths).toContain('/verify-im');expect(webPaths).toContain('/share/t');expect(webPaths).toContain('/share/page');- expect(webPaths).toContain('/verify');- expect(webPaths).toContain('/acceptance');+ expect(webPaths).not.toContain('/verify');+ expect(webPaths).not.toContain('/acceptance');expect(webPaths).toContain('/onboarding');expect(webPaths).not.toContain('/desktop-onboarding');expect(electronPaths).not.toContain('/verify-im');diff --git a/src/spa/router/mobileRouter.config.tsx b/src/spa/router/mobileRouter.config.tsxindex 1252b90d5e8..3a84b20ae62 100644--- a/src/spa/router/mobileRouter.config.tsx+++ b/src/spa/router/mobileRouter.config.tsx@@ -8,11 +8,6 @@ import {} from '@/business/client/BusinessMobileRoutes';import AppsSkeleton from '@/components/Skeleton/Apps';import { mobileAgentSettingsRouteMeta } from '@/features/RouteMeta/mobileRouteMeta';-import {- acceptanceRouteMeta,- verifyReportsRouteMeta,- verifyRouteMeta,-} 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';@@ -629,44 +624,4 @@ export const mobileRoutes: RouteObject[] = [errorElement: <ErrorBoundary />,path: '/verify-im',},-- // Verify report workspace — standalone master-detail (outside main layout)- {- children: [- {- element: dynamicElement(- () => import('@/routes/(main)/verify/empty'),- 'Mobile > Verify Empty',- ),- index: true,- },- {- element: dynamicElement(() => import('@/routes/verify/[runId]'), 'Mobile > VerifyReport'),- handle: { meta: verifyRouteMeta },- path: ':runId',- },- ],- element: dynamicElement(() => import('@/routes/(main)/verify'), 'Mobile > Verify'),- errorElement: <ErrorBoundary />,- handle: { meta: verifyReportsRouteMeta },- path: '/verify',- },- {- element: dynamicElement(- () => import('@/routes/acceptance/[acceptanceId]'),- 'Mobile > AcceptanceReport',- ),- errorElement: <ErrorBoundary />,- handle: { meta: acceptanceRouteMeta },- path: '/acceptance/:acceptanceId',- },- {- element: dynamicElement(- () => import('@/routes/acceptance/[acceptanceId]'),- 'Mobile > AcceptanceCheck',- ),- errorElement: <ErrorBoundary />,- handle: { meta: acceptanceRouteMeta },- path: '/acceptance/:acceptanceId/check/:checkId',- },];diff --git a/src/types/global.d.ts b/src/types/global.d.tsindex 219ca69174e..88d64dde74b 100644--- a/src/types/global.d.ts+++ b/src/types/global.d.ts@@ -53,7 +53,6 @@ declare global {/** Vite define: current bundle is mobile variant */const __MOBILE__: boolean;- const __WORKBENCH__: boolean;/** Vite define: current bundle is Electron desktop variant */const __ELECTRON__: boolean | undefined;diff --git a/src/utils/i18n/loadI18nNamespaceModule.vite.ts b/src/utils/i18n/loadI18nNamespaceModule.vite.tsindex 5bc0cce6cbf..4c3eab7d8d5 100644--- a/src/utils/i18n/loadI18nNamespaceModule.vite.ts+++ b/src/utils/i18n/loadI18nNamespaceModule.vite.ts@@ -9,15 +9,17 @@ type NamespaceLoaderMap = Record<string, () => Promise<NamespaceModule>>;// Use import.meta.glob so Vite can statically analyze and avoid CJS/dynamic import issues.// Platform variants are resolved from their canonical file; exposing them as// separate namespace keys creates duplicate, unreachable dynamic entries.+// Patterns are file-relative (not root-absolute) so the map stays correct no+// matter which app's vite root builds this module (repo root, apps/workbench).const defaultLoaders = import.meta.glob([- '/packages/locales/src/default/*.ts',- '!/packages/locales/src/default/*.vite.ts',- '!/packages/locales/src/default/index.ts',+ '../../../packages/locales/src/default/*.ts',+ '!../../../packages/locales/src/default/*.vite.ts',+ '!../../../packages/locales/src/default/index.ts',]) as NamespaceLoaderMap;-const localeLoaders = import.meta.glob('/locales/*/*.json') as NamespaceLoaderMap;+const localeLoaders = import.meta.glob('../../../locales/*/*.json') as NamespaceLoaderMap;-const getDefaultKey = (ns: string) => `/packages/locales/src/default/${ns}.ts`;-const getLocaleKey = (lng: string, ns: string) => `/locales/${lng}/${ns}.json`;+const getDefaultKey = (ns: string) => `../../../packages/locales/src/default/${ns}.ts`;+const getLocaleKey = (lng: string, ns: string) => `../../../locales/${lng}/${ns}.json`;export const loadI18nNamespaceModule = async (params: LoadI18nNamespaceModuleParams,diff --git a/src/utils/locale.vite.ts b/src/utils/locale.vite.tsindex 31a8aef2b49..9ba0ade9def 100644--- a/src/utils/locale.vite.ts+++ b/src/utils/locale.vite.ts@@ -1,8 +1,10 @@import { normalizeLocale } from '@/locales/resources';-// Use antd ESM locale (es/locale) - CJS locale (locale/*.js) uses module.exports and breaks in Vite+// Use antd ESM locale (es/locale) - CJS locale (locale/*.js) uses module.exports and breaks in Vite.+// Patterns are file-relative (not root-absolute) so the map stays correct no+// matter which app's vite root builds this module (repo root, apps/workbench).const antdLocaleLoaders = import.meta.glob(- '/node_modules/antd/es/locale/{ar_EG,bg_BG,de_DE,en_US,es_ES,fa_IR,fr_FR,it_IT,ja_JP,ko_KR,nl_NL,pl_PL,pt_BR,ru_RU,tr_TR,vi_VN,zh_CN,zh_TW}.js',+ '../../node_modules/antd/es/locale/{ar_EG,bg_BG,de_DE,en_US,es_ES,fa_IR,fr_FR,it_IT,ja_JP,ko_KR,nl_NL,pl_PL,pt_BR,ru_RU,tr_TR,vi_VN,zh_CN,zh_TW}.js',);export const getAntdLocale = async (lang?: string) => {@@ -12,7 +14,7 @@ export const getAntdLocale = async (lang?: string) => {// refs: https://ant.design/docs/react/i18nif (normalLang === 'ar') normalLang = 'ar-EG';- const localePath = `/node_modules/antd/es/locale/${normalLang.replace('-', '_')}.js`;+ const localePath = `../../node_modules/antd/es/locale/${normalLang.replace('-', '_')}.js`;const loadLocale = antdLocaleLoaders[localePath];if (!loadLocale) {diff --git a/tsconfig.json b/tsconfig.jsonindex 239c5ffa5fc..7b7af939479 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -40,6 +40,7 @@"node_modules","apps/desktop/**","apps/mobile/**",+ "apps/workbench/**","scripts/**","tmp","temp",diff --git a/vite.config.ts b/vite.config.tsindex 6ab85f0299b..868965aaec2 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -23,14 +23,12 @@ import { createViteWatchOptions } from './plugins/vite/watchOptions';const isMobile = process.env.MOBILE === 'true';const isAuth = process.env.AUTH === 'true';-const isWorkbench = process.env.SPA_TARGET === 'workbench';const mode = process.env.NODE_ENV === 'production' ? 'production' : 'development';Object.assign(process.env, loadEnv(mode, process.cwd(), ''));const isDev = process.env.NODE_ENV !== 'production';-const isMobileRuntime = isMobile || isWorkbench;-const platform = isAuth ? 'auth' : isMobileRuntime ? 'mobile' : 'web';+const platform = isAuth ? 'auth' : isMobile ? 'mobile' : 'web';const enableViteDevTools = process.env.LOBE_VITE_DEVTOOLS === 'true';const resolveCommandExecutable = (cmd: string) => {@@ -108,38 +106,22 @@ const openExternalBrowser = async (};export default defineConfig({- base: isDev- ? '/'- : process.env.VITE_CDN_BASE ||- (isAuth ? '/_spa-auth/' : isWorkbench ? '/_spa-workbench/' : '/_spa/'),+ base: isDev ? '/' : process.env.VITE_CDN_BASE || (isAuth ? '/_spa-auth/' : '/_spa/'),build: {modulePreload: sharedModulePreload,- outDir: isAuth- ? 'dist/auth'- : isWorkbench- ? 'dist/workbench'- : isMobile- ? 'dist/mobile'- : 'dist/desktop',+ outDir: isAuth ? 'dist/auth' : isMobile ? 'dist/mobile' : 'dist/desktop',reportCompressedSize: false,rolldownOptions: {...(enableViteDevTools && { devtools: {} }),input: path.resolve(__dirname,- isAuth- ? 'index.auth.html'- : isWorkbench- ? 'index.workbench.html'- : isMobile- ? 'index.mobile.html'- : 'index.html',+ isAuth ? 'index.auth.html' : isMobile ? 'index.mobile.html' : 'index.html',),output: createSharedRolldownOutput({ strictExecutionOrder: true }),},},define: {- ...sharedRendererDefine({ isMobile: isMobileRuntime, isElectron: false }),- __WORKBENCH__: JSON.stringify(isWorkbench),+ ...sharedRendererDefine({ isMobile, isElectron: false }),},experimental: {bundledDev: false,@@ -150,7 +132,7 @@ export default defineConfig({},optimizeDeps: sharedOptimizeDeps,plugins: [- isMobileRuntime &&+ isMobile &&isDev && {name: 'mobile-runtime-html-dev-entry',enforce: 'pre' as const,@@ -162,7 +144,7 @@ export default defineConfig({const pathOnly = q === -1 ? raw : raw.slice(0, q);const search = q === -1 ? '' : raw.slice(q);if (pathOnly === '/' || pathOnly === '/index.html') {- req.url = `/${isWorkbench ? 'index.workbench.html' : 'index.mobile.html'}${search}`;+ req.url = `/index.mobile.html${search}`;}next();});@@ -298,7 +280,6 @@ export default defineConfig({},!isAuth &&- !isWorkbench &&VitePWA({injectRegister: null,manifest: false,@@ -346,13 +327,11 @@ export default defineConfig({server: {cors: true,host: true,- port: isWorkbench- ? Number(process.env.WORKBENCH_SPA_PORT) || 3014- : isMobile- ? Number(process.env.MOBILE_SPA_PORT) || 3012- : isAuth- ? Number(process.env.AUTH_SPA_PORT) || 3013- : Number(process.env.SPA_PORT) || 9876,+ port: isMobile+ ? Number(process.env.MOBILE_SPA_PORT) || 3012+ : isAuth+ ? Number(process.env.AUTH_SPA_PORT) || 3013+ : Number(process.env.SPA_PORT) || 9876,// The dev orchestrator (scripts/devStartupSequence.mts) pre-resolves a free// port and injects it via env; never silently drift to another port, since// downstream consumers locate this server through that env contract.