🤯 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(acceptance): restore in-app workspace and assemble the public page from atoms (#18501)
Innei3d751686af31
diff --git a/.agents/skills/compose-atoms/SKILL.md b/.agents/skills/compose-atoms/SKILL.mdnew file mode 100644index 00000000000..2167ced47df--- /dev/null+++ b/.agents/skills/compose-atoms/SKILL.md@@ -0,0 +1,191 @@+---+name: compose-atoms+description: 'Decompose a heavy domain feature into mountable capability atoms. Use when a Viewer/Page/index.tsx owns fetch, filters, mutations, modals, and host integrations together; a visual split still leaves store calls and actions on the page; a portal, embed, share, mobile, or micro-app needs a subset of the same domain; or a new capability is landing as another `readOnly`/`mode`/`variant` flag. Triggers on `compose-atoms`, sink state, 状态下沉, 重业务拆分, 拆成原子, 原子组件, 组装, god component, fat viewer, module graph, slot composition, host seam.'+user-invocable: false+---++# Compose Atoms++A heavy domain is a **kit**, not a viewer with modes. Each host is an import list. An atom owns the data, actions, and dependencies of one capability. The assembler only chooses what to mount.++This is a **module-graph** split. Hiding UI does not drop a module. A host that never imports a file is the only host that does not ship it.++Do not use this skill to slice one component into smaller files. That is `react`.++## When++The folder is a product surface (Conversation, Acceptance, Document, Verify, Task, …) and at least one of these is true:++- One entry owns read + write + workflow + host integration.+- A second host already exists or is the next change (page, portal, share, mobile, popup, micro-app).+- The next feature is another boolean / `mode` / `variant` on the fat tree.+- Reusing a header, list, or card would import trays, stores, or chat.++If the file is large but has **one** capability and **one** host, stop. Use `react`.++## Grain++An atom is the **smallest unit a host is allowed not to mount**.++Ask, for every chunk: _would any host ship the rest and skip this?_ If yes, it is an atom. If no, it stays inside its parent.++That grain is coarser than a visual section and finer than the whole page.++| Too coarse | Right grain | Too fine |+| ---------------------------------- | ----------------------------------- | --------------------------------------------- |+| One `Viewer` with `readOnly` | Identity, goal, list, decision, … | Every badge, row, and icon as a public export |+| `Chat` as a single import | List, composer, intervention, … | Every message sub-row the page then rewires |+| `Document` as editor + every panel | Canvas, header, comments as omitted | Internal toolbar buttons |++A **workflow** (focus review, thread, publish) is one atom to hosts that skip the whole mode. Inside it, keep splitting only if a host would mount a piece of that workflow alone.++## Sink State++The split is worthless if the assembler still holds the domain state. **Imports follow the hook.** A `useStore` / `useX` / `handleAccept` left on the page keeps that module (and everything it imports) on every host that mounts the page.++Sink everything the atom needs into the atom:++| Sinks into the atom | Stays on the assembler |+| ------------------------------------------ | --------------------------------------------- |+| Resource fetch | The record id / scope identity |+| Derived view model (counts, labels, scope) | Which atoms are mounted (the import list) |+| Transient UI (filter, collapse, pending) | Host layout state (focused vs overview, rail) |+| Mutation handlers and their stores/modals | Host seams (provider value the runtime owns) |++```tsx+// wrong — visual split, state still on the page+const Page = () => {+ const { data, mutate } = useX(id);+ const [filter, setFilter] = useState('all');+ const accept = () => void mutate(...);+ return (+ <>+ <Identity data={data} />+ <List data={data} filter={filter} onFilter={setFilter} />+ <DecisionBar onAccept={accept} />+ </>+ );+};++// right — each atom reads and acts; page only assembles+const Page = () => (+ <Scope id={id}>+ <Identity />+ <List />+ <Decision />+ </Scope>+);+```++Do not lift "to fetch once" or "so siblings share data". Two atoms calling the same SWR hook share the cache by key. Sibling writes go through that cache (or a store slice the write atom imports), not through page `useState`.++Lift only when the state **is** the assembler's job: which workflow is on screen, whether a rail is open. If a value is used to render or mutate one capability, it belongs in that capability.++## Kit++| Piece | Owns | Must not own |+| ---------------- | ------------------------------------------------- | -------------------------------------------------- |+| Domain primitive | Types, predicates, formatters | React, stores, services |+| Data access | One resource, one file | Sibling list / infinite / document hooks |+| Read atom | Present + local UI state + its own fetch | Mutations, trays, owner services, host stores |+| Write atom | One mutation and its UI | Page layout, unrelated writes |+| Workflow atom | A mode assembled from other atoms | Becoming the only entry other hosts can import |+| Domain slot | `ReactNode` hole for another **same-domain** atom | A callback whose implementation lives in this file |+| Host seam | Optional host-provided UI, **null by default** | A fallback that imports the host graph |+| Assembler | Layout + the import list | Domain actions; domain fetch except local chrome |++A visual block that both reads and writes is a read atom + a write atom, joined by a domain slot.++Two seam types — do not mix them:++- **Domain slot** — same feature, optional capability (`editSlot`, `toolbar`). The host imports the write atom and passes it in.+- **Host seam** — only some runtimes can resolve it (chat store, topic drawer, Electron). Context default is `null`. The micro-app / share page never imports the provider value. See `split-micro-app` for the runtime cut.++## Ownership++State and imports live in the atom that needs them.++- Read atoms call the isolated resource hook. Filter / collapse / expand stay in the atom.+- Write atoms call the same hook, then mutate. They import their own modals and services. They return `null` when the record is not writable.+- Workflow atoms compose other atoms. They still do not become the light host's entry.+- Assemblers do not fetch in order to push props down. Chrome unique to that host (a title in a shell header) may read the hook.+- Scope context carries **identity** (`id`, `embedded`). It does not carry actions, stores, or modal openers.++Several atoms calling the same SWR hook is expected. SWR dedupes on key. Do not lift data to the assembler "to fetch once".++The shared read hook is **its own file**. A light host imports that file, never a `hooks.ts` / store barrel that also exports list, document, or send-message.++```ts+// any host:+import { useX } from '@/features/Domain/useX';++// never from a light host:+import { useX } from '@/features/Domain/hooks';+import { DomainViewer } from '@/features/Domain';+```++A flag that only changes behavior of code already in the atom is fine. A flag whose purpose is to skip importing another module is not — that module is a slot or a sibling the assembler omits.++`dynamic(() => import(...))` only helps when **no static import** of that module remains on the light graph.++## Assembler++A host is its import list.++```tsx+// light host — deep imports only+<Scope id={id}>+ <ReadA />+ <ReadB />+</Scope>++// full host — same reads, write atoms in slots, workflows as siblings+<ReadA extra={<WriteA />} />+<ReadB toolbar={<WriteB />} />+<Workflow />+<WriteC />+```++Route / portal files compose host skeleton (providers, host seams). Do not add a wrapper page whose only job is to sit between the route and the assembler.++The feature barrel may export the **full** assembler for in-app use. Light hosts must not import that barrel.++## Procedure++1. List **hosts** (page, portal, share, mobile, popup, micro-app — include the next one).+2. List **capabilities as verbs** (view identity, edit field, decide, open host thing). Map host → verbs.+3. Set **grain**: each verb a host can skip is an atom. Group the rest under a parent.+4. Extract primitives and the isolated read hook first.+5. Extract read atoms. Optional same-domain capabilities become `ReactNode` slots, not callbacks that close over write modules.+6. Extract each write / workflow atom into its own file. Heavy deps stay in that file.+7. **Sink state.** Move fetch, view-model, transient UI, and handlers out of the assembler. If the page still calls a domain hook to feed props, the split is not done.+8. Rewrite every host as an import list plus layout. Delete `readOnly` / `isPublic` / `mode` / `variant` on the fat tree.+9. Point light hosts at atoms by **deep path**.+10. Prove the cut. Grep the light entry's import tree, or trace a module the light host must not ship. A missing button is not proof.++```bash+# example: light host must not import a write atom+WORKBENCH_TRACE_MODULE=features/Verify/Acceptance/AcceptanceDecision bun run build:rr+```++If the light assembler appears on the importer chain, a static import still exists — usually a barrel, a leftover flag, or actions left on the page.++## Example++`src/features/Verify/Acceptance/` is one application of this kit, not the template to copy file-for-file.++| Host | Mounts |+| ----------------------------- | ------------------------------------------------------------------------- |+| In-app `Acceptance/index.tsx` | Identity, goal, inventory, decision, focus workflow, ledger + write slots |+| Workbench public detail | Identity, goal, inventory only |+| Portal | Full assembler + `OriginConversationProvider` |++Read `AcceptanceGoal` (read + `editSlot`) and `AcceptanceGoalEdit` (write) for the slot cut. Read `originConversation.tsx` for a host seam. Read workbench `AcceptanceDetail.tsx` for a light assembler.++## Related skills++- **`react`**: single-surface boundaries, styling, memoization.+- **`split-micro-app`**: worker / SSR / gateway / stubs. This skill is how the shared UI is cut afterwards.+- **`spa-routes`**: route files stay thin assemblers.+- **`data-fetching-architecture`**: how the isolated hook fetches, not where a host may import it from.+- **`zustand`**: narrow selectors inside an atom; do not put the whole store on scope context.diff --git a/.agents/skills/react/SKILL.md b/.agents/skills/react/SKILL.mdindex bc32c09af6e..c0df7572001 100644--- a/.agents/skills/react/SKILL.md+++ b/.agents/skills/react/SKILL.md@@ -58,7 +58,7 @@ For Modal specifically, see the dedicated **modal** skill — use the imperativeKeep transient state in its smallest useful owner. Extract a custom hook when state transitions and handlers obscure rendering or form a reusable unit; do not extract solely because a component has a particular number of hooks.-Split a component only to establish a real state, reuse, or render-update boundary. Do not split solely to make files smaller.+Split a component only to establish a real state, reuse, render-update, or mountable-capability boundary. Do not split solely to make files smaller. Decomposing a heavy domain feature into host-assembled atoms is owned by **`compose-atoms`**.## Render Performance and Memoization@@ -85,4 +85,5 @@ Use `Flexbox` and `Center` from `@lobehub/ui`. See `references/layout-kit.md` fo- **`ux`**: loading visuals and user-facing interaction design. Do not use antd `Spin` / `<Spin />`.- **`modal`**: imperative base-ui modal patterns.- **`spa-routes`**: SPA navigation, route ownership, router configuration, and `.desktop` variants.+- **`compose-atoms`**: split a heavy domain feature into mountable capability atoms; each host imports only what it mounts.- **`zustand`**: store structure and selector conventions.diff --git a/.agents/skills/split-micro-app/SKILL.md b/.agents/skills/split-micro-app/SKILL.mdindex 72be76c5335..62a6373e49f 100644--- a/.agents/skills/split-micro-app/SKILL.md+++ b/.agents/skills/split-micro-app/SKILL.md@@ -49,14 +49,18 @@ tsconfig `include` must cover `app/`). Stack: `@react-router/dev@8` + `@cloudfla**SSR bundle weight is the whole battle.** Main-src imports drag the app universe(store web → chat/agent/electron). Tools and cuts, in order:-| Tool / cut | How |-| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Trace who pulls a module | `WORKBENCH_TRACE_MODULE=store/chat/store [WORKBENCH_TRACE_ENV=client] bun run build:rr` — prints importer chain |-| Client-gate heavy routes | `.client.tsx` module + `clientOnlyRoute()` factory (hydration gate; SSR renders loading) |-| SSR-stub store hubs | vite `resolveId` stubs per env (`app/stubs/`): trpc client, services/global, store/electron, store/file, i18n loader. Stubs must be **callable empty-state hooks**, not throwing proxies — render paths call them |-| 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`) |+| Tool / cut | How |+| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| Trace who pulls a module | `WORKBENCH_TRACE_MODULE=store/chat/store [WORKBENCH_TRACE_ENV=client] bun run build:rr` — prints importer chain |+| Client-gate heavy routes | `.client.tsx` module + `clientOnlyRoute()` factory (hydration gate; SSR renders loading) |+| SSR-stub store hubs | vite `resolveId` stubs per env (`app/stubs/`): trpc client, services/global, store/electron, store/file, i18n loader. Stubs must be **callable empty-state hooks**, not throwing proxies — render paths call them. Keep the implemented surface explicit (no catch-all `Proxy` / `as never`): `stubSurfaceGuard` in `vite.config.rr.mts` fails the build when the graph imports an export or member the stub does not implement. Add the member (empty / `reject`) or keep the importer off the graph. |+| Client-shim lambda | Client `@/libs/trpc/client` is a cookie-only `httpLink` (`trpcClient.client.ts`). Do not ship the real `lambda.ts` — its `headers()` pulls image store → chat store + `model-bank` catalog. |+| SSR-stub shiki langs | On the SSR env, resolve `@shikijs/langs` / `@shikijs/themes` / shiki's `langs-bundle` / `themes` / wasm to `app/stubs/shiki.ts`. Do **not** stub the `shiki` package entry — Pierre diffs and Highlighter import named APIs from it. |+| Client shiki from CDN | On the client env, resolve `shiki` / `shiki/*` / `@shikijs/*` to pinned `https://esm.sh/...@<installed shiki version>` as externals. Do not bundle grammars or wasm into `build/client`. |+| Slot-inject app-only features | Context seam owned by the shared feature (see `src/features/Verify/Acceptance/originConversation.tsx`); app provides, micro app leaves null → affordances hide |+| Bypass barrels | Deep-path imports (`@/features/Verify/Acceptance`, not the barrel) — barrels evaluate sibling exports with side effects |+| Compose capability atoms | Shared UI is assembled per surface; the light app never imports the fat viewer. See **`compose-atoms`**. Do not add `readOnly` on the in-app page |+| Decouple dual-use components | Lift store reads to optional props (see AudioPlayer `uploadState`/`onCancelUpload`) |Products: `build/client` (assets → CDN), `build/server` (worker; deploy with`wrangler deploy --config build/server/wrangler.json`). Budget: worker gzip ≤ 10MB paid.diff --git a/AGENTS.md b/AGENTS.mdindex 39af5d971b4..7595bcbf865 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -16,6 +16,7 @@ Guidelines for using AI coding agents in this opensource LobeHub repository.`AGENTS.md` owns repository-wide architecture and workflow. Keep detailed implementation rules in skills so they have one source of truth.- **React and TSX**: Before editing components, component state, render boundaries, or memoization, read [`.agents/skills/react/SKILL.md`](.agents/skills/react/SKILL.md). It owns component selection, styling, state locality, and render-performance rules.+- **Heavy domain features**: When splitting a fat Viewer/Page into reusable pieces (page vs portal vs share vs micro-app), read [`.agents/skills/compose-atoms/SKILL.md`](.agents/skills/compose-atoms/SKILL.md). Split on mountable capabilities, not visual sections, and do not hide unused work behind `readOnly` / `mode` flags.## Project Structurediff --git a/apps/workbench/app/root.tsx b/apps/workbench/app/root.tsxindex 90fa629762f..a4359b00bc7 100644--- a/apps/workbench/app/root.tsx+++ b/apps/workbench/app/root.tsx@@ -86,7 +86,7 @@ export default function Root() {return (<NextThemeProvider>- <WorkbenchShell locale={data?.locale} resources={data?.resources} serverConfig={null}>+ <WorkbenchShell locale={data?.locale} resources={data?.resources}><Outlet /></WorkbenchShell></NextThemeProvider>@@ -106,7 +106,7 @@ export const ErrorBoundary = () => {// (theme + i18n) for the shared error page to render properly.return (<NextThemeProvider>- <WorkbenchShell locale={data?.locale} resources={data?.resources} serverConfig={null}>+ <WorkbenchShell locale={data?.locale} resources={data?.resources}><ErrorCapture error={error} /></WorkbenchShell></NextThemeProvider>diff --git a/apps/workbench/app/routes.ts b/apps/workbench/app/routes.tsindex 4e2ba62635c..181bfec39ee 100644--- a/apps/workbench/app/routes.ts+++ b/apps/workbench/app/routes.ts@@ -4,7 +4,7 @@ export default [index('routes/homeRedirect.tsx'),route('agent/:aid/docs/:docId', 'routes/agentDoc.tsx'),route('acceptance', 'layouts/acceptanceNamespace.tsx', [- index('routes/acceptanceList.tsx'),+ index('routes/acceptanceIndex.tsx'),route(':acceptanceId', 'routes/acceptanceDetail.tsx'),route(':acceptanceId/check/:checkId', 'routes/acceptanceDetailCheck.tsx'),]),diff --git a/apps/workbench/app/routes/acceptanceIndex.tsx b/apps/workbench/app/routes/acceptanceIndex.tsxnew file mode 100644index 00000000000..0e2d5123fe3--- /dev/null+++ b/apps/workbench/app/routes/acceptanceIndex.tsx@@ -0,0 +1 @@+export { default, loader } from './homeRedirect';diff --git a/apps/workbench/app/routes/acceptanceList.tsx b/apps/workbench/app/routes/acceptanceList.tsxdeleted file mode 100644index a9fb247ed74..00000000000--- a/apps/workbench/app/routes/acceptanceList.tsx+++ /dev/null@@ -1 +0,0 @@-export { default } from '../../src/features/acceptance/AcceptanceList';diff --git a/apps/workbench/app/stubs/electronStore.ts b/apps/workbench/app/stubs/electronStore.tsindex bdb29e0aa04..8ba30264df2 100644--- a/apps/workbench/app/stubs/electronStore.ts+++ b/apps/workbench/app/stubs/electronStore.ts@@ -1,8 +1,8 @@-const emptyState = {} as never;+const emptyState = {};// 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 =>+export const useElectronStore = <T = unknown>(selector?: (state: typeof emptyState) => T): T =>selector ? selector(emptyState) : (emptyState as T);useElectronStore.getState = () => emptyState;diff --git a/apps/workbench/app/stubs/fileStore.ts b/apps/workbench/app/stubs/fileStore.tsindex 0e04ff0db36..e6d3150faf8 100644--- a/apps/workbench/app/stubs/fileStore.ts+++ b/apps/workbench/app/stubs/fileStore.ts@@ -1,14 +1,14 @@-const emptyState = {} as never;+const emptyState = {+ uploadWithProgress: async () => undefined,+};-export const useFileStore = <T = unknown>(selector?: (state: never) => T): T =>+export const useFileStore = <T = unknown>(selector?: (state: typeof emptyState) => 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 documentSelectors = {};+export const fileChatSelectors = {};+export const fileManagerSelectors = {};+export const filesSelectors = {};export const getChunkTargetId = () => undefined;diff --git a/apps/workbench/app/stubs/shiki.ts b/apps/workbench/app/stubs/shiki.tsnew file mode 100644index 00000000000..2719eedf375--- /dev/null+++ b/apps/workbench/app/stubs/shiki.ts@@ -0,0 +1,15 @@+const emptyInfo: { aliases?: string[]; displayName?: string; id: string; name?: string }[] = [];++export const bundledLanguagesInfo = emptyInfo;+export const bundledThemesInfo = emptyInfo;+export const bundledLanguages = {};+export const bundledThemes = {};+export const bundledLanguagesAlias = {};+export const bundledLanguagesBase = {};++export const i = bundledLanguagesInfo;+export const n = bundledLanguagesAlias;+export const r = bundledLanguagesBase;+export const t = bundledLanguages;++export default {};diff --git a/apps/workbench/app/stubs/shikiCdn.test.ts b/apps/workbench/app/stubs/shikiCdn.test.tsnew file mode 100644index 00000000000..0e71f8466ef--- /dev/null+++ b/apps/workbench/app/stubs/shikiCdn.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from 'vitest';++import { shikiCdnUrl } from './shikiCdn';++const v = '4.4.3';++describe('shikiCdnUrl', () => {+ it.each([+ ['shiki', `https://esm.sh/shiki@${v}`],+ ['shiki/core', `https://esm.sh/shiki@${v}/core`],+ ['@shikijs/transformers', `https://esm.sh/@shikijs/transformers@${v}`],+ ['@shikijs/langs/python', `https://esm.sh/@shikijs/langs@${v}/python`],+ ])('%s → %s', (source, url) => {+ expect(shikiCdnUrl(source, v)).toBe(url);+ });++ it.each(['react', '@/features/Verify/Acceptance'])('leaves %s bundled', (source) => {+ expect(shikiCdnUrl(source, v)).toBeUndefined();+ });+});diff --git a/apps/workbench/app/stubs/shikiCdn.ts b/apps/workbench/app/stubs/shikiCdn.tsnew file mode 100644index 00000000000..3fd12bd3c58--- /dev/null+++ b/apps/workbench/app/stubs/shikiCdn.ts@@ -0,0 +1,9 @@+export const shikiCdnUrl = (source: string, version: string): string | undefined => {+ if (source === 'shiki') return `https://esm.sh/shiki@${version}`;+ if (source.startsWith('shiki/')) return `https://esm.sh/shiki@${version}/${source.slice(6)}`;+ if (!source.startsWith('@shikijs/')) return;+ const rest = source.slice('@shikijs/'.length);+ const slash = rest.indexOf('/');+ if (slash === -1) return `https://esm.sh/@shikijs/${rest}@${version}`;+ return `https://esm.sh/@shikijs/${rest.slice(0, slash)}@${version}${rest.slice(slash)}`;+};diff --git a/apps/workbench/app/stubs/shikiSource.test.ts b/apps/workbench/app/stubs/shikiSource.test.tsnew file mode 100644index 00000000000..7523b2ade2f--- /dev/null+++ b/apps/workbench/app/stubs/shikiSource.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest';++import { isShikiSource } from './shikiSource';++describe('isShikiSource', () => {+ it.each([+ ['@shikijs/langs', undefined],+ ['@shikijs/langs/cpp', undefined],+ ['@shikijs/themes', undefined],+ ['shiki/wasm', undefined],+ ['/repo/node_modules/@shikijs/langs/dist/cpp.mjs', undefined],+ ['/repo/node_modules/@shikijs/themes/dist/github-dark.mjs', undefined],+ ['./langs-bundle-full-xQVO1Cek.mjs', '/repo/node_modules/shiki/dist/index.mjs'],+ ['./themes.mjs', '/repo/node_modules/shiki/dist/index.mjs'],+ ['./wasm-inlined.mjs', '/repo/node_modules/@shikijs/engine-oniguruma/dist/index.mjs'],+ ] as const)('stubs %s from %s', (source, importer) => {+ expect(isShikiSource(source, importer)).toBe(true);+ });++ it.each([+ ['shiki', undefined],+ ['@shikijs/transformers', undefined],+ ['@shikijs/core', undefined],+ ['@lobehub/ui', undefined],+ ['/repo/src/features/Verify/Acceptance/index.tsx', undefined],+ ['./bundle-full.mjs', '/repo/node_modules/shiki/dist/index.mjs'],+ ] as const)('leaves %s from %s', (source, importer) => {+ expect(isShikiSource(source, importer)).toBe(false);+ });+});diff --git a/apps/workbench/app/stubs/shikiSource.ts b/apps/workbench/app/stubs/shikiSource.tsnew file mode 100644index 00000000000..181994f9ea1--- /dev/null+++ b/apps/workbench/app/stubs/shikiSource.ts@@ -0,0 +1,20 @@+const LANG_OR_THEME = /(?:^|\/)(?:langs-bundle|themes)(?:[-.]|$)/;+const WASM = /wasm(?:-inlined)?|onig\.wasm/;++export const isShikiSource = (source: string, importer?: string) => {+ if (source.startsWith('@shikijs/langs') || source.startsWith('@shikijs/themes')) return true;+ if (source === 'shiki/wasm' || source.startsWith('shiki/wasm')) return true;++ const normalized = source.replaceAll('\\', '/');+ if (normalized.includes('/node_modules/@shikijs/langs/')) return true;+ if (normalized.includes('/node_modules/@shikijs/themes/')) return true;+ if (normalized.includes('/node_modules/shiki/dist/wasm')) return true;+ if (normalized.includes('/node_modules/@shikijs/engine-oniguruma/') && WASM.test(normalized))+ return true;++ const from = (importer ?? '').replaceAll('\\', '/');+ if (from.includes('/node_modules/@shikijs/engine-oniguruma/') && WASM.test(normalized))+ return true;+ if (!from.includes('/node_modules/shiki/')) return false;+ return LANG_OR_THEME.test(normalized) || WASM.test(normalized);+};diff --git a/apps/workbench/app/stubs/surface.test.ts b/apps/workbench/app/stubs/surface.test.tsnew file mode 100644index 00000000000..a82c5492221--- /dev/null+++ b/apps/workbench/app/stubs/surface.test.ts@@ -0,0 +1,110 @@+import { readFileSync } from 'node:fs';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++import {+ collectStubUsage,+ parseStubSurface,+ reportStubSurfaceGaps,+ stubUsageGaps,+} from './surface';++const stubDir = import.meta.dirname;++describe('workbench stub surface', () => {+ it('treats reject() and createTRPCClient() as open members', () => {+ const surface = parseStubSurface(+ readFileSync(path.join(stubDir, 'trpcClient.client.ts'), 'utf8'),+ );++ expect([...surface.exports].sort()).toEqual([+ 'asyncClient',+ 'lambdaClient',+ 'lambdaQuery',+ 'toolsClient',+ ]);+ expect(surface.open.has('lambdaClient')).toBe(true);++ expect(+ stubUsageGaps(+ surface,+ collectStubUsage(+ `import { lambdaClient, createWorkspaceLambdaClient } from '@/libs/trpc/client';+ void lambdaClient.verify.getBundle.query();+ void createWorkspaceLambdaClient('ws');`,+ '@/libs/trpc/client',+ )!,+ ),+ ).toEqual(['createWorkspaceLambdaClient']);+ });++ it('reports a store method the simplified stub does not implement', () => {+ const surface = parseStubSurface(readFileSync(path.join(stubDir, 'fileStore.ts'), 'utf8'));+ const usage = collectStubUsage(+ `import { useFileStore } from '@/store/file';+ const removeFile = useFileStore((s) => s.removeFile);`,+ '@/store/file',+ );++ expect(stubUsageGaps(surface, usage!)).toEqual(['useFileStore.removeFile']);+ expect(+ stubUsageGaps(+ surface,+ collectStubUsage(+ `import { useFileStore } from '@/store/file';+ const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);`,+ '@/store/file',+ )!,+ ),+ ).toEqual([]);+ });++ it('allows implemented hook members and ignores type-only imports', () => {+ const surface = parseStubSurface(readFileSync(path.join(stubDir, 'electronStore.ts'), 'utf8'));+ const usage = collectStubUsage(+ `import type { ElectronStore } from '@/store/electron';+ import { getElectronStoreState, useElectronStore } from '@/store/electron';+ const state = useElectronStore.getState();+ void getElectronStoreState();`,+ '@/store/electron',+ );++ expect(stubUsageGaps(surface, usage!)).toEqual([]);+ });++ it('does not treat a catch-all selector proxy as covering new methods', () => {+ const surface = parseStubSurface(`+ export const fileChatSelectors = new Proxy({}, { get: () => () => undefined });+ `);+ const usage = collectStubUsage(+ `import { fileChatSelectors } from '@/store/file';+ fileChatSelectors.chatUploadFileList(state);`,+ '@/store/file',+ );++ expect(stubUsageGaps(surface, usage!)).toEqual(['fileChatSelectors.chatUploadFileList']);+ });++ it('formats graph gaps with the importer path', () => {+ expect(+ reportStubSurfaceGaps(+ [+ {+ rel: 'src/features/Verify/Acceptance/attachments.tsx',+ source: `import { useFileStore } from '@/store/file';+ const removeFile = useFileStore((s) => s.removeFile);`,+ },+ ],+ [+ {+ source: readFileSync(path.join(stubDir, 'fileStore.ts'), 'utf8'),+ specifier: '@/store/file',+ },+ ],+ ),+ ).toEqual([+ ' src/features/Verify/Acceptance/attachments.tsx\n @/store/file: useFileStore.removeFile',+ ]);+ });+});diff --git a/apps/workbench/app/stubs/surface.ts b/apps/workbench/app/stubs/surface.tsnew file mode 100644index 00000000000..cba396d7385--- /dev/null+++ b/apps/workbench/app/stubs/surface.ts@@ -0,0 +1,224 @@+const EXPORT_CONST = /^[ \t]*export const (\w+)\s*=\s*/gm;+const EXPORT_NAMED = /^[ \t]*export \{([^}]+)\}/gm;+const EXPORT_FUNCTION = /^[ \t]*export (?:async )?function (\w+)/gm;+const ASSIGN_MEMBER = /^[ \t]*(\w+)\.(\w+)\s*=/gm;+const EMPTY_STATE = /(?:const|let)\s+emptyState\s*=\s*\{([^}]*)\}/;+const OPEN_INITIALIZER = /^(?:reject\s*\(|createTRPCClient\b)/;++export type StubSurface = {+ exports: Set<string>;+ members: Map<string, Set<string>>;+ open: Set<string>;+};++export type StubUsage = {+ members: Map<string, Set<string>>;+ names: Set<string>;+};++const addMember = (members: Map<string, Set<string>>, name: string, member: string) => {+ if (!members.has(name)) members.set(name, new Set());+ members.get(name)!.add(member);+};++const parseObjectKeys = (body: string): Set<string> => {+ const keys = new Set<string>();+ for (const match of body.matchAll(/^\s*(?:async\s+)?([A-Za-z_$][\w$]*)\s*(?:[:(,]|$)/gm)) {+ keys.add(match[1]!);+ }+ return keys;+};++const parseNamedSpecifiers = (clause: string): Array<{ imported: string; local: string }> => {+ const specifiers: Array<{ imported: string; local: string }> = [];+ for (const raw of clause.split(',')) {+ const piece = raw.trim();+ if (!piece || piece === ',') continue;+ const typeOnly = /^type\s+/.test(piece);+ const rest = piece.replace(/^type\s+/, '');+ if (!rest || rest === 'type') continue;+ const aliased = rest.match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/);+ if (aliased) {+ if (typeOnly) continue;+ specifiers.push({ imported: aliased[1]!, local: aliased[2]! });+ continue;+ }+ const ident = rest.match(/^([A-Z_$][\w$]*)$/i);+ if (!ident || typeOnly) continue;+ specifiers.push({ imported: ident[1]!, local: ident[1]! });+ }+ return specifiers;+};++export const parseStubSurface = (source: string): StubSurface => {+ const exports = new Set<string>();+ const members = new Map<string, Set<string>>();+ const open = new Set<string>();++ for (const match of source.matchAll(EXPORT_CONST)) {+ const name = match[1]!;+ exports.add(name);+ const rhs = source.slice(match.index! + match[0].length).trimStart();+ if (OPEN_INITIALIZER.test(rhs)) {+ open.add(name);+ continue;+ }+ if (rhs.startsWith('{')) {+ const close = rhs.indexOf('}');+ if (close !== -1) {+ members.set(name, parseObjectKeys(rhs.slice(1, close)));+ }+ }+ }++ for (const match of source.matchAll(EXPORT_FUNCTION)) exports.add(match[1]!);++ for (const match of source.matchAll(EXPORT_NAMED)) {+ for (const spec of parseNamedSpecifiers(match[1]!)) exports.add(spec.imported);+ }++ for (const match of source.matchAll(ASSIGN_MEMBER)) {+ addMember(members, match[1]!, match[2]!);+ }++ const emptyState = source.match(EMPTY_STATE);+ if (emptyState) {+ const keys = parseObjectKeys(emptyState[1]!);+ for (const name of exports) {+ if (open.has(name) || !/^(?:use\w+Store|get\w+StoreState)$/.test(name)) continue;+ for (const key of keys) addMember(members, name, key);+ }+ }++ return { exports, members, open };+};++const collectNamespaceUsage = (source: string, local: string, usage: StubUsage) => {+ const access = new RegExp(+ String.raw`\b${local}\.([A-Za-z_$][\w$]*)(?:\.([A-Za-z_$][\w$]*))?`,+ 'g',+ );+ for (const match of source.matchAll(access)) {+ const exported = match[1]!;+ usage.names.add(exported);+ if (match[2]) addMember(usage.members, exported, match[2]);+ }+};++const collectLocalMembers = (source: string, local: string, exported: string, usage: StubUsage) => {+ const dotted = new RegExp(String.raw`\b${local}\.([A-Za-z_$][\w$]*)`, 'g');+ for (const match of source.matchAll(dotted)) addMember(usage.members, exported, match[1]!);++ const returned = new RegExp(String.raw`\b${local}\(\)\.([A-Za-z_$][\w$]*)`, 'g');+ for (const match of source.matchAll(returned)) addMember(usage.members, exported, match[1]!);++ const selector = new RegExp(+ String.raw`\b${local}\(\s*(?:async\s*)?\(?\s*([A-Za-z_$][\w$]*)\s*(?::[^)=]*)?\)?\s*=>`,+ 'g',+ );+ for (const match of source.matchAll(selector)) {+ const param = match[1]!;+ const window = source.slice(+ match.index! + match[0].length,+ match.index! + match[0].length + 400,+ );+ const props = new RegExp(String.raw`\b${param}\.([A-Za-z_$][\w$]*)`, 'g');+ for (const prop of window.matchAll(props)) addMember(usage.members, exported, prop[1]!);+ }+};++const consumeImportClause = (source: string, clause: string, usage: StubUsage) => {+ const trimmed = clause.trim();+ const namespace = trimmed.match(/^(?:(\w+)\s*,\s*)?\*\s+as\s+(\w+)$/);+ if (namespace) {+ if (namespace[1]) {+ usage.names.add('default');+ collectLocalMembers(source, namespace[1], 'default', usage);+ }+ collectNamespaceUsage(source, namespace[2]!, usage);+ return;+ }++ const named = trimmed.match(/^(?:(\w+)\s*,\s*)?\{([^}]*)\}$/);+ if (named) {+ if (named[1]) {+ usage.names.add('default');+ collectLocalMembers(source, named[1], 'default', usage);+ }+ for (const spec of parseNamedSpecifiers(named[2] ?? '')) {+ usage.names.add(spec.imported);+ collectLocalMembers(source, spec.local, spec.imported, usage);+ }+ return;+ }++ const defaultOnly = trimmed.match(/^(\w+)$/);+ if (defaultOnly) {+ usage.names.add('default');+ collectLocalMembers(source, defaultOnly[1]!, 'default', usage);+ }+};++export const collectStubUsage = (source: string, specifier: string): StubUsage | null => {+ const usage: StubUsage = { members: new Map(), names: new Set() };+ let matched = false;++ for (const quote of [`'${specifier}'`, `"${specifier}"`]) {+ const needle = `from ${quote}`;+ let cursor = 0;+ while (cursor < source.length) {+ const idx = source.indexOf(needle, cursor);+ if (idx === -1) break;+ cursor = idx + needle.length;+ const before = source.slice(Math.max(0, idx - 400), idx);+ const importIdx = Math.max(before.lastIndexOf('import'), before.lastIndexOf('export'));+ if (importIdx === -1) continue;+ matched = true;+ const raw = before.slice(importIdx).replace(/^(?:import|export)\s+/, '');+ if (raw.startsWith('type ')) continue;+ consumeImportClause(source, raw.trim(), usage);+ }+ }++ return matched ? usage : null;+};++export const stubUsageGaps = (surface: StubSurface, usage: StubUsage): string[] => {+ const gaps: string[] = [];++ for (const name of usage.names) {+ if (!surface.exports.has(name)) gaps.push(name);+ }++ for (const [name, members] of usage.members) {+ if (!usage.names.has(name) || !surface.exports.has(name) || surface.open.has(name)) continue;+ const implemented = surface.members.get(name) ?? new Set();+ for (const member of members) {+ if (!implemented.has(member)) gaps.push(`${name}.${member}`);+ }+ }++ return gaps.sort();+};++export const reportStubSurfaceGaps = (+ files: Array<{ rel: string; source: string }>,+ stubs: Array<{ source: string; specifier: string }>,+): string[] => {+ const surfaces = stubs.map((stub) => ({+ specifier: stub.specifier,+ surface: parseStubSurface(stub.source),+ }));++ const lines: string[] = [];+ for (const file of files) {+ for (const stub of surfaces) {+ const usage = collectStubUsage(file.source, stub.specifier);+ if (!usage) continue;+ const gaps = stubUsageGaps(stub.surface, usage);+ if (gaps.length === 0) continue;+ lines.push(` ${file.rel}\n ${stub.specifier}: ${gaps.join(', ')}`);+ }+ }+ return lines;+};diff --git a/apps/workbench/app/stubs/trpcClient.client.test.ts b/apps/workbench/app/stubs/trpcClient.client.test.tsnew file mode 100644index 00000000000..d7bf1040d87--- /dev/null+++ b/apps/workbench/app/stubs/trpcClient.client.test.ts@@ -0,0 +1,20 @@+import { readFileSync } from 'node:fs';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++const source = readFileSync(path.join(import.meta.dirname, 'trpcClient.client.ts'), 'utf8');++describe('workbench client lambda shim', () => {+ it.each(['@/store/image', '@/store/chat', '@/services/_auth', '@/store/user', 'model-bank'])(+ 'does not import %s',+ (needle) => {+ expect(source).not.toContain(needle);+ },+ );++ it('sends cookies and skips the image-page header stack', () => {+ expect(source).toContain("credentials: 'include'");+ expect(source).toContain("url: '/trpc/lambda'");+ });+});diff --git a/apps/workbench/app/stubs/trpcClient.client.ts b/apps/workbench/app/stubs/trpcClient.client.tsnew file mode 100644index 00000000000..fa2561daa65--- /dev/null+++ b/apps/workbench/app/stubs/trpcClient.client.ts@@ -0,0 +1,20 @@+import { createTRPCClient, httpLink } from '@trpc/client';+import superjson from 'superjson';++import type { LambdaRouter } from '@/server/routers/lambda';++import { reject } from './reject';++export const lambdaClient = createTRPCClient<LambdaRouter>({+ links: [+ httpLink({+ fetch: (input, init) => fetch(input, { ...init, credentials: 'include' }),+ transformer: superjson,+ url: '/trpc/lambda',+ }),+ ],+});++export const asyncClient = reject('asyncClient');+export const toolsClient = reject('toolsClient');+export const lambdaQuery = reject('lambdaQuery');diff --git a/apps/workbench/src/features/acceptance/AcceptanceDetail.tsx b/apps/workbench/src/features/acceptance/AcceptanceDetail.tsxindex 1b17fe1d9a4..7ad79b34d62 100644--- a/apps/workbench/src/features/acceptance/AcceptanceDetail.tsx+++ b/apps/workbench/src/features/acceptance/AcceptanceDetail.tsx@@ -1,50 +1,24 @@'use client';-import { Flexbox } from '@lobehub/ui/es/Flex/index';-import Text from '@lobehub/ui/es/Text/index';+import { Flexbox, Text } from '@lobehub/ui';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 { useParams } from 'react-router';++import AcceptanceCheckInventory from '@/features/Verify/Acceptance/AcceptanceCheckInventory';+import AcceptanceGoal from '@/features/Verify/Acceptance/AcceptanceGoal';+import AcceptanceIdentity from '@/features/Verify/Acceptance/AcceptanceIdentity';+import {+ AcceptanceBundleGate,+ AcceptanceScope,+} from '@/features/Verify/Acceptance/AcceptanceScope';+import { useAcceptanceBundle } from '@/features/Verify/Acceptance/useAcceptanceBundle';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;- }-}+import { WorkbenchHeader } from '../../shell/WorkbenchHeader';const styles = createStaticStyles(({ css }) => ({body: css`- overflow: hidden;+ overflow: auto;flex: 1;min-height: 0;`,@@ -57,74 +31,56 @@ const styles = createStaticStyles(({ css }) => ({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};`,+ report: css`+ width: 100%;+ max-width: 920px;+ margin-block: 0;+ margin-inline: auto;+ padding-block: 20px;+ padding-inline: 24px;+ `,}));-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 Title = () => {+ const { acceptanceId } = useParams<{ acceptanceId: string }>();+ const { data } = useAcceptanceBundle(extractUuid(acceptanceId) ?? null);+ return (+ <Text ellipsis strong style={{ minWidth: 0 }}>+ {data?.subject.title ?? acceptanceId}+ </Text>);- const showSidebar = Boolean(workspaceList) && !hasFocusedCheck;+};++const WorkbenchAcceptanceDetail = () => {+ const params = useParams<{ acceptanceId: string }>();+ const acceptanceId = extractUuid(params.acceptanceId);+ if (!acceptanceId) return null;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>+ <AcceptanceScope acceptanceId={acceptanceId}>+ <Flexbox className={styles.page}>+ <Flexbox className={styles.header} justify={'center'}>+ <WorkbenchHeader>+ <Title />+ </WorkbenchHeader></Flexbox><div className={styles.body}>- <AcceptanceViewer />+ <AcceptanceBundleGate height={'100%'}>+ <Flexbox className={styles.report} gap={16}>+ <AcceptanceIdentity />+ <AcceptanceGoal />+ <AcceptanceCheckInventory />+ </Flexbox>+ </AcceptanceBundleGate></div></Flexbox>- </Flexbox>+ </AcceptanceScope>);-});--WorkbenchAcceptanceDetail.displayName = 'WorkbenchAcceptanceDetail';+};export default WorkbenchAcceptanceDetail;diff --git a/apps/workbench/src/features/acceptance/AcceptanceList.tsx b/apps/workbench/src/features/acceptance/AcceptanceList.tsxdeleted file mode 100644index 51c5ce0ad99..00000000000--- a/apps/workbench/src/features/acceptance/AcceptanceList.tsx+++ /dev/null@@ -1,287 +0,0 @@-'use client';--import { Accordion, AccordionItem } from '@lobehub/ui';-import type { DropdownItem } from '@lobehub/ui/base-ui';-import { DropdownMenu } from '@lobehub/ui/base-ui';-import ActionIcon from '@lobehub/ui/es/ActionIcon/index';-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 { Check, FolderClosed, ListFilter, ScrollText, Search, TriangleAlert } from 'lucide-react';-import { memo, useState } from 'react';-import { useTranslation } from 'react-i18next';-import useSWR from 'swr';--import {- type AcceptanceListFilter,- DEFAULT_ACCEPTANCE_LIST_FILTER,- filterAcceptanceList,- normalizeAcceptanceListFilter,-} from '@/features/Verify/Acceptance/Workspace/acceptanceListFilter';-import {- groupAcceptanceList,- hasProjectAcceptanceGroups,-} from '@/features/Verify/Acceptance/Workspace/groupAcceptanceList';-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';-const EMPTY_FILTER_KEYS = {- active: 'acceptance.workspace.filters.empty.active',- completed: 'acceptance.workspace.filters.empty.completed',-} as const satisfies Record<Exclude<AcceptanceListFilter, 'all'>, string>;--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;- `,- groupList: css`- display: flex;- flex-direction: column;- gap: 2px;- `,- groupTitle: css`- display: inline-flex;- gap: 6px;- align-items: center;-- font-size: 12px;- font-weight: 500;- color: ${cssVar.colorTextSecondary};- `,- 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 WorkbenchAcceptanceList = memo(() => {- const { t } = useTranslation('verify');- const { data, error, isLoading, mutate } = useSWR(- verifyKeys.acceptances(),- () => verifyService.listAcceptances(),- {- revalidateIfStale: false,- revalidateOnFocus: false,- revalidateOnReconnect: false,- },- );- 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 groups = groupAcceptanceList(filtered);- const showGroups = hasProjectAcceptanceGroups(groups);- 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),- }));-- 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('acceptance.workspace.title')}- </Text>- <Flexbox horizontal gap={2}>- <DropdownMenu items={filterItems} placement={'bottomRight'}>- <ActionIcon- active={filter !== 'all'}- icon={ListFilter}- title={t('acceptance.workspace.filters.title')}- />- </DropdownMenu>- </Flexbox>- </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>- ) : filtered.length === 0 ? (- trimmedQuery || filter !== 'all' ? (- <Flexbox className={styles.searchEmpty} gap={12}>- <span>- {trimmedQuery- ? t('acceptance.workspace.filters.noSearchResults', { query: trimmedQuery })- : filter === 'all'- ? null- : t(EMPTY_FILTER_KEYS[filter])}- </span>- <button- className={styles.retry}- type={'button'}- onClick={() => {- setQuery('');- setStoredFilter('all');- }}- >- {t('acceptance.workspace.filters.showAll')}- </button>- </Flexbox>- ) : (- <Center className={styles.emptyState}>- <Empty- description={t('acceptance.workspace.listEmpty')}- icon={ScrollText}- title={t('acceptance.workspace.listEmptyTitle')}- />- </Center>- )- ) : (- <div className={styles.list}>- {showGroups ? (- <Accordion defaultExpandedKeys={groups.map(({ key }) => key)} gap={4}>- {groups.map((group) => (- <AccordionItem- itemKey={group.key}- key={group.key}- paddingBlock={4}- paddingInline={8}- title={- <span className={styles.groupTitle}>- <Icon icon={FolderClosed} size={14} />- <span>- {group.projectName ?? t('acceptance.workspace.groups.ungrouped')} ·{' '}- {group.items.length}- </span>- </span>- }- >- <div className={styles.groupList}>- {group.items.map((item) => (- <AcceptanceRow item={item} key={item.id} onChanged={mutate} />- ))}- </div>- </AccordionItem>- ))}- </Accordion>- ) : (- filtered.map((item) => <AcceptanceRow item={item} key={item.id} onChanged={mutate} />)- )}- </div>- )}- </div>- </Flexbox>- );-});--WorkbenchAcceptanceList.displayName = 'WorkbenchAcceptanceList';--export default WorkbenchAcceptanceList;diff --git a/apps/workbench/src/features/acceptance/AcceptanceRow.tsx b/apps/workbench/src/features/acceptance/AcceptanceRow.tsxdeleted file mode 100644index 44a2968cc1b..00000000000--- a/apps/workbench/src/features/acceptance/AcceptanceRow.tsx+++ /dev/null@@ -1,375 +0,0 @@-'use client';--import type { AcceptanceStatus } from '@lobechat/types';-import type { DropdownItem } from '@lobehub/ui/base-ui';-import { confirmModal, DropdownMenu } from '@lobehub/ui/base-ui';-import ActionIcon from '@lobehub/ui/es/ActionIcon/index';-import { Flexbox } from '@lobehub/ui/es/Flex/index';-import Icon from '@lobehub/ui/es/Icon/index';-import { App } from 'antd';-import { createStaticStyles, cssVar } from 'antd-style';-import dayjs from 'dayjs';-import {- BadgeCheck,- CircleCheck,- CircleDashed,- CircleHelp,- CircleX,- LoaderCircle,- MoreHorizontal,- Pencil,- RefreshCw,- RotateCcw,- Trash2,- X,-} from 'lucide-react';-import { memo, useRef, useState } from 'react';-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';--const styles = createStaticStyles(({ css }) => ({- content: css`- overflow: hidden;- display: flex;- flex: 1;- flex-direction: column;- gap: 2px;-- min-width: 0;-- text-align: start;- `,- editRow: css`- padding-block: 4px;- padding-inline: 4px;- `,- itemSub: css`- font-size: 12px;- color: ${cssVar.colorTextTertiary};- `,- itemTitleInput: css`- width: 100%;- min-width: 0;- height: 32px;- padding-inline: 8px;- border: 1px solid ${cssVar.colorBorder};- border-radius: ${cssVar.borderRadius};-- font-size: 14px;- color: ${cssVar.colorText};-- background: ${cssVar.colorBgContainer};- outline: none;-- &:focus {- border-color: ${cssVar.colorPrimary};- box-shadow: 0 0 0 2px ${cssVar.colorPrimaryBg};- }- `,- main: css`- cursor: pointer;-- display: flex;- flex: 1;- gap: 10px;- align-items: center;-- min-width: 0;- padding: 0;- border: 0;-- color: inherit;-- background: transparent;- `,- row: css`- display: flex;- gap: 6px;- align-items: center;-- min-height: 52px;- padding-block: 7px;- padding-inline: 10px 6px;- border-radius: ${cssVar.borderRadiusLG};-- &:hover {- background: ${cssVar.colorFillTertiary};- }- `,- spin: css`- animation: acceptance-spin 1.1s linear infinite;-- @keyframes acceptance-spin {- to {- transform: rotate(360deg);- }- }- `,- title: css`- overflow: hidden;-- font-size: 14px;- font-weight: 500;- color: ${cssVar.colorText};- text-overflow: ellipsis;- white-space: nowrap;- `,-}));--type Glyph = 'accepted' | 'awaiting' | 'bad' | 'closed' | 'repairing' | 'running' | 'unsure';--const RUNNING_STATUSES = new Set<AcceptanceStatus>([- 'pending',- 'planned',- 'verifying',- 'repairing',-]);--const glyphOf = (status: AcceptanceStatus): Glyph => {- if (status === 'repairing') return 'repairing';- if (RUNNING_STATUSES.has(status)) return 'running';- if (status === 'accepted') return 'accepted';- if (status === 'closed') return 'closed';- if (status === 'rejected') return 'bad';- if (status === 'errored') return 'unsure';- return 'awaiting';-};--const SPINNING_GLYPHS = new Set<Glyph>(['running', 'repairing']);--const glyphMeta: Record<Glyph, { color: string; icon: typeof BadgeCheck }> = {- accepted: { color: cssVar.colorSuccess, icon: BadgeCheck },- awaiting: { color: cssVar.colorInfo, icon: CircleDashed },- bad: { color: cssVar.colorError, icon: CircleX },- closed: { color: cssVar.colorTextTertiary, icon: X },- repairing: { color: cssVar.colorWarning, icon: RefreshCw },- running: { color: cssVar.colorInfo, icon: LoaderCircle },- unsure: { color: cssVar.colorWarning, icon: CircleHelp },-};--const relativeTime = (value?: Date | string | null) => {- if (!value) return '';- const date = dayjs(value);- return dayjs().diff(date, 'day') < 7 ? date.fromNow() : date.format('MMM D');-};--interface AcceptanceRowProps {- item: AcceptanceListItem;- onChanged: () => Promise<unknown> | unknown;-}--const AcceptanceRow = memo<AcceptanceRowProps>(({ item, onChanged }) => {- const { t } = useTranslation('verify');- const { message } = App.useApp();- const navigate = useNavigate();- const [editing, setEditing] = useState(false);- const [mutating, setMutating] = useState(false);- const isSavingRef = useRef(false);-- const glyph = glyphOf(item.status as AcceptanceStatus);- const meta = glyphMeta[glyph];- const title = item.subject.title || item.subjectId;- const [draftTitle, setDraftTitle] = useState(title);-- const refresh = () =>- Promise.all([onChanged(), globalMutate(verifyKeys.acceptanceBundle(item.id))]);-- const commitRename = async () => {- if (isSavingRef.current) return;- const next = draftTitle.trim();- if (!next) {- message.error(t('acceptance.workspace.renameEmpty'));- setDraftTitle(title);- setEditing(false);- return;- }- if (next === title) {- setEditing(false);- return;- }-- isSavingRef.current = true;- setMutating(true);- try {- await verifyService.renameAcceptance(item.id, next);- await refresh();- message.success(t('acceptance.workspace.renameSuccess'));- setEditing(false);- } catch (error) {- console.error('[acceptance:rename]', error);- message.error(t('acceptance.workspace.renameError'));- } finally {- isSavingRef.current = false;- setMutating(false);- }- };-- const changeStatus = async (status: 'accepted' | 'closed' | 'delivered') => {- setMutating(true);- try {- await verifyService.updateAcceptanceStatus(item.id, status);- await refresh();- message.success(t('acceptance.workspace.statusSuccess'));- } catch (error) {- console.error('[acceptance:status]', error);- message.error(t('acceptance.workspace.statusError'));- } finally {- setMutating(false);- }- };-- const statusItems: DropdownItem[] = getAcceptanceStatusActions(item.status).map((action) => {- if (action === 'accept') {- return {- icon: <Icon icon={CircleCheck} />,- key: action,- label: t('acceptance.workspace.actions.markAccepted'),- onClick: () => void changeStatus('accepted'),- };- }- if (action === 'reopen') {- return {- icon: <Icon icon={RotateCcw} />,- key: action,- label: t('acceptance.workspace.actions.reopen'),- onClick: () => void changeStatus('delivered'),- };- }- return {- icon: <Icon icon={X} />,- key: action,- label: t('acceptance.workspace.actions.markClosed'),- onClick: () => void changeStatus('closed'),- };- });-- const menuItems: DropdownItem[] = [- {- icon: <Icon icon={Pencil} />,- key: 'rename',- label: t('acceptance.workspace.actions.rename'),- onClick: () => {- setDraftTitle(title);- setEditing(true);- },- },- ...(statusItems.length > 0- ? [- {- children: statusItems,- icon: <Icon icon={CircleDashed} />,- key: 'status',- label: t('acceptance.workspace.actions.status'),- },- { type: 'divider' as const },- ]- : []),- {- danger: true,- icon: <Icon icon={Trash2} />,- key: 'delete',- label: t('acceptance.workspace.actions.delete'),- onClick: () => {- confirmModal({- cancelText: t('actions.cancel'),- content: t('acceptance.workspace.deleteConfirmDescription', { title }),- okButtonProps: { danger: true },- okText: t('actions.delete'),- onOk: async () => {- setMutating(true);- try {- await verifyService.deleteAcceptance(item.id);- await onChanged();- message.success(t('acceptance.workspace.deleteSuccess'));- } catch (error) {- console.error('[acceptance:delete]', error);- message.error(t('acceptance.workspace.deleteError'));- } finally {- setMutating(false);- }- },- title: t('acceptance.workspace.deleteConfirmTitle'),- });- },- },- ];-- if (editing) {- return (- <div className={styles.editRow}>- <input- autoFocus- className={styles.itemTitleInput}- value={draftTitle}- onBlur={() => void commitRename()}- onChange={(event) => setDraftTitle(event.target.value)}- onFocus={(event) => event.currentTarget.select()}- onKeyDown={(event) => {- if (event.key === 'Enter') {- event.preventDefault();- void commitRename();- }- if (event.key === 'Escape') {- event.preventDefault();- setDraftTitle(title);- setEditing(false);- }- }}- />- </div>- );- }-- return (- <div- className={styles.row}- style={mutating ? { opacity: 0.62, pointerEvents: 'none' } : undefined}- >- <button- className={styles.main}- type={'button'}- onClick={() => navigate(`/acceptance/${item.id}`)}- >- <Icon- className={SPINNING_GLYPHS.has(glyph) ? styles.spin : undefined}- icon={meta.icon}- size={17}- style={{ color: meta.color }}- />- <span className={styles.content}>- <span className={styles.title}>{title}</span>- <Flexbox horizontal className={styles.itemSub} gap={8}>- <span>- {item.checkCount != null- ? t('acceptance.workspace.checkCount', { count: item.checkCount })- : t(`acceptance.status.${item.status}` as any)}- </span>- <span>{relativeTime(item.updatedAt ?? item.createdAt)}</span>- </Flexbox>- </span>- </button>- <DropdownMenu- iconSpaceMode={'group'}- items={menuItems}- placement={'bottomRight'}- popupProps={{ style: { minWidth: 160 } }}- >- <ActionIcon- icon={MoreHorizontal}- size={'small'}- title={t('acceptance.workspace.actions.more')}- />- </DropdownMenu>- </div>- );-});--AcceptanceRow.displayName = 'WorkbenchAcceptanceRow';--export default AcceptanceRow;diff --git a/apps/workbench/src/features/acceptance/WorkspaceSidebar.tsx b/apps/workbench/src/features/acceptance/WorkspaceSidebar.tsxdeleted file mode 100644index f37241b9d25..00000000000--- a/apps/workbench/src/features/acceptance/WorkspaceSidebar.tsx+++ /dev/null@@ -1,132 +0,0 @@-'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/apps/workbench/src/features/verify/VerifyDetail.tsx b/apps/workbench/src/features/verify/VerifyDetail.tsxindex c0958633c25..7ff01b096b0 100644--- a/apps/workbench/src/features/verify/VerifyDetail.tsx+++ b/apps/workbench/src/features/verify/VerifyDetail.tsx@@ -11,7 +11,7 @@ import { useVerifyReportBundle } from '@/features/Verify/hooks';import ReportViewer from '@/features/Verify/ReportViewer';import { extractUuid } from '@/features/Verify/utils';-import WorkbenchBrandLink from '../../shell/WorkbenchBrandLink';+import { WorkbenchHeader } from '../../shell/WorkbenchHeader';import SWRMutateInitializer from '../acceptance/SWRMutateInitializer';const styles = createStaticStyles(({ css }) => ({@@ -45,11 +45,12 @@ const WorkbenchVerifyDetail = memo(() => {return (<Flexbox className={styles.page}><SWRMutateInitializer />- <Flexbox horizontal align={'center'} className={styles.header} gap={8}>- <WorkbenchBrandLink />- <Text ellipsis strong style={{ minWidth: 0 }}>- {data?.run.title ?? t('report.titleFallback')}- </Text>+ <Flexbox className={styles.header} justify={'center'}>+ <WorkbenchHeader>+ <Text ellipsis strong style={{ minWidth: 0 }}>+ {data?.run.title ?? t('report.titleFallback')}+ </Text>+ </WorkbenchHeader></Flexbox><div className={styles.body}><ReportViewer />diff --git a/apps/workbench/src/features/verify/VerifyList.tsx b/apps/workbench/src/features/verify/VerifyList.tsxindex 0bb54047bb8..c7cb92602c5 100644--- a/apps/workbench/src/features/verify/VerifyList.tsx+++ b/apps/workbench/src/features/verify/VerifyList.tsx@@ -13,7 +13,7 @@ import useSWR from 'swr';import { verifyKeys } from '@/libs/swr/keys';import { verifyService } from '@/services/verify';-import WorkbenchBrandLink from '../../shell/WorkbenchBrandLink';+import { WorkbenchHeader } from '../../shell/WorkbenchHeader';import VerifyRow from './VerifyRow';const styles = createStaticStyles(({ css }) => ({@@ -119,12 +119,11 @@ const WorkbenchVerifyList = memo(() => {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 }}>+ <WorkbenchHeader>+ <Text strong style={{ fontSize: 17 }}>{t('workspace.title')}</Text>- </Flexbox>+ </WorkbenchHeader><label className={styles.search}><Icon color={cssVar.colorTextQuaternary} icon={Search} size={15} /><inputdiff --git a/apps/workbench/src/router.tsx b/apps/workbench/src/router.tsxindex 75fdba8f0d2..b35f91c7736 100644--- a/apps/workbench/src/router.tsx+++ b/apps/workbench/src/router.tsx@@ -85,7 +85,7 @@ export const workbenchRoutes: RouteObject[] = [{children: [{- element: lazyElement(() => import('./routes/acceptance')),+ element: <ExitWorkbench />,index: true,},{diff --git a/apps/workbench/src/routes/acceptance/index.tsx b/apps/workbench/src/routes/acceptance/index.tsxdeleted file mode 100644index 9efce276093..00000000000--- a/apps/workbench/src/routes/acceptance/index.tsx+++ /dev/null@@ -1,3 +0,0 @@-'use client';--export { default } from '../../features/acceptance/AcceptanceList';diff --git a/apps/workbench/src/shell/WorkbenchBrandLink.tsx b/apps/workbench/src/shell/WorkbenchBrandLink.tsxindex 93bac6f0fd6..0ae7e1702c3 100644--- a/apps/workbench/src/shell/WorkbenchBrandLink.tsx+++ b/apps/workbench/src/shell/WorkbenchBrandLink.tsx@@ -28,134 +28,22 @@ const styles = createStaticStyles(({ css }) => ({`,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 WorkbenchBrandLink = memo(() => {const { t } = useTranslation('verify');- const label = t('actions.backToApp', { name: BRANDING_NAME });+ const label = t('actions.goToApp', { name: BRANDING_NAME });return (<><a aria-label={label} className={styles.brand} href={'/'} title={label}><ProductLogo size={22} /></a>- {divider ? <WorkbenchBrandDivider /> : null}+ <div className={styles.divider} /></>);});diff --git a/apps/workbench/src/shell/WorkbenchHeader.test.ts b/apps/workbench/src/shell/WorkbenchHeader.test.tsnew file mode 100644index 00000000000..e7868e96949--- /dev/null+++ b/apps/workbench/src/shell/WorkbenchHeader.test.ts@@ -0,0 +1,37 @@+import { readFileSync } from 'node:fs';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++const dir = import.meta.dirname;+const header = readFileSync(path.join(dir, 'WorkbenchHeader.tsx'), 'utf8');+const brand = readFileSync(path.join(dir, 'WorkbenchBrandLink.tsx'), 'utf8');++const pageFiles = [+ '../features/acceptance/AcceptanceDetail.tsx',+ '../features/verify/VerifyDetail.tsx',+ '../features/verify/VerifyList.tsx',+] as const;++describe('WorkbenchHeader', () => {+ it('sends guests into the app with a single primary CTA', () => {+ expect(header).toContain("href={'/'}");+ expect(header).toContain("t('actions.goToApp'");+ expect(header).toContain("type={'primary'}");+ expect(header).not.toContain('/signin');+ expect(header).not.toContain('/signup');+ });++ it('labels the brand as entering the app, not returning to it', () => {+ expect(brand).toContain("t('actions.goToApp'");+ expect(brand).not.toContain("t('actions.backToApp'");+ expect(brand).toContain("href={'/'}");+ });++ it.each(pageFiles)('is mounted on %s', (relativePath) => {+ const source = readFileSync(path.join(dir, relativePath), 'utf8');++ expect(source).toContain('WorkbenchHeader');+ expect(source).not.toContain('WorkbenchBrandLink');+ });+});diff --git a/apps/workbench/src/shell/WorkbenchHeader.tsx b/apps/workbench/src/shell/WorkbenchHeader.tsxnew file mode 100644index 00000000000..1bd777b738a--- /dev/null+++ b/apps/workbench/src/shell/WorkbenchHeader.tsx@@ -0,0 +1,38 @@+'use client';++import { BRANDING_NAME } from '@lobechat/business-const';+import { Button } from '@lobehub/ui/base-ui';+import { Flexbox } from '@lobehub/ui/es/Flex/index';+import { createStaticStyles } from 'antd-style';+import type { ReactNode } from 'react';+import { useTranslation } from 'react-i18next';++import WorkbenchBrandLink from './WorkbenchBrandLink';++const styles = createStaticStyles(({ css }) => ({+ cta: css`+ flex: none;+ `,+ title: css`+ flex: 1;+ min-width: 0;+ `,+}));++interface WorkbenchHeaderProps {+ children?: ReactNode;+}++export const WorkbenchHeader = ({ children }: WorkbenchHeaderProps) => {+ const { t } = useTranslation('verify');++ return (+ <Flexbox horizontal align={'center'} gap={8} width={'100%'}>+ <WorkbenchBrandLink />+ <div className={styles.title}>{children}</div>+ <Button className={styles.cta} href={'/'} type={'primary'}>+ {t('actions.goToApp', { name: BRANDING_NAME })}+ </Button>+ </Flexbox>+ );+};diff --git a/apps/workbench/src/shell/WorkbenchShell.tsx b/apps/workbench/src/shell/WorkbenchShell.tsxindex e2713510275..3298edd55a7 100644--- a/apps/workbench/src/shell/WorkbenchShell.tsx+++ b/apps/workbench/src/shell/WorkbenchShell.tsx@@ -4,46 +4,27 @@ import { ModalHost, ToastHost, TooltipGroup } from '@lobehub/ui/base-ui';import { StyleProvider } from 'antd-style';import { memo, type PropsWithChildren } from 'react';-import { ServerConfigStoreProvider } from '@/store/serverConfig/Provider';-import type { SPAServerConfig } from '@/types/spaServerConfig';-import WorkbenchLocale from './WorkbenchLocale';import WorkbenchTheme from './WorkbenchTheme';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 WorkbenchShell = memo<WorkbenchShellProps>(({ children, resources, locale: localeProp }) => {const locale =- props.locale ??+ localeProp ??(typeof document === 'undefined' ? 'en-US' : document.documentElement.lang || 'en-US');return (<WorkbenchLocale defaultLang={locale} resources={resources}><WorkbenchTheme>- <ServerConfigStoreProvider- isMobile- featureFlags={serverConfig?.featureFlags}- serverConfig={serverConfig?.config}- >- <TooltipGroup layoutAnimation={false}>- <StyleProvider speedy={import.meta.env.PROD}>{children}</StyleProvider>- </TooltipGroup>- <ModalHost />- <ToastHost />- </ServerConfigStoreProvider>+ <TooltipGroup layoutAnimation={false}>+ <StyleProvider speedy={import.meta.env.PROD}>{children}</StyleProvider>+ </TooltipGroup>+ <ModalHost />+ <ToastHost /></WorkbenchTheme></WorkbenchLocale>);diff --git a/apps/workbench/vite.config.rr.mts b/apps/workbench/vite.config.rr.mtsindex a308a4a3e1a..3d7db424396 100644--- a/apps/workbench/vite.config.rr.mts+++ b/apps/workbench/vite.config.rr.mts@@ -11,6 +11,9 @@ 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 { shikiCdnUrl } from './app/stubs/shikiCdn';+import { isShikiSource } from './app/stubs/shikiSource';+import { reportStubSurfaceGaps } from './app/stubs/surface';import { antdStaticCssOptions, themeVarsCssOptions } from './staticCssOptions.mjs';const repoRoot = path.resolve(import.meta.dirname, '../..');@@ -22,6 +25,11 @@ const define = {const { 'process.env': _processEnvFallback, ...ssrDefine } = define;+const shikiSsrStub = path.resolve(import.meta.dirname, 'app/stubs/shiki.ts');+const shikiVersion = JSON.parse(+ readFileSync(path.resolve(repoRoot, 'node_modules/shiki/package.json'), 'utf8'),+).version as string;+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'),@@ -37,8 +45,9 @@ const workbenchSsrStubs = (): Plugin => ({applyToEnvironment: (environment) => environment.name === 'ssr',enforce: 'pre',name: 'workbench-ssr-stubs',- resolveId(source) {- return ssrStubs[source];+ resolveId(source, importer) {+ if (ssrStubs[source]) return ssrStubs[source];+ if (isShikiSource(source, importer)) return shikiSsrStub;},});@@ -48,6 +57,7 @@ const i18nClientStub = path.resolve();const clientStubs: Record<string, string> = {+ '@/libs/trpc/client': path.resolve(import.meta.dirname, 'app/stubs/trpcClient.client.ts'),'@/utils/i18n/loadI18nNamespaceModule': i18nClientStub,};@@ -60,6 +70,17 @@ const workbenchClientStubs = (): Plugin => ({},});+const workbenchClientShikiCdn = (): Plugin => ({+ applyToEnvironment: (environment) => environment.name === 'client',+ enforce: 'pre',+ name: 'workbench-client-shiki-cdn',+ resolveId(source) {+ const url = shikiCdnUrl(source, shikiVersion);+ if (!url) return;+ return { external: true, id: url };+ },+});+// 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.@@ -72,6 +93,41 @@ const I18N_NS_PATTERNS = [];const I18N_NS_ARRAY_PATTERN = /useTranslation\(\s*\[([^\]]*)\]/g;+const stubSurfaceGuard = (env: 'client' | 'ssr', stubs: Record<string, string>): Plugin => ({+ apply: 'build',+ applyToEnvironment: (environment) => environment.name === env,+ buildEnd() {+ const stubEntries = Object.entries(stubs).map(([specifier, file]) => ({+ source: readFileSync(file, 'utf8'),+ specifier,+ }));+ const files: Array<{ rel: string; source: 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 (!/\.[cm]?[jt]sx?$/.test(file)) continue;+ const rel = path.relative(repoRoot, file);+ if (rel.startsWith('apps/workbench/app/stubs/')) continue;+ let source: string;+ try {+ source = readFileSync(file, 'utf8');+ } catch {+ continue;+ }+ files.push({ rel, source });+ }+ const lines = reportStubSurfaceGaps(files, stubEntries);+ if (lines.length > 0) {+ this.error(+ `Workbench ${env} stub is missing APIs used by the module graph:\n${lines.join('\n')}\n` ++ `Add the export/member to the matching file in app/stubs/ (empty state or reject), ` ++ `or keep the importer off this graph.`,+ );+ }+ },+ name: `workbench-${env}-stub-surface-guard`,+});+const clientI18nNsGuard = (): Plugin => ({apply: 'build',applyToEnvironment: (environment) => environment.name === 'client',@@ -253,6 +309,9 @@ export default defineConfig({: undefined,workbenchSsrStubs(),workbenchClientStubs(),+ workbenchClientShikiCdn(),+ stubSurfaceGuard('ssr', ssrStubs),+ stubSurfaceGuard('client', clientStubs),clientI18nNsGuard(),buildInputsManifest(),viteMarkdownImport(),@@ -264,6 +323,9 @@ export default defineConfig({reactRouter(),...lobeIconImports(),],+ optimizeDeps: {+ exclude: ['shiki', '@shikijs/core', '@shikijs/stream', '@shikijs/transformers'],+ },resolve: {tsconfigPaths: true,},diff --git a/locales/en-US/verify.json b/locales/en-US/verify.jsonindex 852258deda3..f8749758446 100644--- a/locales/en-US/verify.json+++ b/locales/en-US/verify.json@@ -288,6 +288,7 @@"actions.backToApp": "Back to {{name}}","actions.cancel": "Cancel","actions.delete": "Delete",+ "actions.goToApp": "Go to {{name}}","badge.errored": "Check could not run","badge.failed": "Check failed","badge.passed": "Check passed",diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.jsonindex 84111845589..215e456f233 100644--- a/locales/zh-CN/verify.json+++ b/locales/zh-CN/verify.json@@ -288,6 +288,7 @@"actions.backToApp": "返回 {{name}}","actions.cancel": "取消","actions.delete": "删除",+ "actions.goToApp": "前往 {{name}}","badge.errored": "检查无法运行","badge.failed": "检查未通过","badge.passed": "检查通过",diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.tsindex 6fb3b4759ab..828293ce644 100644--- a/packages/locales/src/default/verify.ts+++ b/packages/locales/src/default/verify.ts@@ -321,6 +321,7 @@ export default {'acceptance.workspace.statusSuccess': 'Status updated','acceptance.workspace.title': 'Deliveries','actions.backToApp': 'Back to {{name}}',+ 'actions.goToApp': 'Go to {{name}}','meta.description': 'Verification runs, delivery reports, and acceptance reviews.','actions.cancel': 'Cancel','actions.delete': 'Delete',diff --git a/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx b/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsxindex 4bfe458455b..83e99b452fd 100644--- a/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx+++ b/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx@@ -172,7 +172,7 @@ describe('Link Render — message link icon toggle', () => {});describe('Link Render — internal entities', () => {- it('hard-navigates acceptance pages into the Workbench runtime', () => {+ it('opens acceptance links in the conversation portal', () => {const assign = vi.spyOn(window.location, 'assign').mockImplementation(() => undefined);const { getByRole } = renderLink({@@ -183,9 +183,9 @@ describe('Link Render — internal entities', () => {fireEvent.click(getByRole('link', { name: 'Acceptance' }));- expect(assign).toHaveBeenCalledWith('/acceptance/acceptance-1');+ expect(mockOpenAcceptance).toHaveBeenCalledWith('acceptance-1');+ expect(assign).not.toHaveBeenCalled();expect(mockNavigate).not.toHaveBeenCalled();- expect(mockOpenAcceptance).not.toHaveBeenCalled();});it('opens official document links in the conversation portal', () => {diff --git a/src/features/Portal/Acceptance/Body.test.tsx b/src/features/Portal/Acceptance/Body.test.tsxindex 92d0f86a9d7..6a809cc2cf1 100644--- a/src/features/Portal/Acceptance/Body.test.tsx+++ b/src/features/Portal/Acceptance/Body.test.tsx@@ -45,7 +45,7 @@ vi.mock('@/store/task', () => ({selector({ closeTopicDrawer: () => {}, openTopicDrawer: () => {} }),}));-vi.mock('./TopicPanel', () => ({ default: () => null }));+vi.mock('@/features/Verify/Acceptance/TopicPanel', () => ({ default: () => null }));describe('Portal Acceptance Body — draftToComposer via the global bus', () => {beforeEach(() => {diff --git a/src/features/Portal/Acceptance/Body.tsx b/src/features/Portal/Acceptance/Body.tsxindex c2e04798edd..5684abbac90 100644--- a/src/features/Portal/Acceptance/Body.tsx+++ b/src/features/Portal/Acceptance/Body.tsx@@ -6,12 +6,11 @@ import {OriginConversationProvider,type OriginConversationSlot,} from '@/features/Verify';+import TopicPanel from '@/features/Verify/Acceptance/TopicPanel';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);diff --git a/src/features/Verify/Acceptance/AcceptanceCheckInventory.tsx b/src/features/Verify/Acceptance/AcceptanceCheckInventory.tsxnew file mode 100644index 00000000000..f74c366bed0--- /dev/null+++ b/src/features/Verify/Acceptance/AcceptanceCheckInventory.tsx@@ -0,0 +1,309 @@+'use client';++import { ActionIcon, Flexbox, Text } from '@lobehub/ui';+import { Select } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, useResponsive } from 'antd-style';+import { ChevronsDownUp, ChevronsUpDown } from 'lucide-react';+import type { ReactNode } from 'react';+import { useCallback, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useSearchParams } from 'react-router';++import { useSingleton } from '@/hooks/useSingleton';+import { mutate as globalMutate } from '@/libs/swr';+import { verifyKeys } from '@/libs/swr/keys';+import { verifyService } from '@/services/verify';++import { useAcceptanceScope } from './AcceptanceScope';+import CheckList, {+ type CheckFilter,+ checkFilterState,+ groupChecks,+ hasVisualEvidence,+ isException,+ isGroupFullyAccepted,+ shouldGroupChecks,+ userReviewState,+} from './CheckList';+import { EMPTY_ID_SET, setAggregateEntry } from './expandState';+import { useAcceptanceBundle } from './useAcceptanceBundle';++const styles = createStaticStyles(({ css }) => ({+ countBadge: css`+ padding-block: 1px;+ padding-inline: 7px;+ border-radius: 99px;++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorFillTertiary};+ `,+}));++interface AcceptanceCheckInventoryProps {+ canReview?: boolean;+ children?: ReactNode;+ onOpenTrace?: (verifierOperationId: string) => void | Promise<void>;+ toolbar?: ReactNode;+}++const AcceptanceCheckInventory = ({+ canReview = false,+ children,+ onOpenTrace,+ toolbar,+}: AcceptanceCheckInventoryProps) => {+ const { t } = useTranslation('verify');+ const { lg = true } = useResponsive();+ const { acceptanceId, embedded } = useAcceptanceScope();+ const compactToolbar = embedded || !lg;+ const { data, mutate } = useAcceptanceBundle(acceptanceId);+ const [searchParams, setSearchParams] = useSearchParams();+ const [localFilter, setLocalFilter] = useState<CheckFilter>('all');+ const urlFilterRaw = searchParams.get('filter');+ const urlFilter: CheckFilter = (+ ['all', 'pending', 'needsFix', 'accepted', 'ignored'] as const+ ).includes(urlFilterRaw as CheckFilter)+ ? (urlFilterRaw as CheckFilter)+ : 'all';+ const filter = embedded ? localFilter : urlFilter;+ const setFilter = (next: CheckFilter) => {+ if (embedded) {+ setLocalFilter(next);+ return;+ }+ setSearchParams(+ (prev) => {+ const params = new URLSearchParams(prev);+ if (next === 'all') params.delete('filter');+ else params.set('filter', next);+ return params;+ },+ { replace: true },+ );+ };+ const [roundFilter, setRoundFilter] = useState<number | null>(null);+ const [expandedById, setExpandedById] = useState<Map<string, Set<string>>>(() => new Map());+ const [collapsedById, setCollapsedById] = useState<Map<string, Set<string>>>(() => new Map());+ const expanded = expandedById.get(acceptanceId) ?? EMPTY_ID_SET;+ const collapsedGroups = collapsedById.get(acceptanceId) ?? EMPTY_ID_SET;+ const setExpanded = useCallback(+ (update: Set<string> | ((prev: Set<string>) => Set<string>)) =>+ setExpandedById((map) => setAggregateEntry(map, acceptanceId, update)),+ [acceptanceId],+ );+ const setCollapsedGroups = useCallback(+ (update: Set<string> | ((prev: Set<string>) => Set<string>)) =>+ setCollapsedById((map) => setAggregateEntry(map, acceptanceId, update)),+ [acceptanceId],+ );+ const seededIds = useSingleton(() => new Set<string>());++ useEffect(() => {+ if (!data || data.checks.length === 0) return;+ if (seededIds.has(acceptanceId)) return;+ seededIds.add(acceptanceId);+ setExpanded(+ new Set(+ data.checks+ .filter(+ (check) =>+ userReviewState(check) !== 'accepted' &&+ (isException(check) || hasVisualEvidence(check)),+ )+ .map((check) => check.id),+ ),+ );+ setCollapsedGroups(+ shouldGroupChecks(data.checks.length)+ ? new Set(+ groupChecks(data.checks, t('acceptance.group.uncategorized'))+ .filter((group) => isGroupFullyAccepted(group.checks))+ .map((group) => group.key),+ )+ : new Set(),+ );+ const defaultFilter: CheckFilter = data.rounds.length > 1 ? 'pending' : 'all';+ if (embedded) {+ setLocalFilter(defaultFilter);+ } else if (!urlFilterRaw && defaultFilter !== 'all') {+ setSearchParams(+ (prev) => {+ const params = new URLSearchParams(prev);+ params.set('filter', defaultFilter);+ return params;+ },+ { replace: true },+ );+ }+ }, [+ acceptanceId,+ data,+ embedded,+ seededIds,+ setCollapsedGroups,+ setExpanded,+ setSearchParams,+ t,+ urlFilterRaw,+ ]);++ if (!data) return null;++ const checks = data.checks;+ const counts = {+ accepted: checks.filter((check) => checkFilterState(check) === 'accepted').length,+ ignored: checks.filter((check) => checkFilterState(check) === 'ignored').length,+ needsFix: checks.filter((check) => checkFilterState(check) === 'needsFix').length,+ pending: checks.filter((check) => checkFilterState(check) === 'pending').length,+ total: checks.length,+ };+ const grouped = shouldGroupChecks(checks.length);+ const groupKeys = grouped+ ? groupChecks(checks, t('acceptance.group.uncategorized')).map((group) => group.key)+ : [];+ const allGroupsCollapsed =+ groupKeys.length > 0 && groupKeys.every((key) => collapsedGroups.has(key));+ const groupFeedback = data.rounds.flatMap((round) =>+ (round.run.decisionDetail?.groupFeedback ?? []).map((entry) => ({+ ...entry,+ roundIndex: round.run.roundIndex ?? 0,+ })),+ );+ const currentRound = data.rounds.at(-1)?.run.roundIndex ?? 0;++ return (+ <>+ <Flexbox horizontal align={'center'} gap={8} wrap={compactToolbar ? 'nowrap' : 'wrap'}>+ <Text strong style={{ fontSize: 14, whiteSpace: 'nowrap' }}>+ {t('acceptance.checks.title')}+ </Text>+ <span className={styles.countBadge}>{counts.total}</span>+ <Flexbox flex={1} />+ {toolbar}+ <Select+ size={'small'}+ style={{ height: 34, width: 118 }}+ value={filter}+ variant={'filled'}+ options={[+ { label: t('acceptance.filter.all', { count: counts.total }), value: 'all' },+ { label: t('acceptance.filter.pending', { count: counts.pending }), value: 'pending' },+ {+ label: t('acceptance.filter.needsFix', { count: counts.needsFix }),+ value: 'needsFix',+ },+ {+ label: t('acceptance.filter.accepted', { count: counts.accepted }),+ value: 'accepted',+ },+ { label: t('acceptance.filter.ignored', { count: counts.ignored }), value: 'ignored' },+ ]}+ onChange={(value) => setFilter(value as CheckFilter)}+ />+ {data.rounds.length > 1 && canReview && (+ <Select+ size={'small'}+ style={{ height: 34, width: 110 }}+ value={roundFilter === null ? 'all' : String(roundFilter)}+ variant={'filled'}+ options={[+ { label: t('acceptance.filter.roundAll'), value: 'all' },+ ...[...data.rounds].reverse().map((round) => ({+ label: t('acceptance.round', { round: round.run.roundIndex }),+ value: String(round.run.roundIndex),+ })),+ ]}+ onChange={(value) => setRoundFilter(value === 'all' ? null : Number(value))}+ />+ )}+ {grouped && (+ <ActionIcon+ icon={allGroupsCollapsed ? ChevronsUpDown : ChevronsDownUp}+ size={'small'}+ title={+ allGroupsCollapsed+ ? t('acceptance.group.expandAll')+ : t('acceptance.group.collapseAll')+ }+ onClick={() => setCollapsedGroups(allGroupsCollapsed ? new Set() : new Set(groupKeys))}+ />+ )}+ </Flexbox>+ {children}+ <CheckList+ canReview={canReview}+ checks={checks}+ collapsedGroups={collapsedGroups}+ currentRound={currentRound}+ expanded={expanded}+ filter={filter}+ groupFeedback={groupFeedback}+ reviewPending={false}+ round={roundFilter}+ onOpenTrace={onOpenTrace}+ onDismissProposal={+ canReview+ ? async (input) => {+ await verifyService.adjudicateProposal({+ adjudication: input.adjudication,+ id: data.acceptance.id,+ predictionId: input.predictionId,+ });+ await mutate();+ void globalMutate(verifyKeys.acceptances());+ }+ : undefined+ }+ onGroupFeedback={async (category, comment, fileIds) => {+ if (!canReview) return false;+ await verifyService.addGroupFeedback({+ category,+ comment,+ fileIds: fileIds.length > 0 ? fileIds : undefined,+ id: data.acceptance.id,+ });+ await mutate();+ void globalMutate(verifyKeys.acceptances());+ return true;+ }}+ onReview={async (input) => {+ if (!canReview) return false;+ await verifyService.reviewChecks({ id: data.acceptance.id, ...input });+ await mutate();+ void globalMutate(verifyKeys.acceptances());+ return true;+ }}+ onToggleGroup={(key) =>+ setCollapsedGroups((previous) => {+ const next = new Set(previous);+ if (next.has(key)) next.delete(key);+ else next.add(key);+ return next;+ })+ }+ onToggleGroupItems={(ids, open) =>+ setExpanded((previous) => {+ const next = new Set(previous);+ for (const id of ids) {+ if (open) next.add(id);+ else next.delete(id);+ }+ return next;+ })+ }+ onToggleItem={(id) =>+ setExpanded((previous) => {+ const next = new Set(previous);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ })+ }+ />+ </>+ );+};++export default AcceptanceCheckInventory;diff --git a/src/features/Verify/Acceptance/AcceptanceCheckOwnerToolbar.tsx b/src/features/Verify/Acceptance/AcceptanceCheckOwnerToolbar.tsxnew file mode 100644index 00000000000..f9d3155f020--- /dev/null+++ b/src/features/Verify/Acceptance/AcceptanceCheckOwnerToolbar.tsx@@ -0,0 +1,82 @@+'use client';++import { ActionIcon } from '@lobehub/ui';+import { toast } from '@lobehub/ui/base-ui';+import { Plus, Sparkles } from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import { mutate as globalMutate } from '@/libs/swr';+import { verifyKeys } from '@/libs/swr/keys';+import { verifyService } from '@/services/verify';++import { useAcceptanceScope } from './AcceptanceScope';+import { openAddCheckModal } from './AddCheckModal';+import { hasVisualEvidence } from './CheckList';+import { useAcceptanceBundle } from './useAcceptanceBundle';++const PREDICT_POLL_INTERVAL_MS = 4000;+const PREDICT_POLL_ATTEMPTS = 30;++const AcceptanceCheckOwnerToolbar = () => {+ const { t } = useTranslation('verify');+ const { acceptanceId } = useAcceptanceScope();+ const { data, mutate } = useAcceptanceBundle(acceptanceId);+ const [predicting, setPredicting] = useState(false);+ if (!data?.isOwner) return null;++ const standing = data.acceptance.config?.checklist ?? [];+ const predictableCount = data.checks.filter(+ (check) => check.result && !check.result.userDecision && hasVisualEvidence(check),+ ).length;++ const saveStanding = async (checklist: typeof standing) => {+ await verifyService.saveAcceptanceChecklist(data.subject.type, data.subject.id, checklist);+ await mutate();+ void globalMutate(verifyKeys.acceptances());+ toast.success(t('acceptance.checkCreate.saved'));+ };++ return (+ <>+ {predictableCount > 0 && (+ <ActionIcon+ icon={Sparkles}+ loading={predicting}+ size={'small'}+ title={t('acceptance.proposal.request')}+ onClick={async () => {+ setPredicting(true);+ try {+ const { queued } = await verifyService.predictReviews(data.acceptance.id);+ if (queued === 0) return;+ for (let attempt = 0; attempt < PREDICT_POLL_ATTEMPTS; attempt += 1) {+ await new Promise((resolve) => setTimeout(resolve, PREDICT_POLL_INTERVAL_MS));+ const next = await mutate();+ const settled = (next?.checks ?? []).filter(+ (check) => check.prediction || check.result?.userDecision,+ ).length;+ if (settled >= queued) break;+ }+ } finally {+ setPredicting(false);+ }+ }}+ />+ )}+ <ActionIcon+ icon={Plus}+ size={'small'}+ title={t('acceptance.checkCreate.title')}+ onClick={() =>+ openAddCheckModal({+ existingIds: standing.map((item) => item.id),+ onSubmit: (items) => saveStanding([...standing, ...items]),+ })+ }+ />+ </>+ );+};++export default AcceptanceCheckOwnerToolbar;diff --git a/src/features/Verify/Acceptance/AcceptanceDecision.tsx b/src/features/Verify/Acceptance/AcceptanceDecision.tsxnew file mode 100644index 00000000000..d1aa96796e3--- /dev/null+++ b/src/features/Verify/Acceptance/AcceptanceDecision.tsx@@ -0,0 +1,257 @@+'use client';++import { copyToClipboard, Flexbox } from '@lobehub/ui';+import { toast } from '@lobehub/ui/base-ui';+import dayjs from 'dayjs';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useIsHydrated } from '@/hooks/useIsHydrated';+import { mutate as globalMutate } from '@/libs/swr';+import { verifyKeys } from '@/libs/swr/keys';+import { verifyService } from '@/services/verify';++import { useAcceptanceScope } from './AcceptanceScope';+import { checkFilterState, isException } from './CheckList';+import { buildRepairPrompt } from './checkWork';+import DecisionBar from './DecisionBar';+import FeedbackDrawer, { type FeedbackListEntry } from './FeedbackDrawer';+import { openAcceptModal, openGroupFeedbackModal, openRejectModal } from './modals';+import { useAcceptanceBundle } from './useAcceptanceBundle';+import { formatAcceptanceCountsText, LIVE_ACCEPTANCE_STATUSES } from './verdict';++interface AcceptanceDecisionProps {+ onDraftToComposer?: (text: string) => boolean;+}++const AcceptanceDecision = ({ onDraftToComposer }: AcceptanceDecisionProps) => {+ const { t } = useTranslation('verify');+ const hydrated = useIsHydrated();+ const { acceptanceId, embedded } = useAcceptanceScope();+ const { data, mutate } = useAcceptanceBundle(acceptanceId);+ const [pending, setPending] = useState(false);+ const [rerunPending, setRerunPending] = useState(false);+ const [feedbackOpen, setFeedbackOpen] = useState(false);+ if (!data?.isOwner || data.acceptance.status === 'closed') return null;++ const { acceptance, checks, origin, rounds } = data;+ const currentRound = rounds.at(-1);+ const acceptedCount = checks.filter((check) => checkFilterState(check) === 'accepted').length;+ const needsFixCount = checks.filter((check) => checkFilterState(check) === 'needsFix').length;+ const ignoredCount = checks.filter((check) => checkFilterState(check) === 'ignored').length;+ const reviewTotal = checks.length;+ const pendingCount = reviewTotal - acceptedCount - needsFixCount - ignoredCount;+ const decidedCount = acceptedCount + needsFixCount + ignoredCount;+ const countsText = formatAcceptanceCountsText(t, {+ failed: checks.filter((check) => check.state === 'failed').length,+ notExecuted: checks.filter((check) => check.state === 'not_executed').length,+ passed: checks.filter((check) => check.state === 'passed').length,+ uncertain: checks.filter((check) => check.state === 'uncertain').length,+ });+ const barState = LIVE_ACCEPTANCE_STATUSES.has(acceptance.status)+ ? ('live' as const)+ : acceptance.status === 'accepted'+ ? ('accepted' as const)+ : acceptance.status === 'rejected'+ ? ('rejected' as const)+ : ('settled' as const);+ const barTexts = {+ accepted: {+ statusText: t('acceptance.banner.accepted', {+ time:+ hydrated && acceptance.completedAt+ ? dayjs(acceptance.completedAt).format('YYYY-MM-DD HH:mm')+ : '',+ }),+ subText: `${countsText} · ${t('acceptance.banner.acceptedHint', { count: rounds.length })}`,+ },+ live: {+ statusText: t(`acceptance.status.${acceptance.status}`),+ subText: t('acceptance.banner.liveHint'),+ },+ rejected: {+ statusText: t('acceptance.banner.rejected'),+ subText: currentRound?.run.decisionDetail?.comment ?? t('acceptance.banner.rejectedHint'),+ },+ settled:+ decidedCount === 0+ ? {+ statusText: t('acceptance.bar.progressZero', { total: reviewTotal }),+ subText: undefined,+ }+ : pendingCount === 0+ ? needsFixCount === 0+ ? {+ statusText: t('acceptance.bar.progressDone', { total: reviewTotal }),+ subText: undefined,+ }+ : {+ statusText: t('acceptance.bar.needsFix', { count: needsFixCount }),+ subText: undefined,+ }+ : {+ statusText: t('acceptance.bar.progress', {+ done: decidedCount,+ rest: pendingCount,+ total: reviewTotal,+ }),+ subText: undefined,+ },+ }[barState];++ const currentRoundIndex = currentRound?.run.roundIndex ?? 0;+ const groupFeedbackEntries = rounds.flatMap((round) =>+ (round.run.decisionDetail?.groupFeedback ?? []).map((entry) => ({+ ...entry,+ roundIndex: round.run.roundIndex ?? 0,+ })),+ );+ const feedbackEntries: FeedbackListEntry[] = [+ ...checks.flatMap((check) =>+ check.reviews+ .filter((review) => review.action === 'reject')+ .map((review) => ({+ annotationCount: review.annotations?.length || undefined,+ attachments: review.attachments,+ checkId: check.id,+ checkSeq: check.seq,+ comment: review.comment ?? '',+ createdAt: review.createdAt,+ kind: 'check' as const,+ roundIndex: review.roundIndex,+ stale: review.roundIndex < currentRoundIndex,+ title: check.title,+ })),+ ),+ ...groupFeedbackEntries.map((entry) => ({+ attachments: entry.attachments,+ comment: entry.comment,+ createdAt: entry.createdAt,+ groupLabel: entry.category,+ kind: 'group' as const,+ roundIndex: entry.roundIndex,+ stale: entry.roundIndex < currentRoundIndex,+ })),+ ].sort((a, b) => b.createdAt.localeCompare(a.createdAt));++ const runAction = async (action: () => Promise<unknown>) => {+ setPending(true);+ try {+ await action();+ await mutate();+ void globalMutate(verifyKeys.acceptances());+ return true;+ } finally {+ setPending(false);+ }+ };++ const repairPrompt = buildRepairPrompt(acceptance.id);++ return (+ <>+ <DecisionBar+ acceptedCount={acceptedCount}+ embedded={embedded}+ feedbackCount={feedbackEntries.filter((entry) => !entry.stale).length}+ ignoredCount={ignoredCount}+ needsFixCount={needsFixCount}+ pending={pending}+ repairing={acceptance.status === 'repairing'}+ rerunAvailable={embedded || Boolean(origin?.topic)}+ rerunPending={rerunPending}+ state={barState}+ statusText={barTexts.statusText}+ subText={barTexts.subText}+ totalCount={reviewTotal}+ onOpenFeedback={() => setFeedbackOpen(true)}+ onAccept={() =>+ openAcceptModal({+ exceptions: checks.filter((check) => isException(check)).map((check) => check.title),+ onConfirm: () => runAction(() => verifyService.acceptDelivery(acceptance.id)),+ subjectTitle: data.subject.title ?? data.subject.id,+ })+ }+ onAddComment={() =>+ openGroupFeedbackModal({+ description: t('acceptance.bar.addCommentDescription'),+ groupLabel: t('acceptance.feedback.global'),+ onConfirm: (comment, fileIds) =>+ runAction(() =>+ verifyService.addGroupFeedback({+ category: '',+ comment,+ fileIds: fileIds.length > 0 ? fileIds : undefined,+ id: acceptance.id,+ }),+ ).then(Boolean),+ title: t('acceptance.bar.addComment'),+ })+ }+ onCopyReview={async () => {+ await copyToClipboard(repairPrompt);+ toast.success({+ placement: 'bottom',+ style: { marginBlockEnd: 88 },+ title: t('acceptance.bar.copied'),+ });+ }}+ onRejectComment={() =>+ openRejectModal({+ onConfirm: (comment) =>+ runAction(() => verifyService.rejectDelivery(acceptance.id, comment)),+ })+ }+ onRerun={async () => {+ if (embedded) {+ if (onDraftToComposer?.(repairPrompt)) {+ toast.success({+ placement: 'bottom',+ style: { marginBlockEnd: 88 },+ title: t('acceptance.bar.rerunDrafted'),+ });+ }+ return;+ }+ if (!origin?.topic) return;+ setRerunPending(true);+ try {+ await verifyService.dispatchAcceptanceRepair({+ agentId: origin.agent?.id,+ content: repairPrompt,+ topicId: origin.topic.id,+ });+ await verifyService.markAcceptanceRepairing(acceptance.id);+ await mutate();+ void globalMutate(verifyKeys.acceptances());+ toast.success({+ placement: 'bottom',+ style: { marginBlockEnd: 88 },+ title: t('acceptance.bar.rerunSent'),+ });+ } catch (cause) {+ toast.error(cause instanceof Error ? cause.message : t('acceptance.actionError'));+ } finally {+ setRerunPending(false);+ }+ }}+ />+ <Flexbox style={{ height: 8 }} />+ <FeedbackDrawer+ entries={feedbackEntries}+ open={feedbackOpen}+ onClose={() => setFeedbackOpen(false)}+ onJumpToCheck={(checkId) => {+ setFeedbackOpen(false);+ setTimeout(() => {+ document+ .querySelector(`[data-check-row="${checkId}"]`)+ ?.scrollIntoView({ behavior: 'smooth', block: 'center' });+ }, 80);+ }}+ />+ </>+ );+};++export default AcceptanceDecision;diff --git a/src/features/Verify/Acceptance/AcceptanceEnterFocus.tsx b/src/features/Verify/Acceptance/AcceptanceEnterFocus.tsxnew file mode 100644index 00000000000..63699454516--- /dev/null+++ b/src/features/Verify/Acceptance/AcceptanceEnterFocus.tsx@@ -0,0 +1,35 @@+'use client';++import { Icon } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { ChevronRight } from 'lucide-react';+import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router';++import { useAcceptanceScope } from './AcceptanceScope';+import { acceptanceCheckPath } from './routes';+import { useAcceptanceBundle } from './useAcceptanceBundle';++const AcceptanceEnterFocus = () => {+ const { t } = useTranslation('verify');+ const navigate = useNavigate();+ const { acceptanceId, embedded } = useAcceptanceScope();+ const { data } = useAcceptanceBundle(acceptanceId);+ if (embedded || !data || data.checks.length === 0) return null;++ return (+ <Button+ icon={<Icon icon={ChevronRight} />}+ size={'small'}+ style={{ alignSelf: 'flex-start' }}+ type={'text'}+ onClick={() =>+ navigate(acceptanceCheckPath(acceptanceId, data.checks[0]!.id), { replace: true })+ }+ >+ {t('acceptance.focus.enter')}+ </Button>+ );+};++export default AcceptanceEnterFocus;diff --git a/src/features/Verify/Acceptance/AcceptanceFocusReview.tsx b/src/features/Verify/Acceptance/AcceptanceFocusReview.tsxnew file mode 100644index 00000000000..48e6baca6db--- /dev/null+++ b/src/features/Verify/Acceptance/AcceptanceFocusReview.tsx@@ -0,0 +1,372 @@+'use client';++import type { AcceptanceChecklistItem } from '@lobechat/types';+import { Flexbox, Icon, Tag, Text } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import {+ ArrowLeft,+ BadgeCheck,+ Ban,+ Check,+ ChevronRight,+ CircleDashed,+ HelpCircle,+ PencilLine,+ Plus,+ RotateCcw,+ XCircle,+} from 'lucide-react';+import { useTranslation } from 'react-i18next';++import NavItem from '@/features/NavPanel/components/NavItem';++import AcceptanceStatusPill from './AcceptanceStatusPill';+import {+ type AcceptanceCheck,+ checkFilterState,+ type CheckReviewInput,+ FocusedCheckDetails,+ focusedCheckStates,+ isCheckWorkActionable,+ type ProposalDismissInput,+} from './CheckList';+import { acceptanceFocusedLayout, acceptanceScrollLayout } from './layout';++const styles = createStaticStyles(({ css }) => ({+ countBadge: css`+ padding-block: 1px;+ padding-inline: 7px;+ border-radius: 99px;++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorFillTertiary};+ `,+ layout: css`+ display: grid;+ grid-template-columns: 320px minmax(0, 1fr);++ @media (width > 900px) {+ flex: 1;+ min-height: 0;+ }++ @media (width <= 900px) {+ grid-template-columns: 1fr;+ }+ `,+ outline: css`+ position: sticky;+ inset-block-start: 0;++ padding: 8px;+ border-inline-end: 1px solid ${cssVar.colorBorderSecondary};++ background: ${cssVar.colorFillQuaternary};++ @media (width <= 900px) {+ position: static;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ border-inline-end: 0;+ }+ `,+ outlineList: css`+ overflow: ${acceptanceScrollLayout.paneOverflow};++ > * {+ flex-shrink: 0;+ }+ `,+ main: css`+ overflow: ${acceptanceScrollLayout.paneOverflow};+ min-width: 0;+ padding-block: ${acceptanceFocusedLayout.contentPaddingBlock};+ padding-inline: 32px;+ `,+ content: css`+ width: min(880px, 100%);+ margin-inline: auto;+ `,+ work: css`+ padding: 16px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};+ background: ${cssVar.colorFillQuaternary};+ `,+}));++interface AcceptanceFocusReviewProps {+ canReview: boolean;+ checks: AcceptanceCheck[];+ focusedCheck: AcceptanceCheck;+ onAddChecks?: () => void;+ onBack: () => void;+ onCheckWork?: () => void;+ onDismissProposal?: (input: ProposalDismissInput) => Promise<void>;+ onEditStandingCheck?: (item: AcceptanceChecklistItem) => void;+ onReview: (input: CheckReviewInput) => Promise<boolean>;+ onRound?: (round: number) => void;+ onSelectCheck: (id: string) => void;+ orderedChecks: AcceptanceCheck[];+ reviewPending: boolean;+ roundCount: number;+ standingChecks?: AcceptanceChecklistItem[];+ status: string;+ subjectTitle: string;+}++const AcceptanceFocusReview = ({+ canReview,+ checks,+ focusedCheck,+ onAddChecks,+ onBack,+ onCheckWork,+ onDismissProposal,+ onEditStandingCheck,+ onReview,+ onRound,+ onSelectCheck,+ orderedChecks,+ reviewPending,+ roundCount,+ standingChecks = [],+ status,+ subjectTitle,+}: AcceptanceFocusReviewProps) => {+ const { t } = useTranslation('verify');+ const focusedStates = focusedCheckStates(focusedCheck);++ return (+ <div className={styles.layout}>+ <Flexbox className={styles.outline}>+ <Flexbox flex={'none'} gap={10} paddingBlock={8} paddingInline={4}>+ <Button+ icon={<Icon icon={ArrowLeft} />}+ size={'small'}+ style={{ alignSelf: 'flex-start' }}+ type={'text'}+ onClick={onBack}+ >+ {t('acceptance.focus.back')}+ </Button>+ <Flexbox gap={4} paddingInline={4}>+ <Text strong style={{ fontSize: 15 }}>+ {subjectTitle}+ </Text>+ <Flexbox horizontal align={'center'} gap={6}>+ <AcceptanceStatusPill size={12} status={status} />+ <Text fontSize={11} type={'secondary'}>+ {t('acceptance.roundCount', { count: roundCount })}+ </Text>+ </Flexbox>+ </Flexbox>+ <Flexbox horizontal align={'center'} gap={8} paddingInline={4}>+ <Text strong style={{ fontSize: 13 }}>+ {t('acceptance.checks.title')}+ </Text>+ <span className={styles.countBadge}>{checks.length + standingChecks.length}</span>+ <Flexbox flex={1} />+ {onAddChecks && (+ <Button+ icon={<Icon icon={Plus} />}+ size={'small'}+ type={'text'}+ onClick={onAddChecks}+ >+ {t('acceptance.checkCreate.title')}+ </Button>+ )}+ </Flexbox>+ </Flexbox>+ <Flexbox className={styles.outlineList} flex={1}>+ {orderedChecks.map((check) => {+ const state = checkFilterState(check);+ const icon =+ state === 'accepted'+ ? BadgeCheck+ : state === 'needsFix'+ ? RotateCcw+ : state === 'ignored'+ ? Ban+ : CircleDashed;+ const color =+ state === 'accepted' ? 'success' : state === 'needsFix' ? 'error' : 'default';++ return (+ <NavItem+ active={check.id === focusedCheck.id}+ extra={<Icon color={cssVar.colorTextQuaternary} icon={ChevronRight} size={14} />}+ key={check.id}+ paddingBlock={acceptanceFocusedLayout.outlineItemPaddingBlock}+ paddingInline={acceptanceFocusedLayout.outlineItemPaddingInline}+ title={check.title}+ titleColor={cssVar.colorText}+ description={+ <Flexbox horizontal align={'center'} gap={8}>+ <Tag color={color} icon={<Icon icon={icon} />} size={'small'}>+ {t(`acceptance.focus.state.${state}`)}+ </Tag>+ <Text fontSize={12} type={'secondary'}>+ {t('acceptance.focus.evidenceCount', { count: check.evidence.length })}+ </Text>+ </Flexbox>+ }+ slots={{+ titlePrefix: (+ <Flexbox align={'center'} height={22} style={{ alignSelf: 'flex-start' }}>+ <Text+ style={{+ color: cssVar.colorTextQuaternary,+ fontFamily: cssVar.fontFamilyCode,+ fontSize: 11,+ }}+ >+ C{check.seq}+ </Text>+ </Flexbox>+ ),+ }}+ onClick={() => onSelectCheck(check.id)}+ />+ );+ })}+ {standingChecks.length > 0 && onEditStandingCheck && (+ <Flexbox gap={4} paddingBlock={8} paddingInline={8}>+ <Text fontSize={11} type={'secondary'}>+ {t('acceptance.checkCreate.pendingGroup')}+ </Text>+ {standingChecks.map((item) => (+ <NavItem+ extra={<Icon color={cssVar.colorTextQuaternary} icon={PencilLine} />}+ key={item.id}+ paddingBlock={acceptanceFocusedLayout.outlineItemPaddingBlock}+ paddingInline={acceptanceFocusedLayout.outlineItemPaddingInline}+ title={item.name}+ titleColor={cssVar.colorText}+ description={+ <Text fontSize={12} type={'secondary'}>+ {item.method || t('acceptance.checkCreate.pendingDescription')}+ </Text>+ }+ onClick={() => onEditStandingCheck(item)}+ />+ ))}+ </Flexbox>+ )}+ </Flexbox>+ </Flexbox>++ <Flexbox className={styles.main}>+ <Flexbox className={styles.content} gap={16}>+ <Flexbox gap={acceptanceFocusedLayout.headerGap}>+ <Flexbox+ horizontal+ align={'center'}+ gap={5}+ style={{+ color:+ focusedStates.review === 'accepted'+ ? cssVar.colorSuccess+ : focusedStates.review === 'needsFix'+ ? cssVar.colorError+ : focusedStates.review === 'ignored'+ ? cssVar.colorTextQuaternary+ : cssVar.colorTextTertiary,+ fontSize: 12,+ }}+ >+ <Icon+ size={14}+ icon={+ focusedStates.review === 'accepted'+ ? BadgeCheck+ : focusedStates.review === 'needsFix'+ ? RotateCcw+ : focusedStates.review === 'ignored'+ ? Ban+ : CircleDashed+ }+ />+ {t(`acceptance.focus.state.${focusedStates.review}`)}+ <Text style={{ color: cssVar.colorTextQuaternary }}>·</Text>+ <Flexbox+ horizontal+ align={'center'}+ gap={5}+ style={{+ color:+ focusedStates.verifier === 'passed'+ ? cssVar.colorSuccess+ : focusedStates.verifier === 'failed'+ ? cssVar.colorError+ : focusedStates.verifier === 'uncertain'+ ? cssVar.colorWarning+ : cssVar.colorTextQuaternary,+ }}+ >+ <Icon+ size={14}+ icon={+ focusedStates.verifier === 'passed'+ ? Check+ : focusedStates.verifier === 'failed'+ ? XCircle+ : focusedStates.verifier === 'uncertain'+ ? HelpCircle+ : CircleDashed+ }+ />+ {t('acceptance.focus.verifierLabel')} ·{' '}+ {t(`report.verdict.${focusedStates.verifierLabel}`)}+ </Flexbox>+ </Flexbox>+ <Flexbox horizontal align={'baseline'} gap={8}>+ <Text+ style={{+ color: cssVar.colorTextTertiary,+ flex: 'none',+ fontFamily: cssVar.fontFamilyCode,+ fontSize: 12,+ }}+ >+ C{focusedCheck.seq}+ </Text>+ <Text as={'h2'} style={{ fontSize: 22, margin: 0 }}>+ {focusedCheck.title}+ </Text>+ </Flexbox>+ <Text fontSize={13} type={'secondary'}>+ {t(`acceptance.focus.verifierDescription.${focusedStates.verifierLabel}`)}+ </Text>+ </Flexbox>+ {onCheckWork && isCheckWorkActionable(focusedCheck) && (+ <Flexbox horizontal align={'center'} className={styles.work} gap={16}>+ <Flexbox flex={1} gap={3}>+ <Text strong>{t('acceptance.checkWork.title')}</Text>+ <Text fontSize={12} type={'secondary'}>+ {t('acceptance.checkWork.description')}+ </Text>+ </Flexbox>+ <Button type={'primary'} onClick={onCheckWork}>+ {t('acceptance.checkWork.copy')}+ </Button>+ </Flexbox>+ )}+ <FocusedCheckDetails+ canReview={canReview}+ check={focusedCheck}+ reviewPending={reviewPending}+ onDismissProposal={onDismissProposal}+ onReview={onReview}+ onRound={onRound}+ />+ </Flexbox>+ </Flexbox>+ </div>+ );+};++export default AcceptanceFocusReview;diff --git a/src/features/Verify/Acceptance/AcceptanceFocusWorkspace.tsx b/src/features/Verify/Acceptance/AcceptanceFocusWorkspace.tsxnew file mode 100644index 00000000000..187437ce872--- /dev/null+++ b/src/features/Verify/Acceptance/AcceptanceFocusWorkspace.tsx@@ -0,0 +1,113 @@+'use client';++import { copyToClipboard } from '@lobehub/ui';+import { toast } from '@lobehub/ui/base-ui';+import { useTranslation } from 'react-i18next';+import { useNavigate, useParams } from 'react-router';++import { mutate as globalMutate } from '@/libs/swr';+import { verifyKeys } from '@/libs/swr/keys';+import { verifyService } from '@/services/verify';++import AcceptanceFocusReview from './AcceptanceFocusReview';+import { useAcceptanceScope } from './AcceptanceScope';+import { openAddCheckModal } from './AddCheckModal';+import { type CheckFilter, checkFilterState } from './CheckList';+import { copyCheckRepairPrompt } from './checkWork';+import { acceptanceCheckPath, acceptanceOverviewPath } from './routes';+import { useAcceptanceBundle } from './useAcceptanceBundle';++const CHECK_REVIEW_ORDER: Record<Exclude<CheckFilter, 'all'>, number> = {+ pending: 0,+ needsFix: 1,+ accepted: 2,+ ignored: 3,+};++const AcceptanceFocusWorkspace = () => {+ const { t } = useTranslation('verify');+ const navigate = useNavigate();+ const params = useParams<{ checkId?: string }>();+ const { acceptanceId } = useAcceptanceScope();+ const { data, mutate } = useAcceptanceBundle(acceptanceId);+ const focusedCheck = data?.checks.find((check) => check.id === params.checkId);+ if (!data || !focusedCheck) return null;++ const orderedChecks = [...data.checks].sort(+ (a, b) =>+ CHECK_REVIEW_ORDER[checkFilterState(a)] - CHECK_REVIEW_ORDER[checkFilterState(b)] ||+ a.seq - b.seq,+ );+ const standing = (data.acceptance.config?.checklist ?? []).filter(+ (item) => !data.checks.some((check) => check.id === item.id),+ );++ const saveStanding = async (checklist: typeof standing) => {+ await verifyService.saveAcceptanceChecklist(data.subject.type, data.subject.id, checklist);+ await mutate();+ void globalMutate(verifyKeys.acceptances());+ toast.success(t('acceptance.checkCreate.saved'));+ };++ return (+ <AcceptanceFocusReview+ canReview={data.isOwner}+ checks={data.checks}+ focusedCheck={focusedCheck}+ orderedChecks={orderedChecks}+ reviewPending={false}+ roundCount={data.rounds.length}+ standingChecks={standing}+ status={data.acceptance.status}+ subjectTitle={data.subject.title ?? data.subject.id}+ onBack={() => navigate(acceptanceOverviewPath(acceptanceId), { replace: true })}+ onSelectCheck={(id) => navigate(acceptanceCheckPath(acceptanceId, id), { replace: true })}+ onAddChecks={+ data.isOwner+ ? () =>+ openAddCheckModal({+ existingIds: (data.acceptance.config?.checklist ?? []).map((item) => item.id),+ onSubmit: (items) =>+ saveStanding([...(data.acceptance.config?.checklist ?? []), ...items]),+ })+ : undefined+ }+ onCheckWork={+ data.isOwner && data.acceptance.status !== 'closed'+ ? async () => {+ await copyCheckRepairPrompt(data.acceptance.id, focusedCheck, copyToClipboard);+ toast.success({ title: t('acceptance.checkWork.copied') });+ }+ : undefined+ }+ onEditStandingCheck={+ data.isOwner+ ? async (item) => {+ const { openCheckEditModal } =+ await import('@/features/Conversation/ChatInput/VerifyTray/EditModal');+ const checklist = data.acceptance.config?.checklist ?? [];+ openCheckEditModal({+ initial: { ...item, method: item.method ?? '' },+ onRemove: () =>+ void saveStanding(checklist.filter((check) => check.id !== item.id)),+ onSubmit: (value) =>+ saveStanding(+ checklist.map((check) =>+ check.id === item.id ? { ...check, ...value } : check,+ ),+ ),+ });+ }+ : undefined+ }+ onReview={async (input) => {+ await verifyService.reviewChecks({ id: data.acceptance.id, ...input });+ await mutate();+ void globalMutate(verifyKeys.acceptances());+ return true;+ }}+ />+ );+};++export default AcceptanceFocusWorkspace;diff --git a/src/features/Verify/Acceptance/AcceptanceGoal.tsx b/src/features/Verify/Acceptance/AcceptanceGoal.tsxnew file mode 100644index 00000000000..e77febf2aee--- /dev/null+++ b/src/features/Verify/Acceptance/AcceptanceGoal.tsx@@ -0,0 +1,181 @@+'use client';++import { ActionIcon, Flexbox, Icon, Text } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { ChevronsDownUp, ChevronsUpDown, GitBranch, GitCommitHorizontal } from 'lucide-react';+import type { ReactNode } from 'react';+import { useTranslation } from 'react-i18next';++import { useLocalStorageState } from '@/hooks/useLocalStorageState';++import { useAcceptanceScope } from './AcceptanceScope';+import { acceptanceCodingScope } from './codingScope';+import { useAcceptanceBundle } from './useAcceptanceBundle';++const GOAL_COLLAPSED_STORAGE_KEY = 'lobehub-acceptance-goal-collapsed';++const styles = createStaticStyles(({ css }) => ({+ card: css`+ overflow: hidden;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};+ background: ${cssVar.colorBgContainer};++ &:hover [data-goal-toggle='true'] {+ pointer-events: auto;+ opacity: 1;+ }+ `,+ goalToggle: css`+ pointer-events: none;+ opacity: 0;+ transition: opacity ${cssVar.motionDurationMid};++ &:focus-visible {+ pointer-events: auto;+ opacity: 1;+ }++ @media (hover: none) {+ pointer-events: auto;+ opacity: 1;+ }+ `,+ requirementLabel: css`+ font-size: 12px;+ font-weight: 500;+ color: ${cssVar.colorTextTertiary};+ letter-spacing: 0.04em;+ `,+ scopeChip: css`+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ `,+ scopeLink: css`+ cursor: pointer;+ color: ${cssVar.colorTextSecondary};++ &:hover {+ color: ${cssVar.colorText};+ text-decoration: underline;+ }+ `,+ summaryClamp: css`+ overflow: hidden;+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 3;++ line-height: 1.6;+ `,+ viewReportLink: css`+ cursor: pointer;+ font-size: 12px;+ color: ${cssVar.colorTextQuaternary};++ &:hover {+ color: ${cssVar.colorTextSecondary};+ }+ `,+}));++interface AcceptanceGoalProps {+ editSlot?: ReactNode;+ reportSlot?: ReactNode;+}++const AcceptanceGoal = ({ editSlot, reportSlot }: AcceptanceGoalProps) => {+ const { t } = useTranslation('verify');+ const { acceptanceId } = useAcceptanceScope();+ const { data } = useAcceptanceBundle(acceptanceId);+ const [collapsed, setCollapsed] = useLocalStorageState(GOAL_COLLAPSED_STORAGE_KEY, false);+ if (!data) return null;++ const requirement = data.acceptance.requirement;+ const latestSummary = data.latestReport?.summary;+ const currentRound = data.rounds.at(-1);+ const roundLabel = currentRound+ ? t('acceptance.round', { round: currentRound.run.roundIndex })+ : undefined;+ const scope = acceptanceCodingScope(data.rounds);+ const emptyLabel = editSlot+ ? t('acceptance.requirementEmptyEditable')+ : t('acceptance.requirementEmpty');+ const showContext = Boolean(latestSummary || scope);++ return (+ <Flexbox+ className={styles.card}+ gap={collapsed ? 0 : 12}+ paddingBlock={collapsed ? 8 : 12}+ paddingInline={collapsed ? 12 : 16}+ >+ <Flexbox horizontal align={'center'} gap={4}>+ <Text className={styles.requirementLabel}>{t('acceptance.requirementLabel')}</Text>+ {!collapsed && editSlot}+ {collapsed && (+ <Text+ ellipsis+ fontSize={13}+ style={{ flex: 1, minWidth: 0 }}+ title={requirement ?? emptyLabel}+ >+ {requirement ?? emptyLabel}+ </Text>+ )}+ {!collapsed && <Flexbox flex={1} />}+ <ActionIcon+ data-goal-toggle+ className={styles.goalToggle}+ icon={collapsed ? ChevronsUpDown : ChevronsDownUp}+ size={'small'}+ title={t(collapsed ? 'acceptance.goalExpand' : 'acceptance.goalCollapse')}+ onClick={() => setCollapsed((value) => !value)}+ />+ </Flexbox>+ {!collapsed &&+ (requirement ? (+ <Text style={{ fontSize: 15, lineHeight: 1.7 }}>{requirement}</Text>+ ) : (+ <Text style={{ fontSize: 15, lineHeight: 1.7 }}>{emptyLabel}</Text>+ ))}+ {!collapsed && showContext && (+ <Flexbox+ gap={8}+ paddingBlock={'12px 0'}+ style={{ borderBlockStart: `1px solid ${cssVar.colorBorderSecondary}` }}+ >+ <Flexbox horizontal align={'center'} gap={8}>+ <Text fontSize={12} type={'secondary'}>+ {t('acceptance.latestSummary')}+ {roundLabel ? ` · ${roundLabel}` : ''}+ </Text>+ <Flexbox flex={1} />+ {reportSlot}+ </Flexbox>+ {latestSummary && (+ <Text className={styles.summaryClamp} fontSize={13} type={'secondary'}>+ {latestSummary}+ </Text>+ )}+ {scope && (+ <Flexbox horizontal align={'center'} gap={16} wrap={'wrap'}>+ {scope.branch && (+ <Flexbox horizontal align={'center'} className={styles.scopeChip} gap={4}>+ <Icon icon={GitBranch} size={13} /> {scope.branch}+ </Flexbox>+ )}+ {scope.commit && (+ <Flexbox horizontal align={'center'} className={styles.scopeChip} gap={4}>+ <Icon icon={GitCommitHorizontal} size={13} /> {scope.commit.slice(0, 10)}+ </Flexbox>+ )}+ </Flexbox>+ )}+ </Flexbox>+ )}+ </Flexbox>+ );+};++export default AcceptanceGoal;diff --git a/src/features/Verify/Acceptance/AcceptanceGoalEdit.tsx b/src/features/Verify/Acceptance/AcceptanceGoalEdit.tsxnew file mode 100644index 00000000000..162775b0a29--- /dev/null+++ b/src/features/Verify/Acceptance/AcceptanceGoalEdit.tsx@@ -0,0 +1,49 @@+'use client';++import { ActionIcon } from '@lobehub/ui';+import { toast } from '@lobehub/ui/base-ui';+import { PencilLine } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { mutate as globalMutate } from '@/libs/swr';+import { verifyKeys } from '@/libs/swr/keys';+import { verifyService } from '@/services/verify';++import { useAcceptanceScope } from './AcceptanceScope';+import { useAcceptanceBundle } from './useAcceptanceBundle';++const AcceptanceGoalEdit = () => {+ const { t } = useTranslation('verify');+ const { acceptanceId } = useAcceptanceScope();+ const { data, mutate } = useAcceptanceBundle(acceptanceId);+ if (!data?.isOwner) return null;++ const handleEdit = async () => {+ const { openGoalModal } =+ await import('@/features/Conversation/ChatInput/VerifyTray/GoalModal');+ openGoalModal({+ initialGoal: data.acceptance.requirement ?? undefined,+ onSubmit: async (goal) => {+ try {+ await verifyService.saveAcceptanceGoal(data.subject.type, data.subject.id, goal);+ } catch (cause) {+ toast.error(cause instanceof Error ? cause.message : t('acceptance.actionError'));+ throw cause;+ }+ await mutate();+ void globalMutate(verifyKeys.acceptances());+ },+ });+ };++ return (+ <ActionIcon+ icon={PencilLine}+ size={'small'}+ title={t('acceptance.goalEdit')}+ onClick={handleEdit}+ />+ );+};++export default AcceptanceGoalEdit;diff --git a/src/features/Verify/Acceptance/AcceptanceIdentity.tsx b/src/features/Verify/Acceptance/AcceptanceIdentity.tsxnew file mode 100644index 00000000000..2dd34c6ebd3--- /dev/null+++ b/src/features/Verify/Acceptance/AcceptanceIdentity.tsx@@ -0,0 +1,125 @@+'use client';++import { Avatar, Flexbox, Icon, Tag, Text } from '@lobehub/ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import dayjs from 'dayjs';+import { GitPullRequest } from 'lucide-react';+import type { ReactNode } from 'react';+import { useTranslation } from 'react-i18next';++import { useIsHydrated } from '@/hooks/useIsHydrated';++import { useAcceptanceScope } from './AcceptanceScope';+import AcceptanceStatusPill from './AcceptanceStatusPill';+import { acceptanceCodingScope } from './codingScope';+import { useAcceptanceBundle } from './useAcceptanceBundle';+import { formatAcceptanceCountsText } from './verdict';++const styles = createStaticStyles(({ css }) => ({+ scopeChip: css`+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ `,+ scopeLink: css`+ cursor: pointer;+ color: ${cssVar.colorTextSecondary};++ &:hover {+ color: ${cssVar.colorText};+ text-decoration: underline;+ }+ `,+}));++interface AcceptanceIdentityProps {+ statusSlot?: ReactNode;+ topicSlot?: ReactNode;+}++const AcceptanceIdentity = ({ statusSlot, topicSlot }: AcceptanceIdentityProps) => {+ const { t } = useTranslation('verify');+ const hydrated = useIsHydrated();+ const { acceptanceId, embedded } = useAcceptanceScope();+ const { data } = useAcceptanceBundle(acceptanceId);+ if (!data) return null;++ const { acceptance, checks, origin, rounds, subject } = data;+ const currentRound = rounds.at(-1);+ const scope = acceptanceCodingScope(rounds);+ const pullRequest = scope?.pullRequest;+ const countsText = formatAcceptanceCountsText(t, {+ failed: checks.filter((check) => check.state === 'failed').length,+ notExecuted: checks.filter((check) => check.state === 'not_executed').length,+ passed: checks.filter((check) => check.state === 'passed').length,+ uncertain: checks.filter((check) => check.state === 'uncertain').length,+ });+ const latestAt =+ hydrated && currentRound+ ? t('acceptance.verdict.latestAt', {+ time: dayjs(currentRound.run.createdAt).format('MM-DD HH:mm'),+ })+ : undefined;+ const originAgent = embedded ? null : origin?.agent;+ const showOrigin = Boolean(originAgent || topicSlot || pullRequest?.number);++ return (+ <Flexbox gap={10}>+ <Flexbox horizontal align={'center'} gap={10} wrap={'wrap'}>+ {statusSlot ?? <AcceptanceStatusPill status={acceptance.status} />}+ <Text fontSize={12} type={'secondary'}>+ {[countsText, latestAt].filter(Boolean).join(' · ')}+ </Text>+ </Flexbox>++ <Flexbox horizontal align={'center'} gap={10}>+ <Text as={'h1'} style={{ fontSize: 18, margin: 0 }}>+ {subject.title ?? subject.id}+ </Text>+ <Tag size={'small'}>{t(`acceptance.subject.${subject.type}`)}</Tag>+ </Flexbox>++ {showOrigin && (+ <Flexbox horizontal align={'center'} gap={16} wrap={'wrap'}>+ {originAgent && (+ <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>+ )}+ {topicSlot}+ {pullRequest?.number ? (+ pullRequest.url ? (+ <a+ className={cx(styles.scopeChip, styles.scopeLink)}+ href={pullRequest.url}+ rel={'noreferrer'}+ target={'_blank'}+ title={pullRequest.title ?? pullRequest.url}+ >+ <Flexbox horizontal align={'center'} gap={4}>+ <Icon icon={GitPullRequest} size={13} /> #{pullRequest.number}+ </Flexbox>+ </a>+ ) : (+ <Flexbox horizontal align={'center'} className={styles.scopeChip} gap={4}>+ <Icon icon={GitPullRequest} size={13} /> #{pullRequest.number}+ </Flexbox>+ )+ ) : null}+ </Flexbox>+ )}+ </Flexbox>+ );+};++export default AcceptanceIdentity;diff --git a/src/features/Verify/Acceptance/AcceptanceLedgerRail.tsx b/src/features/Verify/Acceptance/AcceptanceLedgerRail.tsxnew file mode 100644index 00000000000..83d6f41d1b0--- /dev/null+++ b/src/features/Verify/Acceptance/AcceptanceLedgerRail.tsx@@ -0,0 +1,176 @@+'use client';++import { ActionIcon, DraggablePanel, Flexbox } from '@lobehub/ui';+import { Drawer } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, useResponsive } from 'antd-style';+import { PanelRightOpen } from 'lucide-react';+import { useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useParams, useSearchParams } from 'react-router';++import ReportViewer from '../ReportViewer';+import { resolveRoundParam } from '../utils';+import { useAcceptanceScope } from './AcceptanceScope';+import { checkFilterState } from './CheckList';+import LedgerPanel, { type AcceptanceRound } from './LedgerPanel';+import { useOriginConversation } from './originConversation';+import { useAcceptanceBundle } from './useAcceptanceBundle';+import { canViewAcceptanceHistory } from './visibility';++const styles = createStaticStyles(({ css }) => ({+ toggle: css`+ position: absolute;+ z-index: 10;+ inset-block-start: 16px;+ inset-inline-end: 16px;++ border: 1px solid ${cssVar.colorBorderSecondary};++ background: ${cssVar.colorBgContainer};++ &:hover {+ border-color: ${cssVar.colorBorder};+ }+ `,+}));++const AcceptanceLedgerRail = () => {+ const { t } = useTranslation('verify');+ const { lg = true } = useResponsive();+ const isNarrowViewport = !lg;+ const params = useParams<{ checkId?: string }>();+ const [searchParams, setSearchParams] = useSearchParams();+ const { acceptanceId, embedded } = useAcceptanceScope();+ const { data } = useAcceptanceBundle(acceptanceId);+ const originConversation = useOriginConversation();+ const [expand, setExpand] = useState(!embedded);+ const [topicPanelOpen, setTopicPanelOpen] = useState(false);+ const highlightRound = null;+ const focused = Boolean(params.checkId);++ useEffect(() => {+ if (isNarrowViewport) setExpand(false);+ }, [isNarrowViewport]);++ useEffect(() => {+ if (focused) setExpand(false);+ }, [focused]);++ if (!data || !canViewAcceptanceHistory(data.isOwner)) return null;++ const urlRoundRaw = searchParams.get('r');+ const reportRound = embedded ? null : resolveRoundParam(data.rounds, urlRoundRaw);+ const reviewableChecks = data.checks;+ const reviewByRound = (() => {+ const map = new Map<number, { accepted: number; total: number }>();+ for (const check of reviewableChecks) {+ const round = check.resultRound;+ if (round === undefined || round === null) continue;+ const cur = map.get(round) ?? { accepted: 0, total: 0 };+ cur.total += 1;+ if (checkFilterState(check) === 'accepted') cur.accepted += 1;+ map.set(round, cur);+ }+ return map;+ })();++ const openReport = (round: AcceptanceRound | null) => {+ if (embedded) return;+ setSearchParams(+ (prev) => {+ const next = new URLSearchParams(prev);+ if (round?.run.roundIndex == null) next.delete('r');+ else next.set('r', String(round.run.roundIndex));+ return next;+ },+ { replace: true },+ );+ };++ const TopicPanel = originConversation?.TopicPanel;+ const origin = data.origin;+ const topic =+ topicPanelOpen && origin?.agent?.id && origin.topic && TopicPanel ? (+ <TopicPanel+ agentId={origin.agent.id}+ title={origin.topic.title ?? data.subject.title ?? origin.topic.id}+ topicId={origin.topic.id}+ onCollapse={() => setExpand(false)}+ onBack={() => {+ setTopicPanelOpen(false);+ originConversation?.closeTopicDrawer();+ }}+ />+ ) : null;++ const ledger = (+ <LedgerPanel+ highlight={highlightRound}+ reviewByRound={reviewByRound}+ rounds={data.rounds}+ onCollapse={() => setExpand(false)}+ onOpenReport={openReport}+ />+ );++ return (+ <>+ {!focused && !expand && (+ <ActionIcon+ className={styles.toggle}+ icon={PanelRightOpen}+ size={'small'}+ title={t('acceptance.ledger.expand')}+ onClick={() => setExpand(true)}+ />+ )}+ {isNarrowViewport ? (+ <Drawer+ noHeader+ closable={false}+ containerMaxWidth={'100%'}+ open={expand}+ placement={'right'}+ styles={{ bodyContent: { padding: 0 } }}+ width={'min(340px, 88vw)'}+ onClose={() => setExpand(false)}+ >+ {topic ?? ledger}+ </Drawer>+ ) : (+ <DraggablePanel+ stableLayout+ defaultSize={{ width: 340 }}+ expand={expand}+ minWidth={300}+ placement={'right'}+ style={{ flex: 'none', height: '100%' }}+ onExpandChange={setExpand}+ >+ <Flexbox style={{ height: '100%', minHeight: 0, overflow: 'hidden' }}>+ {topic ?? <Flexbox style={{ height: '100%', overflow: 'auto' }}>{ledger}</Flexbox>}+ </Flexbox>+ </DraggablePanel>+ )}+ <Drawer+ noHeader+ containerMaxWidth={'100%'}+ open={reportRound !== null}+ placement={'right'}+ width={'min(960px, 92vw)'}+ styles={{+ bodyContent: { height: '100%', minHeight: 0, overflow: 'hidden', padding: 0 },+ }}+ onClose={() => openReport(null)}+ >+ {reportRound && (+ <Flexbox style={{ height: '100%', position: 'relative' }}>+ <ReportViewer runId={reportRound.run.id} />+ </Flexbox>+ )}+ </Drawer>+ </>+ );+};++export default AcceptanceLedgerRail;diff --git a/src/features/Verify/Acceptance/AcceptanceOriginTopic.tsx b/src/features/Verify/Acceptance/AcceptanceOriginTopic.tsxnew file mode 100644index 00000000000..c1fa26c80b6--- /dev/null+++ b/src/features/Verify/Acceptance/AcceptanceOriginTopic.tsx@@ -0,0 +1,58 @@+'use client';++import { createStaticStyles, cssVar, cx } from 'antd-style';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { useAcceptanceScope } from './AcceptanceScope';+import { useOriginConversation } from './originConversation';+import { useAcceptanceBundle } from './useAcceptanceBundle';++const styles = createStaticStyles(({ css }) => ({+ chip: css`+ cursor: pointer;++ padding: 0;+ border: 0;++ font: inherit;+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};++ background: none;++ &:hover {+ color: ${cssVar.colorText};+ text-decoration: underline;+ }+ `,+}));++const AcceptanceOriginTopic = () => {+ const { t } = useTranslation('verify');+ const { acceptanceId, embedded } = useAcceptanceScope();+ const { data } = useAcceptanceBundle(acceptanceId);+ const originConversation = useOriginConversation();+ const openTopic = useCallback(() => {+ if (!originConversation || !data?.origin?.topic) return;+ originConversation.openTopicDrawer(data.origin.topic.id, {+ agentId: data.origin.agent?.id,+ title: data.origin.topic.title ?? data.subject.title ?? data.origin.topic.id,+ });+ }, [data, originConversation]);++ if (embedded || !data?.origin?.topic || !originConversation) return null;++ return (+ <button+ className={cx(styles.chip)}+ title={t('acceptance.origin.openTopic')}+ type={'button'}+ onClick={openTopic}+ >+ {data.origin.topic.title ?? data.subject.title ?? data.origin.topic.id}+ </button>+ );+};++export default AcceptanceOriginTopic;diff --git a/src/features/Verify/Acceptance/AcceptanceScope.tsx b/src/features/Verify/Acceptance/AcceptanceScope.tsxnew file mode 100644index 00000000000..73ed6a38661--- /dev/null+++ b/src/features/Verify/Acceptance/AcceptanceScope.tsx@@ -0,0 +1,67 @@+'use client';++import { Center, Empty } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { createContext, type ReactNode, use } from 'react';+import { useTranslation } from 'react-i18next';++import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';++import { useAcceptanceBundle } from './useAcceptanceBundle';++type AcceptanceScopeValue = {+ acceptanceId: string;+ embedded: boolean;+};++const AcceptanceScopeContext = createContext<AcceptanceScopeValue | null>(null);++export const useAcceptanceScope = () => {+ const scope = use(AcceptanceScopeContext);+ if (!scope) throw new Error('AcceptanceScope is required');+ return scope;+};++export const AcceptanceScope = ({+ acceptanceId,+ children,+ embedded = false,+}: {+ acceptanceId: string;+ children: ReactNode;+ embedded?: boolean;+}) => (+ <AcceptanceScopeContext value={{ acceptanceId, embedded }}>{children}</AcceptanceScopeContext>+);++export const AcceptanceBundleGate = ({+ children,+ height = '100%',+}: {+ children: ReactNode;+ height?: string | number;+}) => {+ const { t } = useTranslation('verify');+ const { acceptanceId } = useAcceptanceScope();+ const { data, isLoading, mutate } = useAcceptanceBundle(acceptanceId);++ if (isLoading && !data) {+ return (+ <Center height={height}>+ <NeuralNetworkLoading size={48} />+ </Center>+ );+ }++ if (!data) {+ return (+ <Center height={height}>+ <Empty description={t('acceptance.error.description')} title={t('acceptance.error.title')}>+ <Button onClick={() => void mutate()}>{t('report.actions.retry')}</Button>+ </Empty>+ </Center>+ );+ }++ return children;+};diff --git a/src/features/Verify/Acceptance/AcceptanceStatusControl.tsx b/src/features/Verify/Acceptance/AcceptanceStatusControl.tsxnew file mode 100644index 00000000000..04abe638c6d--- /dev/null+++ b/src/features/Verify/Acceptance/AcceptanceStatusControl.tsx@@ -0,0 +1,63 @@+'use client';++import { Icon } from '@lobehub/ui';+import type { DropdownItem } from '@lobehub/ui/base-ui';+import { toast } from '@lobehub/ui/base-ui';+import { CircleCheck, RotateCcw, X } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { mutate as globalMutate } from '@/libs/swr';+import { verifyKeys } from '@/libs/swr/keys';+import { verifyService } from '@/services/verify';++import { useAcceptanceScope } from './AcceptanceScope';+import AcceptanceStatusPill from './AcceptanceStatusPill';+import { getAcceptanceStatusActions } from './statusActions';+import { useAcceptanceBundle } from './useAcceptanceBundle';++const AcceptanceStatusControl = () => {+ const { t } = useTranslation('verify');+ const { acceptanceId } = useAcceptanceScope();+ const { data, mutate } = useAcceptanceBundle(acceptanceId);+ if (!data?.isOwner) return <AcceptanceStatusPill status={data?.acceptance.status ?? 'pending'} />;++ const changeStatus = async (status: 'accepted' | 'closed' | 'delivered') => {+ try {+ await verifyService.updateAcceptanceStatus(data.acceptance.id, status);+ await mutate();+ void globalMutate(verifyKeys.acceptances());+ toast.success(t('acceptance.workspace.statusSuccess'));+ } catch {+ toast.error(t('acceptance.workspace.statusError'));+ }+ };++ const menu: DropdownItem[] = getAcceptanceStatusActions(data.acceptance.status).map((action) => {+ if (action === 'accept') {+ return {+ icon: <Icon icon={CircleCheck} />,+ key: action,+ label: t('acceptance.workspace.actions.markAccepted'),+ onClick: () => void changeStatus('accepted'),+ };+ }+ if (action === 'reopen') {+ return {+ icon: <Icon icon={RotateCcw} />,+ key: action,+ label: t('acceptance.workspace.actions.reopen'),+ onClick: () => void changeStatus('delivered'),+ };+ }+ return {+ icon: <Icon icon={X} />,+ key: action,+ label: t('acceptance.workspace.actions.markClosed'),+ onClick: () => void changeStatus('closed'),+ };+ });++ return <AcceptanceStatusPill menu={menu} status={data.acceptance.status} />;+};++export default AcceptanceStatusControl;diff --git a/src/features/Verify/Acceptance/AcceptanceStatusPill.tsx b/src/features/Verify/Acceptance/AcceptanceStatusPill.tsxnew file mode 100644index 00000000000..7f5e173a00b--- /dev/null+++ b/src/features/Verify/Acceptance/AcceptanceStatusPill.tsx@@ -0,0 +1,64 @@+'use client';++import { Icon } from '@lobehub/ui';+import type { DropdownItem } from '@lobehub/ui/base-ui';+import { DropdownMenu } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { ChevronDown } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { resolveAcceptanceVerdictMeta } from './verdict';++const styles = createStaticStyles(({ css }) => ({+ pill: css`+ display: inline-flex;+ gap: 5px;+ align-items: center;++ padding-block: 2px;+ padding-inline: 10px;+ border-radius: 99px;++ font-size: 12px;+ font-weight: 500;+ `,+ interactive: css`+ cursor: pointer;+ transition: filter ${cssVar.motionDurationMid};++ &:hover {+ filter: brightness(1.08);+ }+ `,+}));++interface AcceptanceStatusPillProps {+ menu?: DropdownItem[];+ pending?: boolean;+ size?: number;+ status: string;+}++const AcceptanceStatusPill = ({ menu, pending, size = 13, status }: AcceptanceStatusPillProps) => {+ const { t } = useTranslation('verify');+ const verdictMeta = resolveAcceptanceVerdictMeta(status, t);+ const pill = (+ <span+ className={menu ? cx(styles.pill, styles.interactive) : styles.pill}+ title={menu ? t('acceptance.workspace.actions.status') : undefined}+ style={{+ background: verdictMeta.bg,+ color: verdictMeta.color,+ pointerEvents: pending ? 'none' : undefined,+ }}+ >+ <Icon icon={verdictMeta.icon} size={size} spin={verdictMeta.spin} />+ {verdictMeta.label}+ {menu ? <Icon icon={ChevronDown} size={11} /> : null}+ </span>+ );++ return menu ? <DropdownMenu items={menu}>{pill}</DropdownMenu> : pill;+};++export default AcceptanceStatusPill;diff --git a/src/features/Verify/Acceptance/AcceptanceViewReportLink.tsx b/src/features/Verify/Acceptance/AcceptanceViewReportLink.tsxnew file mode 100644index 00000000000..b1cfbb252ff--- /dev/null+++ b/src/features/Verify/Acceptance/AcceptanceViewReportLink.tsx@@ -0,0 +1,52 @@+'use client';++import { createStaticStyles, cssVar } from 'antd-style';+import { useTranslation } from 'react-i18next';+import { useSearchParams } from 'react-router';++import { useAcceptanceScope } from './AcceptanceScope';+import { useAcceptanceBundle } from './useAcceptanceBundle';+import { canViewAcceptanceHistory } from './visibility';++const styles = createStaticStyles(({ css }) => ({+ link: css`+ cursor: pointer;+ font-size: 12px;+ color: ${cssVar.colorTextQuaternary};++ &:hover {+ color: ${cssVar.colorTextSecondary};+ }+ `,+}));++const AcceptanceViewReportLink = () => {+ const { t } = useTranslation('verify');+ const { acceptanceId, embedded } = useAcceptanceScope();+ const { data } = useAcceptanceBundle(acceptanceId);+ const [, setSearchParams] = useSearchParams();+ if (embedded || !data?.latestReport || !canViewAcceptanceHistory(data.isOwner)) return null;++ const round = [...data.rounds].reverse().find((item) => item.report);++ return (+ <span+ className={styles.link}+ onClick={() => {+ if (round?.run.roundIndex == null) return;+ setSearchParams(+ (prev) => {+ const params = new URLSearchParams(prev);+ params.set('r', String(round.run.roundIndex));+ return params;+ },+ { replace: true },+ );+ }}+ >+ {t('acceptance.viewFullReport')}+ </span>+ );+};++export default AcceptanceViewReportLink;diff --git a/src/features/Portal/Acceptance/TopicPanel.test.ts b/src/features/Verify/Acceptance/TopicPanel.test.tssimilarity index 100%rename from src/features/Portal/Acceptance/TopicPanel.test.tsrename to src/features/Verify/Acceptance/TopicPanel.test.tsdiff --git a/src/features/Portal/Acceptance/TopicPanel.tsx b/src/features/Verify/Acceptance/TopicPanel.tsxsimilarity index 96%rename from src/features/Portal/Acceptance/TopicPanel.tsxrename to src/features/Verify/Acceptance/TopicPanel.tsxindex b23702dc34d..e52fa3be9f0 100644--- a/src/features/Portal/Acceptance/TopicPanel.tsx+++ b/src/features/Verify/Acceptance/TopicPanel.tsx@@ -7,7 +7,8 @@ import { memo } from 'react';import { useTranslation } from 'react-i18next';import { TopicChatDrawerBody } from '@/features/AgentTasks/AgentTaskDetail/TopicChatDrawer';-import type { OriginTopicPanelProps } from '@/features/Verify';++import type { OriginTopicPanelProps } from './originConversation';/*** The origin conversation rendered in the acceptance workspace's existingdiff --git a/src/features/Verify/Acceptance/Workspace/AcceptanceListPanel.tsx b/src/features/Verify/Acceptance/Workspace/AcceptanceListPanel.tsxindex 53d2ce4381f..af8250f886e 100644--- a/src/features/Verify/Acceptance/Workspace/AcceptanceListPanel.tsx+++ b/src/features/Verify/Acceptance/Workspace/AcceptanceListPanel.tsx@@ -18,6 +18,7 @@ import { DropdownMenu } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';import isEqual from 'fast-deep-equal';import {+ ArrowLeft,Check,FolderClosed,ListFilter,@@ -29,7 +30,7 @@ import {import type { ReactNode } from 'react';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { useParams } from 'react-router';+import { useNavigate, useParams } from 'react-router';import { SkeletonList } from '@/features/NavPanel/components/SkeletonList';import { useLocalStorageState } from '@/hooks/useLocalStorageState';@@ -38,6 +39,7 @@ 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,@@ -236,6 +238,7 @@ interface AcceptanceListPanelProps extends ReportPanelExpand {const AcceptanceListPanel = memo<AcceptanceListPanelProps>(({ expand, headerLeading, isNarrow, renderProjectActions, setExpand }) => {const { t } = useTranslation('verify');+ const navigate = useNavigate();const { acceptanceId } = useParams<{ acceptanceId: string }>();const { data, error, isLoading, mutate } = useAcceptanceList(true);@@ -294,8 +297,21 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(<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}+ <Flexbox+ horizontal+ align={'center'}+ flex={1}+ gap={headerLeading ? 8 : 4}+ style={{ minWidth: 0 }}+ >+ {headerLeading ?? (+ <ActionIcon+ icon={ArrowLeft}+ size={'small'}+ title={t('back', { ns: 'common' })}+ onClick={() => navigate(acceptanceHomePath())}+ />+ )}<Text ellipsis strong style={{ fontSize: 15, minWidth: 0 }}>{t('acceptance.workspace.title')}</Text>diff --git a/src/features/Verify/Acceptance/Workspace/index.tsx b/src/features/Verify/Acceptance/Workspace/index.tsxindex 8425394d2ab..261c9d12375 100644--- a/src/features/Verify/Acceptance/Workspace/index.tsx+++ b/src/features/Verify/Acceptance/Workspace/index.tsx@@ -8,8 +8,6 @@ import { useTranslation } from 'react-i18next';import { Outlet, useParams, useSearchParams } from 'react-router';import { RouteMetaBridge } from '@/features/RouteMeta';-import { useUserStore } from '@/store/user';-import { authSelectors } from '@/store/user/slices/auth/selectors';import { useReportPanelExpand } from '../../Workspace/useReportPanelExpand';import AcceptanceListPanel from './AcceptanceListPanel';@@ -58,32 +56,20 @@ const styles = createStaticStyles(({ css }) => ({`,}));-/**- * Acceptance workspace shell — the acceptance twin of {@link VerifyWorkspace}:- * a persistent, collapsible acceptance-list panel on the left and the selected- * aggregate (or the empty placeholder) rendered through the router `Outlet`.- * An anonymous visitor holding a public acceptance link gets only the detail —- * the list is the owner's, so it renders for signed-in users alone.- */const AcceptanceWorkspace = memo(() => {const { t } = useTranslation('verify');const panel = useReportPanelExpand();const { checkId } = useParams<{ checkId: string }>();const [searchParams] = useSearchParams();const hasFocusedCheck = Boolean(checkId || searchParams.get('check'));- const isAuthLoaded = useUserStore(authSelectors.isLoaded);- const isLogin = useUserStore(authSelectors.isLogin);- const canShowList = Boolean(isAuthLoaded && isLogin);+ const showList = !hasFocusedCheck;return (<Flexbox horizontal height={'100dvh'} style={{ overflow: 'hidden' }} width={'100%'}>- {/* Standalone route (outside the app main layout): drive the tab title here. */}<RouteMetaBridge />- {canShowList && !hasFocusedCheck && (- <AcceptanceListPanel {...panel} renderProjectActions={renderProjectActions} />- )}+ {showList && <AcceptanceListPanel {...panel} renderProjectActions={renderProjectActions} />}<div className={styles.main}>- {canShowList && !hasFocusedCheck && !panel.expand && (+ {showList && !panel.expand && (<buttonaria-label={t('workspace.expand')}className={styles.expandBtn}diff --git a/src/features/Verify/Acceptance/codingScope.ts b/src/features/Verify/Acceptance/codingScope.tsnew file mode 100644index 00000000000..ddd583ea0ab--- /dev/null+++ b/src/features/Verify/Acceptance/codingScope.ts@@ -0,0 +1,9 @@+import type { VerifyCodingScope } from '@lobechat/types';++import type { AcceptanceBundle } from '@/services/verify';++export const acceptanceCodingScope = (rounds: AcceptanceBundle['rounds']) =>+ [...rounds]+ .reverse()+ .find((round) => (round.run.scenario ?? 'coding') === 'coding' && round.run.context)?.run+ .context as VerifyCodingScope | null | undefined;diff --git a/src/features/Verify/Acceptance/index.tsx b/src/features/Verify/Acceptance/index.tsxindex ef217f5dfc3..2619209adae 100644--- a/src/features/Verify/Acceptance/index.tsx+++ b/src/features/Verify/Acceptance/index.tsx@@ -1,154 +1,26 @@'use client';-import type { AcceptanceChecklistItem, VerifyCodingScope } from '@lobechat/types';-import {- ActionIcon,- Avatar,- Center,- copyToClipboard,- DraggablePanel,- Empty,- Flexbox,- Icon,- Tag,- Text,-} from '@lobehub/ui';-import type { DropdownItem } from '@lobehub/ui/base-ui';-import { Button, Drawer, DropdownMenu, Select, toast } from '@lobehub/ui/base-ui';-import { createStaticStyles, cssVar, cx, useResponsive } from 'antd-style';-import dayjs from 'dayjs';-import {- ArrowLeft,- BadgeCheck,- Ban,- Check,- ChevronDown,- ChevronRight,- ChevronsDownUp,- ChevronsUpDown,- CircleCheck,- CircleDashed,- GitBranch,- GitCommitHorizontal,- GitPullRequest,- HelpCircle,- Loader2,- MessagesSquare,- PanelRightOpen,- PencilLine,- Plus,- RefreshCw,- RotateCcw,- Sparkles,- X,- XCircle,-} from 'lucide-react';-import { memo, useCallback, useEffect, useMemo, useState } from 'react';-import { useTranslation } from 'react-i18next';-import { useNavigate, useParams, useSearchParams } from 'react-router';--import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';-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-// every `useClientDataSWR` subscriber (augmented keys + custom cache provider).-import { mutate as globalMutate } from '@/libs/swr';-import { verifyKeys } from '@/libs/swr/keys';-import { verifyService } from '@/services/verify';--import { useAcceptanceBundle } from '../hooks';-import ReportViewer from '../ReportViewer';-import { extractUuid, resolveRoundParam } from '../utils';-import { openAddCheckModal } from './AddCheckModal';-import CheckList, {- type CheckFilter,- checkFilterState,- type CheckReviewInput,- FocusedCheckDetails,- focusedCheckStates,- groupChecks,- hasVisualEvidence,- isCheckWorkActionable,- isException,- isGroupFullyAccepted,- type ProposalDismissInput,- shouldGroupChecks,- userReviewState,-} from './CheckList';-import { buildRepairPrompt, copyCheckRepairPrompt } from './checkWork';-import DecisionBar from './DecisionBar';-import { EMPTY_ID_SET, setAggregateEntry } from './expandState';-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 { canViewAcceptanceHistory, resolveAcceptanceHistoryNavigation } from './visibility';+import { Flexbox } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { useParams } from 'react-router';++import { extractUuid } from '../utils';+import AcceptanceCheckInventory from './AcceptanceCheckInventory';+import AcceptanceCheckOwnerToolbar from './AcceptanceCheckOwnerToolbar';+import AcceptanceDecision from './AcceptanceDecision';+import AcceptanceEnterFocus from './AcceptanceEnterFocus';+import AcceptanceFocusWorkspace from './AcceptanceFocusWorkspace';+import AcceptanceGoal from './AcceptanceGoal';+import AcceptanceGoalEdit from './AcceptanceGoalEdit';+import AcceptanceIdentity from './AcceptanceIdentity';+import AcceptanceLedgerRail from './AcceptanceLedgerRail';+import AcceptanceOriginTopic from './AcceptanceOriginTopic';+import { AcceptanceBundleGate, AcceptanceScope } from './AcceptanceScope';+import AcceptanceStatusControl from './AcceptanceStatusControl';+import AcceptanceViewReportLink from './AcceptanceViewReportLink';+import { acceptanceScrollLayout } from './layout';const styles = createStaticStyles(({ css }) => ({- banner: css`- padding-block: 12px;- padding-inline: 16px;- border-radius: ${cssVar.borderRadiusLG};- `,- card: css`- overflow: hidden;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};- background: ${cssVar.colorBgContainer};-- &:hover [data-goal-toggle='true'] {- pointer-events: auto;- opacity: 1;- }- `,- countBadge: css`- padding-block: 1px;- padding-inline: 7px;- border-radius: 99px;-- font-size: 12px;- color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorFillTertiary};- `,- /* Pinned to the page's top-right corner — the way back to the collapsed- ledger, without a permanent handle tab on the edge. */- ledgerToggle: css`- position: absolute;- z-index: 10;- inset-block-start: 16px;- inset-inline-end: 16px;-- border: 1px solid ${cssVar.colorBorderSecondary};-- background: ${cssVar.colorBgContainer};-- &:hover {- border-color: ${cssVar.colorBorder};- }- `,- goalToggle: css`- pointer-events: none;- opacity: 0;- transition: opacity ${cssVar.motionDurationMid};-- &:focus-visible {- pointer-events: auto;- opacity: 1;- }-- @media (hover: none) {- pointer-events: auto;- opacity: 1;- }- `,contentFrame: css`overflow: ${acceptanceScrollLayout.frameOverflow};`,@@ -162,1891 +34,65 @@ const styles = createStaticStyles(({ css }) => ({background: ${cssVar.colorBgContainer};`,- requirementLabel: css`- font-size: 12px;- font-weight: 500;- color: ${cssVar.colorTextTertiary};- letter-spacing: 0.04em;- `,- scopeChip: css`- font-size: 12px;- color: ${cssVar.colorTextSecondary};- `,- scopeLink: css`- cursor: pointer;- color: ${cssVar.colorTextSecondary};-- &:hover {- color: ${cssVar.colorText};- text-decoration: underline;- }- `,- /** Quiet drawer entry — supporting affordance, not a boxed button. */- viewReportLink: css`- cursor: pointer;- font-size: 12px;- color: ${cssVar.colorTextQuaternary};-- &:hover {- color: ${cssVar.colorTextSecondary};- }- `,- summaryClamp: css`- overflow: hidden;- display: -webkit-box;- -webkit-box-orient: vertical;- -webkit-line-clamp: 3;-- line-height: 1.6;- `,- verdictPill: css`- display: inline-flex;- gap: 5px;- align-items: center;-- padding-block: 2px;- padding-inline: 10px;- border-radius: 99px;-- font-size: 12px;- font-weight: 500;- `,- verdictPillInteractive: css`- cursor: pointer;- transition: filter ${cssVar.motionDurationMid};-- &:hover {- filter: brightness(1.08);- }- `,- focusLayout: css`- display: grid;- grid-template-columns: 320px minmax(0, 1fr);-- @media (width <= 900px) {- grid-template-columns: 1fr;- }- `,- focusOutline: css`- position: sticky;- inset-block-start: 0;-- padding: 8px;- border-inline-end: 1px solid ${cssVar.colorBorderSecondary};-- background: ${cssVar.colorFillQuaternary};-- @media (width <= 900px) {- position: static;- border-block-end: 1px solid ${cssVar.colorBorderSecondary};- border-inline-end: 0;- }- `,- focusOutlineList: css`- overflow: ${acceptanceScrollLayout.paneOverflow};-- > * {- flex-shrink: 0;- }- `,- focusMain: css`- overflow: ${acceptanceScrollLayout.paneOverflow};- min-width: 0;- padding-block: ${acceptanceFocusedLayout.contentPaddingBlock};- padding-inline: 32px;- `,- focusContent: css`- width: min(880px, 100%);- margin-inline: auto;- `,- focusWork: css`- padding: 16px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};- background: ${cssVar.colorFillQuaternary};- `,- standingPanel: css`- overflow: hidden;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};- background: ${cssVar.colorBgContainer};- `,}));-/** Aggregate states in which the round chain is still executing. */-const LIVE_STATUSES = new Set(['pending', 'planned', 'verifying', 'repairing']);-const GOAL_COLLAPSED_STORAGE_KEY = 'lobehub-acceptance-goal-collapsed';-const CHECK_REVIEW_ORDER: Record<Exclude<CheckFilter, 'all'>, number> = {- pending: 0,- needsFix: 1,- accepted: 2,- ignored: 3,-};-interface AcceptancePageProps {- /**- * Render for a specific aggregate instead of the route param — the portal- * embed path. Embedded surfaces are narrow, so the round ledger starts- * collapsed there.- */acceptanceId?: string;- /**- * Portal embed only: draft text into the beside-it conversation composer- * (and sync its input state) instead of posting to the backend. Provided by- * the portal, which lives inside the ConversationProvider.- */onDraftToComposer?: (text: string) => boolean;}-/** How long to wait between bundle re-fetches while the batch runs. */-const PREDICT_POLL_INTERVAL_MS = 4000;-/** ~2 minutes: a bounded batch of 4-concurrent generations settles well inside this. */-const PREDICT_POLL_ATTEMPTS = 30;--const AcceptancePage = memo<AcceptancePageProps>(- ({ acceptanceId: explicitAcceptanceId, onDraftToComposer }) => {- const params = useParams<{ acceptanceId: string; checkId: string }>();- // Route params come from shared links whose autolinker may have glued- // trailing punctuation onto the id — salvage the leading UUID.- const acceptanceId = explicitAcceptanceId ?? extractUuid(params.acceptanceId);- const isEmbedded = Boolean(explicitAcceptanceId);- const navigate = useNavigate();- const { t } = useTranslation('verify');- 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).- const { lg = true } = useResponsive();- const isNarrowViewport = !lg;- // The portal embed is container-narrow even in a wide window — both regimes- // get the one-line compact toolbar.- const compactToolbar = isEmbedded || isNarrowViewport;-- // The standalone acceptance page owns the conversation panel it opens.- // Clear its global drawer state when leaving so it cannot reappear on a- // later task/home surface that also mounts TopicChatDrawer.- useEffect(- () => () => {- if (!isEmbedded) closeTopicDrawer?.();- },- [closeTopicDrawer, isEmbedded],- );-- // The checklist filter survives a refresh via a `?filter=` query param — but- // only on the standalone acceptance page. The portal embed rides the chat- // URL, so it keeps the filter in local state instead of hijacking that query.- const [searchParams, setSearchParams] = useSearchParams();- const legacyFocusedCheckId = isEmbedded ? null : searchParams.get('check');- const focusedCheckId = isEmbedded ? null : (params.checkId ?? legacyFocusedCheckId);- const [localFilter, setLocalFilter] = useState<CheckFilter>('all');- const urlFilterRaw = searchParams.get('filter');- const urlFilter: CheckFilter = (- ['all', 'pending', 'needsFix', 'accepted', 'ignored'] as const- ).includes(urlFilterRaw as CheckFilter)- ? (urlFilterRaw as CheckFilter)- : 'all';- const filter = isEmbedded ? localFilter : urlFilter;- const setFilter = (next: CheckFilter) => {- if (isEmbedded) {- setLocalFilter(next);- return;- }- setSearchParams(- (prev) => {- const params = new URLSearchParams(prev);- if (next === 'all') params.delete('filter');- else params.set('filter', next);- return params;- },- { replace: true },- );- };- const [roundFilter, setRoundFilter] = useState<number | null>(null);- const [goalCollapsed, setGoalCollapsed] = useLocalStorageState(- GOAL_COLLAPSED_STORAGE_KEY,- false,- );- // Expand/collapse state is kept PER aggregate: the portal embed swaps- // `acceptanceId` without remounting, so a single shared set would bleed one- // aggregate's toggles onto the next (and revisiting would show the wrong- // rows). Deriving from a per-id map keeps each aggregate's choices intact- // across repeated portal navigation. The `set*` wrappers write the current- // aggregate's entry, so downstream call sites read like plain useState.- const [expandedById, setExpandedById] = useState<Map<string, Set<string>>>(() => new Map());- const [collapsedById, setCollapsedById] = useState<Map<string, Set<string>>>(() => new Map());- const expanded = expandedById.get(acceptanceId ?? '') ?? EMPTY_ID_SET;- const collapsedGroups = collapsedById.get(acceptanceId ?? '') ?? EMPTY_ID_SET;- const setExpanded = useCallback(- (update: Set<string> | ((prev: Set<string>) => Set<string>)) =>- setExpandedById((map) => setAggregateEntry(map, acceptanceId, update)),- [acceptanceId],- );- const setCollapsedGroups = useCallback(- (update: Set<string> | ((prev: Set<string>) => Set<string>)) =>- setCollapsedById((map) => setAggregateEntry(map, acceptanceId, update)),- [acceptanceId],- );- // Which aggregates have had their one-time defaults (expand/collapse + filter)- // applied. A Set, not a single id, so returning to an already-seeded aggregate- // does NOT re-apply defaults and clobber the toggles the user made.- const seededIds = useSingleton(() => new Set<string>());- const [highlightRound, setHighlightRound] = useState<number | null>(null);- const [ledgerExpand, setLedgerExpand] = useState(!isEmbedded);- const [topicPanelOpen, setTopicPanelOpen] = useState(false);- // Keep previously shared `?check=` links working, but make the nested path- // the single source of truth for the selected check going forward.- useEffect(() => {- if (isEmbedded || params.checkId || !legacyFocusedCheckId || !acceptanceId) return;-- const nextSearchParams = new URLSearchParams(searchParams);- nextSearchParams.delete('check');- navigate(- {- pathname: acceptanceCheckPath(acceptanceId, legacyFocusedCheckId),- search: nextSearchParams.toString(),- },- { replace: true },- );- }, [acceptanceId, isEmbedded, legacyFocusedCheckId, navigate, params.checkId, searchParams]);- // Entering the narrow regime closes the ledger (it would cover the report);- // reopening is an explicit act via the corner toggle, as a float overlay.- useEffect(() => {- if (isNarrowViewport) setLedgerExpand(false);- }, [isNarrowViewport]);- // A focused check is the review workspace: evidence gets the horizontal- // room, while the round ledger remains available from the corner toggle.- // Adjusted during render, not in an effect, so selecting a check commits in- // one render pass instead of render → effect → full second render.- const [prevFocusedCheckId, setPrevFocusedCheckId] = useState(focusedCheckId);- if (prevFocusedCheckId !== focusedCheckId) {- setPrevFocusedCheckId(focusedCheckId);- if (focusedCheckId) setLedgerExpand(false);- }- const closeTopicPanel = useCallback(() => {- setTopicPanelOpen(false);- closeTopicDrawer?.();- }, [closeTopicDrawer]);-- const openTopicPanel = useCallback(() => {- 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,- });- setTopicPanelOpen(true);- setLedgerExpand(true);- }, [data, openTopicDrawer]);-- /**- * An agent judge argues by running, not by writing a paragraph — so the- * reviewable form of its verdict is its own conversation. Resolve the- * verifier operation to its topic and open the same drawer used for the- * origin run.- */- const openVerifierTrace = useCallback(- async (verifierOperationId: string) => {- if (!openTopicDrawer) return;- const resolved = await verifyService.getVerifierThread(verifierOperationId);- const topicId = resolved?.topicId;- if (!topicId) return;- openTopicDrawer(topicId, { title: t('acceptance.checks.viewTrace') });- setTopicPanelOpen(true);- },- [openTopicDrawer, t],- );- const [reportRound, setReportRound] = useState<AcceptanceRound | null>(null);- // `?r=<roundIndex>` deep-links one round's full report — a durable- // per-round snapshot URL (standalone page only; the portal embed rides the- // chat URL). The URL is the source of truth in BOTH directions: a resolved- // round opens the drawer, and a removed/unresolvable param closes it (a- // same-route navigation to the bare URL must not leave a stale drawer up).- // In-page opens/closes don't fight this sync — `openReport` writes state- // and param together, so by the time the param change lands here they- // already agree.- const urlRoundRaw = searchParams.get('r');- useEffect(() => {- if (isEmbedded || !data) return;- setReportRound(- canViewAcceptanceHistory(data.isOwner) ? resolveRoundParam(data.rounds, urlRoundRaw) : null,- );- }, [isEmbedded, data, urlRoundRaw]);- const [pending, setPending] = useState(false);- const [rerunPending, setRerunPending] = useState(false);- const [actionError, setActionError] = useState<string>();- const [feedbackOpen, setFeedbackOpen] = useState(false);- const [predicting, setPredicting] = useState(false);-- const status = data?.acceptance.status;-- // A chain still executing refreshes itself — same cadence as the report page.- useEffect(() => {- if (!status || !LIVE_STATUSES.has(status)) return;- const timer = setInterval(() => void mutate(), 5000);- return () => clearInterval(timer);- }, [status, mutate]);-- // Exceptions and visually-evidenced checks start expanded (P-08) — a check- // still awaiting the user's review shows its evidence (screenshots included)- // up front, not folded away. Seeded once per aggregate (see `seededIds`),- // and only after its checks have arrived, so the user's own toggling is never- // overwritten and an aggregate whose checks stream in a beat late still seeds.- // A check the user already accepted is settled business and stays folded- // regardless of its evidence; groups accepted in full start collapsed too.- useEffect(() => {- if (!data || data.checks.length === 0) return;- if (seededIds.has(acceptanceId ?? '')) return;- seededIds.add(acceptanceId ?? '');- setExpanded(- new Set(- data.checks- .filter(- (check) =>- userReviewState(check) !== 'accepted' &&- (isException(check) || hasVisualEvidence(check)),- )- .map((check) => check.id),- ),- );- setCollapsedGroups(- shouldGroupChecks(data.checks.length)- ? new Set(- groupChecks(data.checks, t('acceptance.group.uncategorized'))- .filter((group) => isGroupFullyAccepted(group.checks))- .map((group) => group.key),- )- : new Set(),- );- // First run (one round): nothing has been reviewed yet, so open on the whole- // list. Second round onward: the reviewer came back for what's still unsigned- // — land them on 未验收. A deep-link's explicit `?filter=` always wins.- const defaultFilter: CheckFilter = data.rounds.length > 1 ? 'pending' : 'all';- if (isEmbedded) {- setLocalFilter(defaultFilter);- } else if (!urlFilterRaw && defaultFilter !== 'all') {- setSearchParams(- (prev) => {- const params = new URLSearchParams(prev);- params.set('filter', defaultFilter);- return params;- },- { replace: true },- );- }- }, [- data,- acceptanceId,- t,- isEmbedded,- urlFilterRaw,- seededIds,- setSearchParams,- setExpanded,- setCollapsedGroups,- ]);-- const counts = useMemo(() => {- const checks = data?.checks ?? [];- return {- accepted: checks.filter((check) => checkFilterState(check) === 'accepted').length,- exceptions: checks.filter((check) => isException(check)).length,- failed: checks.filter((check) => check.state === 'failed').length,- ignored: checks.filter((check) => checkFilterState(check) === 'ignored').length,- needsFix: checks.filter((check) => checkFilterState(check) === 'needsFix').length,- notExecuted: checks.filter((check) => check.state === 'not_executed').length,- passed: checks.filter((check) => check.state === 'passed').length,- pending: checks.filter((check) => checkFilterState(check) === 'pending').length,- total: checks.length,- uncertain: checks.filter((check) => check.state === 'uncertain').length,- };- }, [data]);-- /**- * Checks the predictor could actually act on: executed (so there is a- * result to judge), not yet ruled on, and carrying a frame to look at.- *- * Deliberately NOT `counts.pending`, which counts any check without a- * standing review — including ones that never ran. That gate showed the- * button on acceptances where the server would consider zero checks, and- * the reverse case reads even worse: a page whose remaining "pending" item- * is un-executed loses the button with no visible reason.- */- const predictableCount = useMemo(- () =>- (data?.checks ?? []).filter(- (check) => check.result && !check.result.userDecision && hasVisualEvidence(check),- ).length,- [data],- );-- const acceptanceRecordId = data?.acceptance.id;- const runAction = useCallback(- async (action: () => Promise<unknown>) => {- try {- setPending(true);- setActionError(undefined);- await action();- await mutate();- // The list panel derives its glyph from the same status — a decision- // here must not leave a stale icon there until a hard refresh.- void globalMutate(verifyKeys.acceptances());- return true;- } catch (cause) {- setActionError(cause instanceof Error ? cause.message : t('acceptance.actionError'));- return false;- } finally {- setPending(false);- }- },- [mutate, t],- );-- // Per-check user review — accept settles a check for good; reject records- // the feedback the next verify round reads.- const handleReview = useCallback(- async (input: CheckReviewInput) => {- if (!acceptanceRecordId) return false;- return runAction(() => verifyService.reviewChecks({ id: acceptanceRecordId, ...input }));- },- [runAction, acceptanceRecordId],- );-- // Answering a model proposal is NOT a verdict on the check — the check- // stays pending and still needs the reviewer's own call. It goes through- // its own endpoint so a dismissal can never stamp a `user_decision`.- const handleDismissProposal = useCallback(- async (input: ProposalDismissInput) => {- if (!acceptanceRecordId) return;- await runAction(() =>- verifyService.adjudicateProposal({- adjudication: input.adjudication,- id: acceptanceRecordId,- predictionId: input.predictionId,- }),- );- },- [runAction, acceptanceRecordId],- );-- /**- * Ask for proposals on whatever is still awaiting a verdict. Explicit, so- * opening a report never spends model budget on its own.- *- * The server dispatches the batch AFTER responding, so the mutation returns- * in milliseconds with nothing to show. Poll the bundle until the cards- * land, keeping the button in its loading state meanwhile — otherwise the- * click reads as a no-op for the ~15s the first generation takes.- */- const handlePredictReviews = useCallback(async () => {- if (!acceptanceRecordId) return;- setPredicting(true);- try {- const { queued } = await verifyService.predictReviews(acceptanceRecordId);- if (queued === 0) return;-- for (let attempt = 0; attempt < PREDICT_POLL_ATTEMPTS; attempt += 1) {- await new Promise((resolve) => setTimeout(resolve, PREDICT_POLL_INTERVAL_MS));- const next = await mutate();- // Stop as soon as every queued check has been answered one way or the- // other — a check the model passes writes no row, so waiting for- // `queued` cards would always run to the timeout.- const settled = (next?.checks ?? []).filter(- (check) => check.prediction || check.result?.userDecision,- ).length;- if (settled >= queued) break;- }- } catch (error) {- setActionError(error instanceof Error ? error.message : String(error));- } finally {- setPredicting(false);- }- }, [mutate, acceptanceRecordId]);-- // Group-scoped feedback — for concerns that belong to no single check (the- // checks themselves may be accepted) yet must reach the next round.- const handleGroupFeedback = useCallback(- async (category: string, comment: string, fileIds: string[]) => {- if (!acceptanceRecordId) return false;- return runAction(() =>- verifyService.addGroupFeedback({- category,- comment,- fileIds: fileIds.length > 0 ? fileIds : undefined,- id: acceptanceRecordId,- }),- );- },- [runAction, acceptanceRecordId],- );-- // The decision bar's global note — the same group-feedback channel, aimed- // at the uncategorized bucket ('' targets the whole delivery).- const handleAddGlobalComment = useCallback(() => {- openGroupFeedbackModal({- description: t('acceptance.bar.addCommentDescription'),- groupLabel: t('acceptance.feedback.global'),- onConfirm: (comment, fileIds) => handleGroupFeedback('', comment, fileIds),- title: t('acceptance.bar.addComment'),- });- }, [handleGroupFeedback, t]);-- const gotoRound = useCallback((round: number) => {- setHighlightRound(round);- setLedgerExpand(true);- }, []);- const historyNavigation = useMemo(- () => resolveAcceptanceHistoryNavigation(Boolean(data?.isOwner), gotoRound),- [data?.isOwner, gotoRound],- );-- const handleToggleGroup = useCallback(- (key: string) =>- setCollapsedGroups((previous) => {- const next = new Set(previous);- if (next.has(key)) next.delete(key);- else next.add(key);- return next;- }),- [setCollapsedGroups],- );- const handleToggleGroupItems = useCallback(- (ids: string[], open: boolean) =>- setExpanded((previous) => {- const next = new Set(previous);- for (const id of ids) {- if (open) next.add(id);- else next.delete(id);- }- return next;- }),- [setExpanded],- );- const handleToggleItem = useCallback(- (id: string) =>- setExpanded((previous) => {- const next = new Set(previous);- if (next.has(id)) next.delete(id);- else next.add(id);- return next;- }),- [setExpanded],- );-- // Group-scoped feedback lives on each round's decision detail — flatten the- // chain into the derived per-entry view (roundIndex from the carrying run).- const groupFeedbackEntries = useMemo(- () =>- (data?.rounds ?? []).flatMap((round) =>- (round.run.decisionDetail?.groupFeedback ?? []).map((entry) => ({- ...entry,- roundIndex: round.run.roundIndex ?? 0,- })),- ),- [data],- );-- if (isLoading && !data)- return (- <Center height={'100%'}>- <NeuralNetworkLoading size={48} />- </Center>- );-- if (!data)- return (- <Center height={'100%'}>- <Empty- description={t('acceptance.error.description')}- title={t('acceptance.error.title')}- >- <Button onClick={() => void mutate()}>{t('report.actions.retry')}</Button>- </Empty>- </Center>- );-- const { acceptance, checks, isOwner, latestReport, origin, rounds, subject } = data;- const showHistory = canViewAcceptanceHistory(isOwner);- const originAgent = origin?.agent;- const originTopic = origin?.topic;- const focusedCheck = focusedCheckId- ? checks.find((check) => check.id === focusedCheckId)- : undefined;- const orderedChecks = [...checks].sort(- (a, b) =>- CHECK_REVIEW_ORDER[checkFilterState(a)] - CHECK_REVIEW_ORDER[checkFilterState(b)] ||- a.seq - b.seq,- );- const standingChecklist = acceptance.config?.checklist ?? [];- const unverifiedStandingChecks = standingChecklist.filter(- (item) => !checks.some((check) => check.id === item.id),- );- const focusedStates = focusedCheck- ? focusedCheckStates(focusedCheck)- : {- review: 'pending' as const,- verifier: 'not_executed' as const,- verifierLabel: 'notExecuted' as const,- };- const setFocusedCheck = (id?: string) => {- if (isEmbedded || !acceptanceId) return;-- const nextSearchParams = new URLSearchParams(searchParams);- nextSearchParams.delete('check');- navigate(- {- pathname: id- ? acceptanceCheckPath(acceptanceId, id)- : acceptanceOverviewPath(acceptanceId),- search: nextSearchParams.toString(),- },- { replace: true },- );- };- const currentRound = rounds.at(-1);- // The latest coding round's context — rendered with the latest report card- // (it describes what THAT round verified), not as aggregate-level identity.- // A round with no scenario predates the column and is a coding round; a- // non-coding round's context carries none of the chips the card renders.- const scope = [...rounds]- .reverse()- .find((round) => (round.run.scenario ?? 'coding') === 'coding' && round.run.context)?.run- .context as VerifyCodingScope | null | undefined;-- const grouped = shouldGroupChecks(checks.length);- const groupKeys = grouped- ? groupChecks(checks, t('acceptance.group.uncategorized')).map((group) => group.key)- : [];- const allGroupsCollapsed =- groupKeys.length > 0 && groupKeys.every((key) => collapsedGroups.has(key));-- const countsText = [- t('acceptance.stats.passed', { count: counts.passed }),- counts.uncertain > 0 ? t('acceptance.stats.uncertain', { count: counts.uncertain }) : null,- counts.failed > 0 ? t('acceptance.stats.failed', { count: counts.failed }) : null,- counts.notExecuted > 0- ? t('acceptance.stats.notExecuted', { count: counts.notExecuted })- : null,- ]- .filter(Boolean)- .join(' · ');-- // The header's one-glance state: the lifecycle isn't over until the user- // closes it — a settled-but-undecided chain reads as "in progress", never- // as a green all-clear the user hasn't given.- const verdictMeta: {- bg: string;- color: string;- icon: typeof BadgeCheck;- label: string;- spin?: boolean;- } =- acceptance.status === 'repairing'- ? {- // A repair round is an in-progress TASK — warn-coloured spinning- // refresh, matching the system's task-process cue, not a neutral verify.- bg: cssVar.colorWarningBg,- color: cssVar.colorWarning,- icon: RefreshCw,- label: t('acceptance.status.repairing'),- spin: true,- }- : LIVE_STATUSES.has(acceptance.status)- ? {- bg: cssVar.colorInfoBg,- color: cssVar.colorInfo,- icon: Loader2,- label: t(`acceptance.status.${acceptance.status}`),- spin: true,- }- : acceptance.status === 'accepted'- ? {- bg: cssVar.colorSuccessBg,- color: cssVar.colorSuccess,- icon: BadgeCheck,- label: t('acceptance.status.accepted'),- }- : acceptance.status === 'closed'- ? {- bg: cssVar.colorFillSecondary,- color: cssVar.colorTextSecondary,- icon: X,- label: t('acceptance.status.closed'),- }- : acceptance.status === 'rejected'- ? {- bg: cssVar.colorErrorBg,- color: cssVar.colorError,- icon: RotateCcw,- label: t('acceptance.status.rejected'),- }- : acceptance.status === 'errored'- ? {- bg: cssVar.colorWarningBg,- color: cssVar.colorWarning,- icon: HelpCircle,- label: t('acceptance.status.errored'),- }- : {- bg: cssVar.colorInfoBg,- color: cssVar.colorInfo,- icon: CircleDashed,- label: t('acceptance.verdict.inProgress'),- };-- const changeAcceptanceStatus = async (status: 'accepted' | 'closed' | 'delivered') => {- const succeeded = await runAction(() =>- verifyService.updateAcceptanceStatus(acceptance.id, status),- );- if (succeeded) {- toast.success(t('acceptance.workspace.statusSuccess'));- } else {- toast.error(t('acceptance.workspace.statusError'));- }- };-- const statusMenuItems: DropdownItem[] = getAcceptanceStatusActions(acceptance.status).map(- (action) => {- if (action === 'accept') {- return {- icon: <Icon icon={CircleCheck} />,- key: action,- label: t('acceptance.workspace.actions.markAccepted'),- onClick: () => void changeAcceptanceStatus('accepted'),- };- }- if (action === 'reopen') {- return {- icon: <Icon icon={RotateCcw} />,- key: action,- label: t('acceptance.workspace.actions.reopen'),- onClick: () => void changeAcceptanceStatus('delivered'),- };- }- return {- icon: <Icon icon={X} />,- key: action,- label: t('acceptance.workspace.actions.markClosed'),- onClick: () => void changeAcceptanceStatus('closed'),- };- },- );-- // Open/close the round report drawer AND mirror it to `?r=` (standalone- // page only) so the address bar is always a copyable snapshot link for the- // round being viewed.- const openReport = (round: AcceptanceRound | null) => {- setReportRound(round);- if (isEmbedded) return;- setSearchParams(- (prev) => {- const params = new URLSearchParams(prev);- if (round?.run.roundIndex == null) params.delete('r');- else params.set('r', String(round.run.roundIndex));- return params;- },- { replace: true },- );- };-- // The acceptance goal is a user-editable field — reuse the tray's goal- // modal so both entry points write the same subject-level requirement. A- // failed save is toasted here and rethrown so the modal stays open with- // the draft intact.- const handleEditGoal = () =>- openGoalModal({- initialGoal: acceptance.requirement ?? undefined,- onSubmit: async (goal) => {- try {- await verifyService.saveAcceptanceGoal(subject.type, subject.id, goal);- } catch (cause) {- toast.error(cause instanceof Error ? cause.message : t('acceptance.actionError'));- throw cause;- }- await mutate();- },- });-- // The floating bar's one-line state + supporting line — the old banner's- // content, relocated to where the decision actually happens.- const barState = LIVE_STATUSES.has(acceptance.status)- ? ('live' as const)- : acceptance.status === 'accepted'- ? ('accepted' as const)- : acceptance.status === 'rejected'- ? ('rejected' as const)- : ('settled' as const);- // Review progress — the bar's dial and wording track the user's own decisions,- // split the SAME way as the checklist chips (已验收 / 待修复 / 未验收) so the two- // never disagree. A rejected check is DECIDED (it belongs to 待修复), not- // "awaiting your acceptance" — only the untouched 未验收 checks are pending.- const reviewableChecks = checks.filter((check) => check.result);- const reviewTotal = reviewableChecks.length;- const acceptedCount = reviewableChecks.filter(- (check) => checkFilterState(check) === 'accepted',- ).length;- const needsFixCount = reviewableChecks.filter(- (check) => checkFilterState(check) === 'needsFix',- ).length;- const ignoredCount = reviewableChecks.filter(- (check) => checkFilterState(check) === 'ignored',- ).length;- const pendingCount = reviewTotal - acceptedCount - needsFixCount - ignoredCount;- const decidedCount = acceptedCount + needsFixCount + ignoredCount;- // Per-round acceptance tally for the ledger: each reviewable check belongs to- // the round its current result came from, so the ledger can show that round's- // own 已验收 / 待验收 progress instead of a raw verification verdict.- const reviewByRound = (() => {- const map = new Map<number, { accepted: number; total: number }>();- for (const check of reviewableChecks) {- const round = check.resultRound;- if (round === undefined || round === null) continue;- const cur = map.get(round) ?? { accepted: 0, total: 0 };- cur.total += 1;- if (checkFilterState(check) === 'accepted') cur.accepted += 1;- map.set(round, cur);- }- return map;- })();- const barTexts = {- accepted: {- statusText: t('acceptance.banner.accepted', {- time:- hydrated && acceptance.completedAt- ? dayjs(acceptance.completedAt).format('YYYY-MM-DD HH:mm')- : '',- }),- subText: `${countsText} · ${t('acceptance.banner.acceptedHint', { count: rounds.length })}`,- },- live: {- statusText: t(`acceptance.status.${acceptance.status}` as any),- subText: t('acceptance.banner.liveHint'),- },- rejected: {- statusText: t('acceptance.banner.rejected'),- subText: currentRound?.run.decisionDetail?.comment ?? t('acceptance.banner.rejectedHint'),- },- // The status line stands alone in every settled state — a grey stats echo- // (`N 通过 · …`) under it read as an unresolved caveat and just added noise.- settled:- decidedCount === 0- ? // Nothing reviewed yet — a clean "not started" prompt (no "已完成 0/…").- {- statusText: t('acceptance.bar.progressZero', { total: reviewTotal }),- subText: undefined,- }- : pendingCount === 0- ? needsFixCount === 0- ? // Every check accepted — ready to accept the delivery.- {- statusText: t('acceptance.bar.progressDone', { total: reviewTotal }),- subText: undefined,- }- : // Fully reviewed, but some checks need a fix — NOT "awaiting acceptance".- {- statusText: t('acceptance.bar.needsFix', { count: needsFixCount }),- subText: undefined,- }- : // Mid-review — the remainder is the UNDECIDED (未验收) count, not total-accepted.- {- statusText: t('acceptance.bar.progress', {- done: decidedCount,- rest: pendingCount,- total: reviewTotal,- }),- subText: undefined,- },- }[barState];-- // Every feedback event, flattened for the clearing list: per-check rejects- // (each review event) + group/global notes, active vs consumed by round.- const currentRoundIndex = currentRound?.run.roundIndex ?? 0;- const feedbackEntries: FeedbackListEntry[] = [- ...checks.flatMap((check) =>- check.reviews- .filter((review) => review.action === 'reject')- .map((review) => ({- annotationCount: review.annotations?.length || undefined,- attachments: review.attachments,- checkId: check.id,- checkSeq: check.seq,- comment: review.comment ?? '',- createdAt: review.createdAt,- kind: 'check' as const,- roundIndex: review.roundIndex,- stale: review.roundIndex < currentRoundIndex,- title: check.title,- })),- ),- ...groupFeedbackEntries.map((entry) => ({- attachments: entry.attachments,- comment: entry.comment,- createdAt: entry.createdAt,- groupLabel: entry.category,- kind: 'group' as const,- roundIndex: entry.roundIndex,- stale: entry.roundIndex < currentRoundIndex,- })),- ].sort((a, b) => b.createdAt.localeCompare(a.createdAt));- const activeFeedbackCount = feedbackEntries.filter((entry) => !entry.stale).length;-- const jumpToCheck = (checkId: string) => {- setFeedbackOpen(false);- setExpanded((previous) => new Set(previous).add(checkId));- // Wait a paint so a collapsed group/row has rendered before scrolling.- setTimeout(() => {- document- .querySelector(`[data-check-row="${checkId}"]`)- ?.scrollIntoView({ behavior: 'smooth', block: 'center' });- }, 80);- };-- const handleAccept = () =>- openAcceptModal({- exceptions: checks.filter((check) => isException(check)).map((check) => check.title),- onConfirm: () => runAction(() => verifyService.acceptDelivery(acceptance.id)),- subjectTitle: subject.title ?? subject.id,- });-- // The aggregate-level reject — the whole delivery goes back with a comment.- const handleRejectComment = () =>- openRejectModal({- onConfirm: (comment) =>- runAction(() => verifyService.rejectDelivery(acceptance.id, comment)),- });-- const repairPrompt = buildRepairPrompt(acceptance.id);- // Hand the repair prompt to the reviewer's clipboard — for pasting to any- // agent, not just the origin conversation.- const handleCopyReview = async () => {- await copyToClipboard(repairPrompt);- // Bottom-center, lifted clear of the sticky decision bar so it floats ABOVE- // the action row the click came from (not overlapping it).- toast.success({- placement: 'bottom',- style: { marginBlockEnd: 88 },- title: t('acceptance.bar.copied'),- });- };-- // Dispatch the repair prompt straight into the origin conversation — the- // agent reads the feedback itself via the CLI, no hand-summarizing. The- // aggregate is stamped `repairing` so the page (and the list) show the- // send-back took effect instead of sitting unchanged.- //- // Portal embed exception: the acceptance sits beside the live conversation, so- // a send-back drafts the prompt into the user's own composer (left) for them- // to review and send — never a silent backend post behind their back.- const handleRerun = async () => {- if (isEmbedded) {- // The portal handler drafts into the composer AND syncs its input state so- // Send enables; only toast once it actually landed (composer mounted).- if (onDraftToComposer?.(repairPrompt)) {- toast.success({- placement: 'bottom',- style: { marginBlockEnd: 88 },- title: t('acceptance.bar.rerunDrafted'),- });- }- return;- }- if (!origin?.topic) return;- setRerunPending(true);- try {- await verifyService.dispatchAcceptanceRepair({- agentId: origin.agent?.id,- content: repairPrompt,- topicId: origin.topic.id,- });- await verifyService.markAcceptanceRepairing(acceptance.id);- await mutate();- void globalMutate(verifyKeys.acceptances());- toast.success({- placement: 'bottom',- style: { marginBlockEnd: 88 },- title: t('acceptance.bar.rerunSent'),- });- } catch (cause) {- toast.error(cause instanceof Error ? cause.message : t('acceptance.actionError'));- } finally {- setRerunPending(false);- }- };-- const handleCheckWork = async () => {- if (!focusedCheck) return;- await copyCheckRepairPrompt(acceptance.id, focusedCheck, copyToClipboard);- toast.success({ title: t('acceptance.checkWork.copied') });- };-- const saveStandingChecklist = async (checklist: AcceptanceChecklistItem[]) => {- try {- await verifyService.saveAcceptanceChecklist(subject.type, subject.id, checklist);- await mutate();- toast.success({ title: t('acceptance.checkCreate.saved') });- } catch (cause) {- toast.error(cause instanceof Error ? cause.message : t('acceptance.actionError'));- throw cause;- }- };-- const handleAddChecks = () =>- openAddCheckModal({- existingIds: standingChecklist.map((item) => item.id),- onSubmit: (items: AcceptanceChecklistItem[]) =>- saveStandingChecklist([...standingChecklist, ...items]),- });-- const handleEditStandingCheck = (item: AcceptanceChecklistItem) =>- openCheckEditModal({- initial: { ...item, method: item.method ?? '' },- onRemove: () =>- void saveStandingChecklist(standingChecklist.filter((check) => check.id !== item.id)),- onSubmit: (value) =>- saveStandingChecklist(- standingChecklist.map((check) =>- check.id === item.id ? { ...check, ...value } : check,- ),- ),- });-- return (- <Flexbox horizontal className={styles.page}>- {/* The reopen affordance lives at the page corner — no edge handle tab. */}- {showHistory && !ledgerExpand && !focusedCheck && (- <ActionIcon- className={styles.ledgerToggle}- icon={PanelRightOpen}- size={'small'}- title={t('acceptance.ledger.expand')}- onClick={() => setLedgerExpand(true)}- />- )}- <Flexbox className={styles.contentFrame} flex={1} style={{ minWidth: 0 }}>- <Flexbox- gap={16}- paddingBlock={focusedCheck ? 0 : 20}- paddingInline={focusedCheck ? 0 : 24}- style={{- margin: focusedCheck ? 0 : '0 auto',- maxWidth: focusedCheck ? 'none' : 920,- width: '100%',- }}- >- {!focusedCheck && (- <>- {/* Header — state first (the lifecycle isn't closed until the user- closes it), then identity, then the origin conversation. */}- <Flexbox gap={10}>- <Flexbox horizontal align={'center'} gap={10} wrap={'wrap'}>- {isOwner ? (- <DropdownMenu items={statusMenuItems}>- <span- className={cx(styles.verdictPill, styles.verdictPillInteractive)}- title={t('acceptance.workspace.actions.status')}- style={{- background: verdictMeta.bg,- color: verdictMeta.color,- pointerEvents: pending ? 'none' : undefined,- }}- >- <Icon icon={verdictMeta.icon} size={13} spin={verdictMeta.spin} />- {verdictMeta.label}- <Icon icon={ChevronDown} size={11} />- </span>- </DropdownMenu>- ) : (- <span- className={styles.verdictPill}- style={{ background: verdictMeta.bg, color: verdictMeta.color }}- >- <Icon icon={verdictMeta.icon} size={13} spin={verdictMeta.spin} />- {verdictMeta.label}- </span>- )}- <Text fontSize={12} type={'secondary'}>- {[- countsText,- hydrated && currentRound- ? t('acceptance.verdict.latestAt', {- time: dayjs(currentRound.run.createdAt).format('MM-DD HH:mm'),- })- : null,- ]- .filter(Boolean)- .join(' · ')}- </Text>- </Flexbox>-- <Flexbox horizontal align={'center'} gap={10}>- <Text as={'h1'} style={{ fontSize: 18, margin: 0 }}>- {subject.title ?? subject.id}- </Text>- <Tag size={'small'}>{t(`acceptance.subject.${subject.type}`)}</Tag>- </Flexbox>-- {/* Origin — the conversation this acceptance belongs to (agent +- topic). Owner-only: the server redacts it for shared links.- Hidden in the portal embed: that surface already lives inside- the origin conversation. */}- {!isEmbedded && (originAgent || originTopic || scope?.pullRequest?.number) && (- <Flexbox horizontal align={'center'} gap={16} wrap={'wrap'}>- {originAgent && (- <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>- )}- {originTopic && originConversation && (- <Button- className={cx(styles.scopeChip, styles.scopeLink)}- icon={MessagesSquare}- size={'small'}- style={{ fontSize: 14 }}- title={t('acceptance.origin.openTopic')}- type={'text'}- onClick={openTopicPanel}- >- {originTopic.title ?? subject.title ?? originTopic.id}- </Button>- )}- {scope?.pullRequest?.number &&- (scope.pullRequest.url ? (- <a- className={cx(styles.scopeChip, styles.scopeLink)}- href={scope.pullRequest.url}- rel={'noreferrer'}- target={'_blank'}- title={scope.pullRequest.title ?? scope.pullRequest.url}- >- <Flexbox horizontal align={'center'} gap={4}>- <Icon icon={GitPullRequest} size={13} /> #{scope.pullRequest.number}- </Flexbox>- </a>- ) : (- <Flexbox horizontal align={'center'} className={styles.scopeChip} gap={4}>- <Icon icon={GitPullRequest} size={13} /> #{scope.pullRequest.number}- </Flexbox>- ))}- </Flexbox>- )}- {!isEmbedded && orderedChecks.length > 0 && (- <Button- icon={<Icon icon={ChevronRight} />}- size={'small'}- style={{ alignSelf: 'flex-start' }}- type={'text'}- onClick={() => setFocusedCheck(orderedChecks[0].id)}- >- {t('acceptance.focus.enter')}- </Button>- )}- </Flexbox>-- {actionError && <Text type={'danger'}>{actionError}</Text>}-- {/* The acceptance goal — THE thing this delivery is judged against,- one prominent card. The latest report summary (and the chips- describing what that round verified) is supporting context inside- it, never the headline. */}- <Flexbox- className={styles.card}- gap={goalCollapsed ? 0 : 12}- paddingBlock={goalCollapsed ? 8 : 12}- paddingInline={goalCollapsed ? 12 : 16}- >- <Flexbox horizontal align={'center'} gap={4}>- <Text className={styles.requirementLabel}>- {t('acceptance.requirementLabel')}- </Text>- {isOwner && !goalCollapsed && (- <ActionIcon- icon={PencilLine}- size={'small'}- title={t('acceptance.goalEdit')}- onClick={handleEditGoal}- />- )}- {goalCollapsed && (- <Text- ellipsis- fontSize={13}- style={{ flex: 1, minWidth: 0 }}- title={- acceptance.requirement ??- t(- isOwner- ? 'acceptance.requirementEmptyEditable'- : 'acceptance.requirementEmpty',- )- }- >- {acceptance.requirement ??- t(- isOwner- ? 'acceptance.requirementEmptyEditable'- : 'acceptance.requirementEmpty',- )}- </Text>- )}- {!goalCollapsed && <Flexbox flex={1} />}- <ActionIcon- data-goal-toggle- className={styles.goalToggle}- icon={goalCollapsed ? ChevronsUpDown : ChevronsDownUp}- size={'small'}- title={t(goalCollapsed ? 'acceptance.goalExpand' : 'acceptance.goalCollapse')}- onClick={() => setGoalCollapsed((collapsed) => !collapsed)}- />- </Flexbox>- {!goalCollapsed &&- (acceptance.requirement ? (- <Text style={{ fontSize: 15, lineHeight: 1.7 }}>- {acceptance.requirement}- </Text>- ) : isOwner ? (- // The empty state is itself the entry: the whole line invites- // the owner to record the goal, not just the pencil above.- <Text- className={styles.scopeLink}- style={{ fontSize: 15, lineHeight: 1.7 }}- onClick={handleEditGoal}- >- {t('acceptance.requirementEmptyEditable')}- </Text>- ) : (- <Text style={{ fontSize: 15, lineHeight: 1.7 }}>- {t('acceptance.requirementEmpty')}- </Text>- ))}- {!goalCollapsed && (latestReport?.summary || scope) && (- <Flexbox- gap={8}- paddingBlock={'12px 0'}- style={{ borderBlockStart: `1px solid ${cssVar.colorBorderSecondary}` }}- >- {/* label → the summary itself → provenance chips, all flush- left; the drawer entry is a quiet text link, not a button. */}- <Flexbox horizontal align={'center'} gap={8}>- <Text fontSize={12} type={'secondary'}>- {t('acceptance.latestSummary')}- {currentRound- ? ` · ${t('acceptance.round', { round: currentRound.run.roundIndex })}`- : ''}- </Text>- <Flexbox flex={1} />- {showHistory && latestReport && (- <span- className={styles.viewReportLink}- onClick={() =>- openReport([...rounds].reverse().find((r) => r.report) ?? null)- }- >- {t('acceptance.viewFullReport')}- </span>- )}- </Flexbox>- {latestReport?.summary && (- <Text className={styles.summaryClamp} fontSize={13} type={'secondary'}>- {latestReport.summary}- </Text>- )}- {scope && (- <Flexbox horizontal align={'center'} gap={16} wrap={'wrap'}>- {scope.branch && (- <Flexbox- horizontal- align={'center'}- className={styles.scopeChip}- gap={4}- >- <Icon icon={GitBranch} size={13} /> {scope.branch}- </Flexbox>- )}- {scope.commit && (- <Flexbox- horizontal- align={'center'}- className={styles.scopeChip}- gap={4}- >- <Icon icon={GitCommitHorizontal} size={13} />{' '}- {scope.commit.slice(0, 10)}- </Flexbox>- )}- </Flexbox>- )}- </Flexbox>- )}- </Flexbox>- </>- )}-- {focusedCheck ? (- <div className={styles.focusLayout}>- <Flexbox className={styles.focusOutline}>- <Flexbox flex={'none'} gap={10} paddingBlock={8} paddingInline={4}>- <Button- icon={<Icon icon={ArrowLeft} />}- size={'small'}- style={{ alignSelf: 'flex-start' }}- type={'text'}- onClick={() => setFocusedCheck()}- >- {t('acceptance.focus.back')}- </Button>- <Flexbox gap={4} paddingInline={4}>- <Text strong style={{ fontSize: 15 }}>- {subject.title ?? subject.id}- </Text>- <Flexbox horizontal align={'center'} gap={6}>- <span- className={styles.verdictPill}- style={{ background: verdictMeta.bg, color: verdictMeta.color }}- >- <Icon icon={verdictMeta.icon} size={12} spin={verdictMeta.spin} />- {verdictMeta.label}- </span>- <Text fontSize={11} type={'secondary'}>- {t('acceptance.roundCount', { count: rounds.length })}- </Text>- </Flexbox>- </Flexbox>- <Flexbox horizontal align={'center'} gap={8} paddingInline={4}>- <Text strong style={{ fontSize: 13 }}>- {t('acceptance.checks.title')}- </Text>- <span className={styles.countBadge}>- {checks.length + unverifiedStandingChecks.length}- </span>- <Flexbox flex={1} />- {isOwner && (- <Button- icon={<Icon icon={Plus} />}- size={'small'}- type={'text'}- onClick={handleAddChecks}- >- {t('acceptance.checkCreate.title')}- </Button>- )}- </Flexbox>- </Flexbox>- <Flexbox className={styles.focusOutlineList} flex={1}>- {orderedChecks.map((check) => {- const state = checkFilterState(check);- const icon =- state === 'accepted'- ? BadgeCheck- : state === 'needsFix'- ? RotateCcw- : state === 'ignored'- ? Ban- : CircleDashed;- const color =- state === 'accepted'- ? 'success'- : state === 'needsFix'- ? 'error'- : state === 'ignored'- ? 'default'- : 'default';-- return (- <NavItem- active={check.id === focusedCheck.id}- key={check.id}- paddingBlock={acceptanceFocusedLayout.outlineItemPaddingBlock}- paddingInline={acceptanceFocusedLayout.outlineItemPaddingInline}- title={check.title}- titleColor={cssVar.colorText}- description={- <Flexbox horizontal align={'center'} gap={8}>- <Tag color={color} icon={<Icon icon={icon} />} size={'small'}>- {t(`acceptance.focus.state.${state}`)}- </Tag>- <Text fontSize={12} type={'secondary'}>- {t('acceptance.focus.evidenceCount', {- count: check.evidence.length,- })}- </Text>- </Flexbox>- }- extra={- <Icon- color={cssVar.colorTextQuaternary}- icon={ChevronRight}- size={14}- />- }- slots={{- titlePrefix: (- <Flexbox- align={'center'}- height={22}- style={{ alignSelf: 'flex-start' }}- >- <Text- style={{- color: cssVar.colorTextQuaternary,- fontFamily: cssVar.fontFamilyCode,- fontSize: 11,- }}- >- C{check.seq}- </Text>- </Flexbox>- ),- }}- onClick={() => setFocusedCheck(check.id)}- />- );- })}- {unverifiedStandingChecks.length > 0 && (- <Flexbox gap={4} paddingBlock={8} paddingInline={8}>- <Text fontSize={11} type={'secondary'}>- {t('acceptance.checkCreate.pendingGroup')}- </Text>- {unverifiedStandingChecks.map((item) => (- <NavItem- extra={<Icon color={cssVar.colorTextQuaternary} icon={PencilLine} />}- key={item.id}- paddingBlock={acceptanceFocusedLayout.outlineItemPaddingBlock}- paddingInline={acceptanceFocusedLayout.outlineItemPaddingInline}- title={item.name}- titleColor={cssVar.colorText}- description={- <Text fontSize={12} type={'secondary'}>- {item.method || t('acceptance.checkCreate.pendingDescription')}- </Text>- }- onClick={() => handleEditStandingCheck(item)}- />- ))}- </Flexbox>- )}- </Flexbox>- </Flexbox>-- <Flexbox className={styles.focusMain}>- <Flexbox className={styles.focusContent} gap={16}>- <Flexbox gap={acceptanceFocusedLayout.headerGap}>- <Flexbox- horizontal- align={'center'}- gap={5}- style={{- color:- focusedStates.review === 'accepted'- ? cssVar.colorSuccess- : focusedStates.review === 'needsFix'- ? cssVar.colorError- : focusedStates.review === 'ignored'- ? cssVar.colorTextQuaternary- : cssVar.colorTextTertiary,- fontSize: 12,- }}- >- <Icon- size={14}- icon={- focusedStates.review === 'accepted'- ? BadgeCheck- : focusedStates.review === 'needsFix'- ? RotateCcw- : focusedStates.review === 'ignored'- ? Ban- : CircleDashed- }- />- {t(`acceptance.focus.state.${focusedStates.review}`)}- <Text style={{ color: cssVar.colorTextQuaternary }}>·</Text>- <Flexbox- horizontal- align={'center'}- gap={5}- style={{- color:- focusedStates.verifier === 'passed'- ? cssVar.colorSuccess- : focusedStates.verifier === 'failed'- ? cssVar.colorError- : focusedStates.verifier === 'uncertain'- ? cssVar.colorWarning- : cssVar.colorTextQuaternary,- }}- >- <Icon- size={14}- icon={- focusedStates.verifier === 'passed'- ? Check- : focusedStates.verifier === 'failed'- ? XCircle- : focusedStates.verifier === 'uncertain'- ? HelpCircle- : CircleDashed- }- />- {t('acceptance.focus.verifierLabel')} ·{' '}- {t(`report.verdict.${focusedStates.verifierLabel}`)}- </Flexbox>- </Flexbox>- <Flexbox horizontal align={'baseline'} gap={8}>- <Text- style={{- color: cssVar.colorTextTertiary,- flex: 'none',- fontFamily: cssVar.fontFamilyCode,- fontSize: 12,- }}- >- C{focusedCheck.seq}- </Text>- <Text as={'h2'} style={{ fontSize: 22, margin: 0 }}>- {focusedCheck.title}- </Text>- </Flexbox>- <Text fontSize={13} type={'secondary'}>- {t(`acceptance.focus.verifierDescription.${focusedStates.verifierLabel}`)}- </Text>- </Flexbox>- {isOwner &&- acceptance.status !== 'closed' &&- isCheckWorkActionable(focusedCheck) && (- <Flexbox horizontal align={'center'} className={styles.focusWork} gap={16}>- <Flexbox flex={1} gap={3}>- <Text strong>{t('acceptance.checkWork.title')}</Text>- <Text fontSize={12} type={'secondary'}>- {t('acceptance.checkWork.description')}- </Text>- </Flexbox>- <Button type={'primary'} onClick={handleCheckWork}>- {t('acceptance.checkWork.copy')}- </Button>- </Flexbox>- )}- <FocusedCheckDetails- canReview={isOwner}- check={focusedCheck}- reviewPending={pending}- onDismissProposal={handleDismissProposal}- onReview={handleReview}- onRound={historyNavigation}- />- </Flexbox>- </Flexbox>- </div>- ) : (- <>- {/* Check union — the complete inventory, familiar sections (P-14).- State and round are both audit filters, so they share one compact- Select treatment instead of competing control dialects. */}- <Flexbox- horizontal- align={'center'}- gap={8}- wrap={compactToolbar ? 'nowrap' : 'wrap'}- >- <Text strong style={{ fontSize: 14, whiteSpace: 'nowrap' }}>- {t('acceptance.checks.title')}- </Text>- <span className={styles.countBadge}>- {counts.total + unverifiedStandingChecks.length}- </span>- <Flexbox flex={1} />- {/* Explicit, and only while something is still unreviewed —- asking for proposals on a fully-judged acceptance would- spend budget to produce cards nobody can act on. */}- {isOwner && predictableCount > 0 && (- <ActionIcon- icon={Sparkles}- loading={predicting}- size={'small'}- title={t('acceptance.proposal.request')}- onClick={handlePredictReviews}- />- )}- {isOwner && (- <ActionIcon- icon={Plus}- size={'small'}- title={t('acceptance.checkCreate.title')}- onClick={handleAddChecks}- />- )}- <Select- size={'small'}- style={{ height: 34, width: 118 }}- value={filter}- variant={'filled'}- options={[- {- label: t('acceptance.filter.all', { count: counts.total }),- value: 'all',- },- {- label: t('acceptance.filter.pending', { count: counts.pending }),- value: 'pending',- },- {- label: t('acceptance.filter.needsFix', { count: counts.needsFix }),- value: 'needsFix',- },- {- label: t('acceptance.filter.accepted', { count: counts.accepted }),- value: 'accepted',- },- {- label: t('acceptance.filter.ignored', { count: counts.ignored }),- value: 'ignored',- },- ]}- onChange={(value) => setFilter(value as CheckFilter)}- />- {/* Which round touched a check — audit slicing, orthogonal to the- review-state segments. */}- {showHistory && rounds.length > 1 && (- <Select- size={'small'}- // Match the state filter so both read as one control family.- style={{ height: 34, width: 110 }}- value={roundFilter === null ? 'all' : String(roundFilter)}- variant={'filled'}- options={[- { label: t('acceptance.filter.roundAll'), value: 'all' },- ...[...rounds].reverse().map((round) => ({- label: t('acceptance.round', { round: round.run.roundIndex }),- value: String(round.run.roundIndex),- })),- ]}- onChange={(value) => setRoundFilter(value === 'all' ? null : Number(value))}- />- )}- {grouped && (- <ActionIcon- icon={allGroupsCollapsed ? ChevronsUpDown : ChevronsDownUp}- size={'small'}- title={- allGroupsCollapsed- ? t('acceptance.group.expandAll')- : t('acceptance.group.collapseAll')- }- onClick={() =>- setCollapsedGroups(allGroupsCollapsed ? new Set() : new Set(groupKeys))- }- />- )}- </Flexbox>-- {unverifiedStandingChecks.length > 0 && (- <Flexbox className={styles.standingPanel}>- <Flexbox- horizontal- align={'center'}- gap={8}- paddingBlock={10}- paddingInline={12}- style={{ borderBlockEnd: `1px solid ${cssVar.colorBorderSecondary}` }}- >- <Icon color={cssVar.colorTextTertiary} icon={CircleDashed} size={14} />- <Text strong style={{ fontSize: 13 }}>- {t('acceptance.checkCreate.pendingGroup')}- </Text>- <span className={styles.countBadge}>{unverifiedStandingChecks.length}</span>- <Text fontSize={12} type={'secondary'}>- {t('acceptance.checkCreate.pendingGroupDescription')}- </Text>- </Flexbox>- {unverifiedStandingChecks.map((item) => (- <NavItem- extra={<Icon color={cssVar.colorTextQuaternary} icon={PencilLine} />}- key={item.id}- title={item.name}- titleColor={cssVar.colorText}- description={- <Text fontSize={12} type={'secondary'}>- {item.method || t('acceptance.checkCreate.pendingDescription')}- </Text>- }- onClick={() => handleEditStandingCheck(item)}- />- ))}- </Flexbox>- )}-- <CheckList- canReview={isOwner}- checks={checks}- collapsedGroups={collapsedGroups}- currentRound={currentRound?.run.roundIndex ?? 0}- expanded={expanded}- filter={filter}- groupFeedback={groupFeedbackEntries}- reviewPending={pending}- round={roundFilter}- onDismissProposal={handleDismissProposal}- onGroupFeedback={handleGroupFeedback}- onOpenTrace={originConversation ? openVerifierTrace : undefined}- onReview={handleReview}- onRound={historyNavigation}- onToggleGroup={handleToggleGroup}- onToggleGroupItems={handleToggleGroupItems}- onToggleItem={handleToggleItem}- />- </>- )}- {/* The floating decision strip — owner-only: closing the loop and- queueing feedback are the author's calls, never a visitor's. */}- {isOwner && !focusedCheck && acceptance.status !== 'closed' && (- <DecisionBar- acceptedCount={acceptedCount}- embedded={isEmbedded}- feedbackCount={activeFeedbackCount}- ignoredCount={ignoredCount}- needsFixCount={needsFixCount}- pending={pending}- repairing={acceptance.status === 'repairing'}- rerunAvailable={isEmbedded || Boolean(origin?.topic)}- rerunPending={rerunPending}- state={barState}- statusText={barTexts.statusText}- subText={barTexts.subText}- totalCount={reviewTotal}- onAccept={handleAccept}- onAddComment={handleAddGlobalComment}- onCopyReview={handleCopyReview}- onOpenFeedback={() => setFeedbackOpen(true)}- onRejectComment={handleRejectComment}- onRerun={handleRerun}- />- )}- {!focusedCheck && <Flexbox style={{ height: 8 }} />}- </Flexbox>- </Flexbox>-- <FeedbackDrawer- entries={feedbackEntries}- open={feedbackOpen}- onClose={() => setFeedbackOpen(false)}- onJumpToCheck={jumpToCheck}- />-- {/* Runs / origin conversation share one right rail. Opening the origin- Topic replaces the run list in-place instead of layering a floating- drawer over the workspace. No edge- handle: opening happens from the page-corner toggle, closing from the- rail's own header action. On narrow viewports it opens as a masked- drawer over the report — dismissable by tapping outside — instead of- shrinking the report into an unreadable column. The panel's own- fold icon is the close affordance (same as wide mode), so the Drawer's- built-in close button is suppressed — one collapse handle, not two. */}- {showHistory &&- (isNarrowViewport ? (- <Drawer- noHeader- closable={false}- containerMaxWidth={'100%'}- open={ledgerExpand}- placement={'right'}- styles={{ bodyContent: { padding: 0 } }}- width={'min(340px, 88vw)'}- onClose={() => setLedgerExpand(false)}+const AcceptancePage = ({+ acceptanceId: explicitAcceptanceId,+ onDraftToComposer,+}: AcceptancePageProps) => {+ const params = useParams<{ acceptanceId: string; checkId: string }>();+ const acceptanceId = explicitAcceptanceId ?? extractUuid(params.acceptanceId);+ const embedded = Boolean(explicitAcceptanceId);+ const focused = !embedded && Boolean(params.checkId);++ if (!acceptanceId) return null;++ return (+ <AcceptanceScope acceptanceId={acceptanceId} embedded={embedded}>+ <AcceptanceBundleGate>+ <Flexbox horizontal className={styles.page}>+ <Flexbox className={styles.contentFrame} flex={1} style={{ minWidth: 0 }}>+ <Flexbox+ flex={focused ? 1 : undefined}+ gap={16}+ paddingBlock={focused ? 0 : 20}+ paddingInline={focused ? 0 : 24}+ style={{+ margin: focused ? 0 : '0 auto',+ maxWidth: focused ? 'none' : 920,+ minHeight: focused ? 0 : undefined,+ width: '100%',+ }}>- {topicPanelOpen && origin?.agent?.id && origin.topic && OriginTopicPanel ? (- <OriginTopicPanel- agentId={origin.agent.id}- title={origin.topic.title ?? subject.title ?? origin.topic.id}- topicId={origin.topic.id}- onBack={closeTopicPanel}- onCollapse={() => setLedgerExpand(false)}- />+ {focused ? (+ <AcceptanceFocusWorkspace />) : (- <LedgerPanel- highlight={highlightRound}- reviewByRound={reviewByRound}- rounds={rounds}- onCollapse={() => setLedgerExpand(false)}- onOpenReport={openReport}- />- )}- </Drawer>- ) : (- <DraggablePanel- stableLayout- defaultSize={{ width: 340 }}- expand={ledgerExpand}- minWidth={300}- placement={'right'}- style={{ flex: 'none', height: '100%' }}- onExpandChange={setLedgerExpand}- >- <Flexbox style={{ height: '100%', minHeight: 0, overflow: 'hidden' }}>- {topicPanelOpen && origin?.agent?.id && origin.topic && OriginTopicPanel ? (- <OriginTopicPanel- agentId={origin.agent.id}- title={origin.topic.title ?? subject.title ?? origin.topic.id}- topicId={origin.topic.id}- onBack={closeTopicPanel}- onCollapse={() => setLedgerExpand(false)}+ <>+ <AcceptanceIdentity+ statusSlot={<AcceptanceStatusControl />}+ topicSlot={<AcceptanceOriginTopic />}/>- ) : (- <Flexbox style={{ height: '100%', overflow: 'auto' }}>- <LedgerPanel- highlight={highlightRound}- reviewByRound={reviewByRound}- rounds={rounds}- onCollapse={() => setLedgerExpand(false)}- onOpenReport={openReport}- />- </Flexbox>- )}- </Flexbox>- </DraggablePanel>- ))}-- {/* Per-round report drill-down — the full verify run view, not a- markdown excerpt: same content as /verify/:runId, opened in place.- No drawer header: the report's own hero (title + verdict pill) is the- header; the Drawer's OWN floating close renders even with noHeader,- so no extra close button here (two would overlap). */}- {showHistory && (- <Drawer- noHeader- containerMaxWidth={'100%'}- open={reportRound !== null}- placement={'right'}- width={'min(960px, 92vw)'}- styles={{- bodyContent: { height: '100%', minHeight: 0, overflow: 'hidden', padding: 0 },- }}- onClose={() => openReport(null)}- >- {reportRound && (- <Flexbox style={{ height: '100%', position: 'relative' }}>- <ReportViewer runId={reportRound.run.id} />- </Flexbox>- )}- </Drawer>- )}- </Flexbox>- );- },-);--AcceptancePage.displayName = 'AcceptancePage';+ <AcceptanceEnterFocus />+ <AcceptanceGoal+ editSlot={<AcceptanceGoalEdit />}+ reportSlot={<AcceptanceViewReportLink />}+ />+ <AcceptanceCheckInventory canReview toolbar={<AcceptanceCheckOwnerToolbar />} />+ <AcceptanceDecision onDraftToComposer={onDraftToComposer} />+ </>+ )}+ </Flexbox>+ </Flexbox>+ <AcceptanceLedgerRail />+ </Flexbox>+ </AcceptanceBundleGate>+ </AcceptanceScope>+ );+};export default AcceptancePage;diff --git a/src/features/Verify/Acceptance/useAcceptanceBundle.ts b/src/features/Verify/Acceptance/useAcceptanceBundle.tsnew file mode 100644index 00000000000..d8ff2c1adea--- /dev/null+++ b/src/features/Verify/Acceptance/useAcceptanceBundle.ts@@ -0,0 +1,29 @@+import { useEffect } from 'react';++import { useClientDataSWR } from '@/libs/swr';+import { verifyKeys } from '@/libs/swr/keys';+import { verifyService } from '@/services/verify';++import { LIVE_ACCEPTANCE_STATUSES } from './verdict';++const ACCEPTANCE_BUNDLE_SWR_CONFIG = {+ revalidateOnFocus: true,+ revalidateOnReconnect: true,+} as const;++export const useAcceptanceBundle = (acceptanceId: string | null) => {+ const swr = useClientDataSWR(+ acceptanceId ? verifyKeys.acceptanceBundle(acceptanceId) : null,+ () => verifyService.getAcceptanceBundle(acceptanceId!),+ ACCEPTANCE_BUNDLE_SWR_CONFIG,+ );++ const status = swr.data?.acceptance.status;+ useEffect(() => {+ if (!status || !LIVE_ACCEPTANCE_STATUSES.has(status)) return;+ const timer = setInterval(() => void swr.mutate(), 5000);+ return () => clearInterval(timer);+ }, [status, swr.mutate]);++ return swr;+};diff --git a/src/features/Verify/Acceptance/verdict.test.ts b/src/features/Verify/Acceptance/verdict.test.tsnew file mode 100644index 00000000000..0202f90974f--- /dev/null+++ b/src/features/Verify/Acceptance/verdict.test.ts@@ -0,0 +1,26 @@+import type { TFunction } from 'i18next';+import { describe, expect, it } from 'vitest';++import { formatAcceptanceCountsText, resolveAcceptanceVerdictMeta } from './verdict';++const t = ((key: string) => key) as TFunction<'verify'>;++describe('resolveAcceptanceVerdictMeta', () => {+ it('treats repairing as an in-progress task, not a settled verdict', () => {+ const meta = resolveAcceptanceVerdictMeta('repairing', t);+ expect(meta.label).toBe('acceptance.status.repairing');+ expect(meta.spin).toBe(true);+ });++ it('treats accepted as a terminal success', () => {+ expect(resolveAcceptanceVerdictMeta('accepted', t).label).toBe('acceptance.status.accepted');+ });+});++describe('formatAcceptanceCountsText', () => {+ it('joins only the counts that are present', () => {+ expect(+ formatAcceptanceCountsText(t, { failed: 1, notExecuted: 0, passed: 3, uncertain: 0 }),+ ).toBe('acceptance.stats.passed · acceptance.stats.failed');+ });+});diff --git a/src/features/Verify/Acceptance/verdict.ts b/src/features/Verify/Acceptance/verdict.tsnew file mode 100644index 00000000000..a1e22bd4de1--- /dev/null+++ b/src/features/Verify/Acceptance/verdict.ts@@ -0,0 +1,98 @@+import { cssVar } from 'antd-style';+import type { TFunction } from 'i18next';+import {+ BadgeCheck,+ CircleDashed,+ HelpCircle,+ Loader2,+ RefreshCw,+ RotateCcw,+ X,+} from 'lucide-react';++export const LIVE_ACCEPTANCE_STATUSES = new Set(['pending', 'planned', 'verifying', 'repairing']);++export type AcceptanceVerdictMeta = {+ bg: string;+ color: string;+ icon: typeof BadgeCheck;+ label: string;+ spin?: boolean;+};++export const resolveAcceptanceVerdictMeta = (+ status: string,+ t: TFunction<'verify'>,+): AcceptanceVerdictMeta => {+ if (status === 'repairing') {+ return {+ bg: cssVar.colorWarningBg,+ color: cssVar.colorWarning,+ icon: RefreshCw,+ label: t('acceptance.status.repairing'),+ spin: true,+ };+ }+ if (status === 'pending' || status === 'planned' || status === 'verifying') {+ return {+ bg: cssVar.colorInfoBg,+ color: cssVar.colorInfo,+ icon: Loader2,+ label: t(`acceptance.status.${status}`),+ spin: true,+ };+ }+ if (status === 'accepted') {+ return {+ bg: cssVar.colorSuccessBg,+ color: cssVar.colorSuccess,+ icon: BadgeCheck,+ label: t('acceptance.status.accepted'),+ };+ }+ if (status === 'closed') {+ return {+ bg: cssVar.colorFillSecondary,+ color: cssVar.colorTextSecondary,+ icon: X,+ label: t('acceptance.status.closed'),+ };+ }+ if (status === 'rejected') {+ return {+ bg: cssVar.colorErrorBg,+ color: cssVar.colorError,+ icon: RotateCcw,+ label: t('acceptance.status.rejected'),+ };+ }+ if (status === 'errored') {+ return {+ bg: cssVar.colorWarningBg,+ color: cssVar.colorWarning,+ icon: HelpCircle,+ label: t('acceptance.status.errored'),+ };+ }+ return {+ bg: cssVar.colorInfoBg,+ color: cssVar.colorInfo,+ icon: CircleDashed,+ label: t('acceptance.verdict.inProgress'),+ };+};++export const formatAcceptanceCountsText = (+ t: TFunction<'verify'>,+ counts: { failed: number; notExecuted: number; passed: number; uncertain: number },+) =>+ [+ t('acceptance.stats.passed', { count: counts.passed }),+ counts.uncertain > 0 ? t('acceptance.stats.uncertain', { count: counts.uncertain }) : null,+ counts.failed > 0 ? t('acceptance.stats.failed', { count: counts.failed }) : null,+ counts.notExecuted > 0+ ? t('acceptance.stats.notExecuted', { count: counts.notExecuted })+ : null,+ ]+ .filter(Boolean)+ .join(' · ');diff --git a/src/features/Verify/hooks.ts b/src/features/Verify/hooks.tsindex cb2af95910b..83a7d9ede71 100644--- a/src/features/Verify/hooks.ts+++ b/src/features/Verify/hooks.ts@@ -61,13 +61,7 @@ export const useVerifyReportBundle = (verifyRunId: string | null) =>VERIFY_REPORT_SWR_CONFIG,);-/** Cross-round acceptance decision bundle by acceptance id. */-export const useAcceptanceBundle = (acceptanceId: string | null) =>- useClientDataSWR(- acceptanceId ? verifyKeys.acceptanceBundle(acceptanceId) : null,- () => verifyService.getAcceptanceBundle(acceptanceId!),- ACCEPTANCE_BUNDLE_SWR_CONFIG,- );+export { useAcceptanceBundle } from './Acceptance/useAcceptanceBundle';/** The optional acceptance aggregate attached to a task/topic/document subject. */export const useAcceptanceBySubject = (diff --git a/src/libs/next/proxy/define-config.test.ts b/src/libs/next/proxy/define-config.test.tsindex 693458c5b11..c9eeb0449a6 100644--- a/src/libs/next/proxy/define-config.test.ts+++ b/src/libs/next/proxy/define-config.test.ts@@ -53,28 +53,30 @@ describe('defineConfig locale path-traversal hardening', () => {});describe('defineConfig Workbench SPA rewrite', () => {- 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');+ it('routes verify through Workbench for every user agent', async () => {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).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 acceptance on the main SPA', 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');++ expect(new URL(mobileAcceptance!).pathname).toMatch(/^\/spa\/[^/]+\/acceptance\/acceptance-1$/);+ expect(new URL(desktopAcceptance!).pathname).toMatch(+ /^\/spa\/[^/]+\/acceptance\/acceptance-1$/,+ );+ });+it('keeps the agent documents index in the Main Mobile SPA', async () => {const detail = await run('http://localhost:3010/agent/agt_1/docs/doc_1?hl=en-US',diff --git a/src/libs/next/workbenchNavigation.test.ts b/src/libs/next/workbenchNavigation.test.tsindex f5756f78ad6..f7452fbaed4 100644--- a/src/libs/next/workbenchNavigation.test.ts+++ b/src/libs/next/workbenchNavigation.test.ts@@ -3,17 +3,20 @@ 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',+ it.each(['/verify', '/verify/run-1'])(+ 'hard-navigates verify 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);- },- );+ it.each([+ '/acceptance',+ '/acceptance/a-1?r=2',+ '/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/workbenchRoutes.test.ts b/src/libs/next/workbenchRoutes.test.tsindex e30f1d96e56..0d42cfc8336 100644--- a/src/libs/next/workbenchRoutes.test.ts+++ b/src/libs/next/workbenchRoutes.test.ts@@ -3,30 +3,25 @@ import { describe, expect, it } from 'vitest';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(['/verify', '/verify/run-1'])('owns verify 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);- },- );+ it.each([+ '/acceptance',+ '/acceptance/acceptance-1',+ '/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(['/agent/agt_9GOn6nUgGw35/docs/TWuw2YunjhwLblZ7','/agent/agt_9GOn6nUgGw35/docs/TWuw2YunjhwLblZ7/',- '/acceptance',- '/acceptance/',- '/acceptance/acceptance-1',- '/acceptance/acceptance-1?round=2',- '/acceptance/acceptance-1/check/check-1','/verify','/verify/','/verify/run-1',@@ -38,6 +33,9 @@ describe('isWorkbenchSpaRoute', () => {'/agent/agt_9GOn6nUgGw35','/agent/agt_9GOn6nUgGw35/docs','/agent/agt_9GOn6nUgGw35/docs/doc-1/history',+ '/acceptance',+ '/acceptance/acceptance-1',+ '/acceptance/acceptance-1/check/check-1','/acceptance-preview','/acceptance/acceptance-1/history','/workspace/acceptance/acceptance-1',diff --git a/src/libs/next/workbenchRoutes.ts b/src/libs/next/workbenchRoutes.tsindex a0f358a9fb2..aec430d84a9 100644--- a/src/libs/next/workbenchRoutes.ts+++ b/src/libs/next/workbenchRoutes.ts@@ -1,14 +1,12 @@const AGENT_DOCUMENT_ROUTE = /^\/agent\/[^/]+\/docs\/[^/]+\/?$/;-const ACCEPTANCE_ROUTE = /^\/acceptance(?:\/[^/]+(?:\/check\/[^/]+)?)?\/?$/;const VERIFY_ROUTE = /^\/verify(?:\/[^/]+)?\/?$/;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);+ return VERIFY_ROUTE.test(path);};/** Every path Workbench can own, including mobile-only agent documents. */diff --git a/src/routes/(main)/acceptance/empty.tsx b/src/routes/(main)/acceptance/empty.tsxnew file mode 100644index 00000000000..267e0dc69fa--- /dev/null+++ b/src/routes/(main)/acceptance/empty.tsx@@ -0,0 +1,3 @@+'use client';++export { AcceptanceEmptyDetail as default } from '@/features/Verify';diff --git a/src/routes/(main)/acceptance/index.tsx b/src/routes/(main)/acceptance/index.tsxnew file mode 100644index 00000000000..7e55fd7c5ce--- /dev/null+++ b/src/routes/(main)/acceptance/index.tsx@@ -0,0 +1,3 @@+'use client';++export { AcceptanceWorkspace as default } from '@/features/Verify';diff --git a/src/routes/acceptance/[acceptanceId]/index.tsx b/src/routes/acceptance/[acceptanceId]/index.tsxnew file mode 100644index 00000000000..44d4a08664f--- /dev/null+++ b/src/routes/acceptance/[acceptanceId]/index.tsx@@ -0,0 +1,26 @@+'use client';++import { useMemo } from 'react';++import {+ AcceptanceViewer,+ OriginConversationProvider,+ type OriginConversationSlot,+} from '@/features/Verify';+import TopicPanel from '@/features/Verify/Acceptance/TopicPanel';+import { useTaskStore } from '@/store/task';++export default function AcceptanceRoute() {+ const openTopicDrawer = useTaskStore((s) => s.openTopicDrawer);+ const closeTopicDrawer = useTaskStore((s) => s.closeTopicDrawer);+ const originConversation = useMemo<OriginConversationSlot>(+ () => ({ TopicPanel, closeTopicDrawer, openTopicDrawer }),+ [closeTopicDrawer, openTopicDrawer],+ );++ return (+ <OriginConversationProvider value={originConversation}>+ <AcceptanceViewer />+ </OriginConversationProvider>+ );+}diff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsxindex 1da9395ea86..e19b7b226e0 100644--- a/src/spa/router/desktopRouter.config.tsx+++ b/src/spa/router/desktopRouter.config.tsx@@ -2,6 +2,7 @@import type { RouteObject } from 'react-router';+import { acceptanceRouteMeta } from '@/features/Verify/routeMeta';import { sharePageRouteMeta } from '@/routes/share/page/[id]/routeMeta';import { shareTopicRouteMeta } from '@/routes/share/t/[id]/routeMeta';import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';@@ -56,6 +57,38 @@ const webOnlyRoutes: RouteObject[] = [errorElement: <ErrorBoundary />,path: '/verify-im',},++ {+ 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 1df5edfc5be..6a482adc0ed 100644--- a/src/spa/router/desktopRouter.sync.test.tsx+++ b/src/spa/router/desktopRouter.sync.test.tsx@@ -277,7 +277,7 @@ describe('desktop router shared definition', () => {expect(webPaths).toContain('/share/t');expect(webPaths).toContain('/share/page');expect(webPaths).not.toContain('/verify');- expect(webPaths).not.toContain('/acceptance');+ expect(webPaths).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 3a84b20ae62..71ac16e8e6d 100644--- a/src/spa/router/mobileRouter.config.tsx+++ b/src/spa/router/mobileRouter.config.tsx@@ -8,6 +8,7 @@ import {} from '@/business/client/BusinessMobileRoutes';import AppsSkeleton from '@/components/Skeleton/Apps';import { mobileAgentSettingsRouteMeta } from '@/features/RouteMeta/mobileRouteMeta';+import { acceptanceRouteMeta } from '@/features/Verify/routeMeta';import { agentRouteMeta } from '@/routes/(main)/agent/features/routeMeta';import { sharePageRouteMeta } from '@/routes/share/page/[id]/routeMeta';import { shareTopicRouteMeta } from '@/routes/share/t/[id]/routeMeta';@@ -624,4 +625,23 @@ export const mobileRoutes: RouteObject[] = [errorElement: <ErrorBoundary />,path: '/verify-im',},++ {+ 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',+ },];