Skip to content

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

🐛 fix: LocalFile chip preview & user-message rendering, restore acceptance rerun handoff (#19025)

Arvin Xu6eeb04e58664
diff --git a/locales/en-US/components.json b/locales/en-US/components.json
index 30397bb30db..0d05db4655e 100644
--- a/locales/en-US/components.json
+++ b/locales/en-US/components.json
@@ -119,6 +119,7 @@
"KeyValueEditor.keyPlaceholder": "Key",
"KeyValueEditor.valuePlaceholder": "Value",
"LocalFile.action.open": "Open",
+ "LocalFile.action.preview": "Preview",
"LocalFile.action.showInFolder": "Show in Folder",
"MaxTokenSlider.unlimited": "Unlimited",
"ModelSelect.featureTag.audio": "This model supports audio input recognition.",
diff --git a/locales/en-US/verify.json b/locales/en-US/verify.json
index 79af3880837..b4f2684f8c9 100644
--- a/locales/en-US/verify.json
+++ b/locales/en-US/verify.json
@@ -29,6 +29,9 @@
"acceptance.bar.progressDone": "All {{total}} checks confirmed — ready to accept",
"acceptance.bar.progressZero": "{{total}} checks awaiting your review",
"acceptance.bar.rejectComment": "Reject with comment",
+ "acceptance.bar.rerun": "Fix",
+ "acceptance.bar.rerunDrafted": "Drafted into your composer — review and send it.",
+ "acceptance.bar.rerunSent": "Sent to the origin conversation — the repair round is starting.",
"acceptance.checkCreate.add": "Add checks",
"acceptance.checkCreate.addToScope": "Add to acceptance scope",
"acceptance.checkCreate.empty": "All checks in this rubric are already in scope.",
diff --git a/locales/zh-CN/components.json b/locales/zh-CN/components.json
index 87ed650e8fa..4882ec1873e 100644
--- a/locales/zh-CN/components.json
+++ b/locales/zh-CN/components.json
@@ -119,6 +119,7 @@
"KeyValueEditor.keyPlaceholder": "键",
"KeyValueEditor.valuePlaceholder": "值",
"LocalFile.action.open": "打开",
+ "LocalFile.action.preview": "预览",
"LocalFile.action.showInFolder": "在文件夹中显示",
"MaxTokenSlider.unlimited": "无限制",
"ModelSelect.featureTag.audio": "该模型支持音频输入识别",
diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.json
index acdb028635f..5b57ac81833 100644
--- a/locales/zh-CN/verify.json
+++ b/locales/zh-CN/verify.json
@@ -29,6 +29,9 @@
"acceptance.bar.progressDone": "{{total}} 项验证项已全部确认,可以接受交付",
"acceptance.bar.progressZero": "共 {{total}} 项等待你的验收",
"acceptance.bar.rejectComment": "评论并打回",
+ "acceptance.bar.rerun": "打回重跑",
+ "acceptance.bar.rerunDrafted": "已填入对话框,检查后发送。",
+ "acceptance.bar.rerunSent": "已发送到源会话,修复轮次启动中。",
"acceptance.checkCreate.add": "添加检查项",
"acceptance.checkCreate.addToScope": "加入验收范围",
"acceptance.checkCreate.empty": "这个 Rubric 中的检查项都已在验收范围内。",
diff --git a/packages/locales/src/default/components.ts b/packages/locales/src/default/components.ts
index 388bc6cda69..68f4a0fbea1 100644
--- a/packages/locales/src/default/components.ts
+++ b/packages/locales/src/default/components.ts
@@ -139,6 +139,7 @@ export default {
'KeyValueEditor.keyPlaceholder': 'Key',
'KeyValueEditor.valuePlaceholder': 'Value',
'LocalFile.action.open': 'Open',
+ 'LocalFile.action.preview': 'Preview',
'LocalFile.action.showInFolder': 'Show in Folder',
'MaxTokenSlider.unlimited': 'Unlimited',
'ModelSelect.featureTag.audio': 'This model supports audio input recognition.',
diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.ts
index 37fbfa01350..c685c90b944 100644
--- a/packages/locales/src/default/verify.ts
+++ b/packages/locales/src/default/verify.ts
@@ -38,6 +38,9 @@ export default {
'acceptance.bar.progressDone': 'All {{total}} checks confirmed — ready to accept',
'acceptance.bar.progressZero': '{{total}} checks awaiting your review',
'acceptance.bar.rejectComment': 'Reject with comment',
+ 'acceptance.bar.rerun': 'Fix',
+ 'acceptance.bar.rerunDrafted': 'Drafted into your composer — review and send it.',
+ 'acceptance.bar.rerunSent': 'Sent to the origin conversation — the repair round is starting.',
'acceptance.checks.allAccepted.desc': 'Nice work — every acceptance check has been signed off.',
'acceptance.checks.allAccepted.title': 'All checks accepted 🎉',
'acceptance.checks.copied': 'Copied',
diff --git a/src/features/Acceptance/Viewer/AcceptanceDecision.tsx b/src/features/Acceptance/Viewer/AcceptanceDecision.tsx
index c72bc1a3b02..b3ffd5ec136 100644
--- a/src/features/Acceptance/Viewer/AcceptanceDecision.tsx
+++ b/src/features/Acceptance/Viewer/AcceptanceDecision.tsx
@@ -17,20 +17,29 @@ import { buildRepairPrompt } from './checkWork';
import DecisionBar from './DecisionBar';
import FeedbackDrawer, { type FeedbackListEntry } from './FeedbackDrawer';
import { openAcceptModal, openGroupFeedbackModal, openRejectModal } from './modals';
+import { dispatchRepairRerun } from './repairRerun';
import { useAcceptanceBundle } from './useAcceptanceBundle';
import { formatAcceptanceCountsText, LIVE_ACCEPTANCE_STATUSES } from './verdict';
import { canReviewAcceptance } from './visibility';
-const AcceptanceDecision = () => {
+interface AcceptanceDecisionProps {
+ onDraftToComposer?: (text: string) => boolean;
+}
+
+const AcceptanceDecision = ({ onDraftToComposer }: AcceptanceDecisionProps) => {
const { t } = useTranslation('verify');
const hydrated = useIsHydrated();
- const { acceptanceId } = useAcceptanceScope();
+ const { acceptanceId, embedded } = useAcceptanceScope();
const { data, mutate } = useAcceptanceBundle(acceptanceId);
const [pending, setPending] = useState(false);
+ const [rerunPending, setRerunPending] = useState(false);
+ // Latched once a standalone dispatch reaches the server: the repair run has
+ // started, so Fix must not offer a retry even if later bookkeeping failed.
+ const [rerunDispatched, setRerunDispatched] = useState(false);
const [feedbackOpen, setFeedbackOpen] = useState(false);
if (!data || !canReviewAcceptance(data) || data.acceptance.status === 'closed') return null;
- const { acceptance, checks, rounds } = data;
+ 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;
@@ -148,11 +157,14 @@ const AcceptanceDecision = () => {
<>
<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) && !rerunDispatched)}
+ rerunPending={rerunPending}
state={barState}
statusText={barTexts.statusText}
subText={barTexts.subText}
@@ -195,6 +207,59 @@ const AcceptanceDecision = () => {
runAction(() => verifyService.rejectDelivery(acceptance.id, comment)),
})
}
+ onRerun={async () => {
+ if (embedded) {
+ // The origin conversation's composer sits right beside the portal —
+ // draft the repair prompt into it so the user reviews and sends it.
+ // No receiver attached (composer still mounting, or the portal is
+ // hosted away from a conversation, e.g. the Home drawer): fall back
+ // to the clipboard so the click always hands the prompt over.
+ if (onDraftToComposer?.(repairPrompt)) {
+ toast.success({
+ placement: 'bottom',
+ style: { marginBlockEnd: 88 },
+ title: t('acceptance.bar.rerunDrafted'),
+ });
+ } else {
+ await copyToClipboard(repairPrompt);
+ toast.success({
+ placement: 'bottom',
+ style: { marginBlockEnd: 88 },
+ title: t('acceptance.bar.copied'),
+ });
+ }
+ return;
+ }
+ if (!origin?.topic) return;
+ setRerunPending(true);
+ try {
+ await dispatchRepairRerun({
+ dispatch: () =>
+ verifyService.dispatchAcceptanceRepair({
+ agentId: origin.agent?.id,
+ content: repairPrompt,
+ topicId: origin.topic!.id,
+ }),
+ markRepairing: () => verifyService.markAcceptanceRepairing(acceptance.id),
+ });
+ // The run is live from here — even if the refresh below throws or
+ // the repairing stamp failed (dispatchRepairRerun swallows it; the
+ // aggregate converges once the repair round lands), the
+ // `rerunDispatched` latch keeps Fix from double-running the repair.
+ setRerunDispatched(true);
+ await mutate();
+ void globalMutate(isAcceptanceListKey);
+ 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
diff --git a/src/features/Acceptance/Viewer/DecisionBar.test.ts b/src/features/Acceptance/Viewer/DecisionBar.test.ts
index 9e3b1edea13..e6c64f1bb25 100644
--- a/src/features/Acceptance/Viewer/DecisionBar.test.ts
+++ b/src/features/Acceptance/Viewer/DecisionBar.test.ts
@@ -3,7 +3,17 @@ import { describe, expect, it } from 'vitest';
import verify from '../../../../packages/locales/src/default/verify';
describe('DecisionBar copy', () => {
- it('uses the copy prompt as the repair handoff', () => {
+ it('keeps the copy prompt action and uses Fix for rerunning the repair', () => {
+ // Regression (#18843): the rerun handoff was collapsed into copy-only.
+ // Embedded drafts into the composer; standalone dispatches to the origin
+ // conversation — both hang off these keys.
expect(verify['acceptance.bar.copyReview']).toBe('Copy review prompt');
+ expect(verify['acceptance.bar.rerun']).toBe('Fix');
+ expect(verify['acceptance.bar.rerunDrafted']).toBe(
+ 'Drafted into your composer — review and send it.',
+ );
+ expect(verify['acceptance.bar.rerunSent']).toBe(
+ 'Sent to the origin conversation — the repair round is starting.',
+ );
});
});
diff --git a/src/features/Acceptance/Viewer/DecisionBar.tsx b/src/features/Acceptance/Viewer/DecisionBar.tsx
index ece7ba6fe38..de09aa7a502 100644
--- a/src/features/Acceptance/Viewer/DecisionBar.tsx
+++ b/src/features/Acceptance/Viewer/DecisionBar.tsx
@@ -129,6 +129,9 @@ ProgressRing.displayName = 'AcceptanceProgressRing';
interface DecisionBarProps {
/** Checks the user has signed off, of `totalCount` reviewable ones. */
acceptedCount: number;
+ /** Rendered inside the conversation portal — the composer beside the bar
+ receives the repair draft, so the copy handoff stays standalone-only. */
+ embedded?: boolean;
/** Active (not-yet-consumed) feedback recorded this round. */
feedbackCount: number;
/** Checks removed from the acceptance scope by the reviewer. */
@@ -143,10 +146,16 @@ interface DecisionBarProps {
onOpenFeedback: () => void;
/** Open the aggregate reject dialog (comment required). */
onRejectComment: () => void;
+ /** Start the repair round: embedded, drafts the prompt into the composer
+ beside the bar; standalone, dispatches it to the origin conversation. */
+ onRerun: () => void;
pending: boolean;
/** A live round that is a dispatched repair — coloured as an in-progress task
(warning), not a neutral verify, to match the system's task-process cue. */
repairing?: boolean;
+ /** The origin conversation is known — the rerun dispatch has a target. */
+ rerunAvailable: boolean;
+ rerunPending: boolean;
state: BarState;
/** The state line, prepared by the page (status + counts wording). */
statusText: string;
@@ -158,13 +167,16 @@ interface DecisionBarProps {
* The floating decision strip (P-12): review progress, the feedback
* clearing-list opener, and the closing actions. What the actions are follows
* the review state — feedback queued for the next round turns the bar into a
- * repair handoff (copy the review prompt);
+ * repair handoff (打回重跑: embedded drafts the prompt into the composer
+ * beside the bar, standalone dispatches to the origin conversation, with copy
+ * as the standalone-only manual fallback);
* a clean review offers reject-with-comment and accept, with accept gaining
* primary weight only once every check is signed off.
*/
const DecisionBar = memo<DecisionBarProps>(
({
acceptedCount,
+ embedded,
feedbackCount,
ignoredCount,
needsFixCount,
@@ -173,8 +185,11 @@ const DecisionBar = memo<DecisionBarProps>(
onCopyReview,
onOpenFeedback,
onRejectComment,
+ onRerun,
pending,
repairing,
+ rerunAvailable,
+ rerunPending,
state,
statusText,
subText,
@@ -275,14 +290,11 @@ const DecisionBar = memo<DecisionBarProps>(
<div style={{ flex: 1, minWidth: 8 }} />
- {/* Copy is the universal repair handoff across standalone and embedded views. */}
- {state === 'live' && hasFeedback && (
- <Button
- disabled={pending}
- style={{ flex: 'none' }}
- type={'primary'}
- onClick={onCopyReview}
- >
+ {/* A dispatched send-back (repairing) keeps the copy entry alive —
+ the reviewer may still hand the prompt to another agent. Embedded,
+ the composer beside it already receives the draft. */}
+ {state === 'live' && hasFeedback && !embedded && (
+ <Button disabled={pending} style={{ flex: 'none' }} type={'fill'} onClick={onCopyReview}>
{t('acceptance.bar.copyReview')}
</Button>
)}
@@ -292,6 +304,16 @@ const DecisionBar = memo<DecisionBarProps>(
// Feedback is queued — the delivery isn't being accepted now; the
// bar's job is getting the repair round started.
<>
+ {!embedded && (
+ <Button
+ disabled={pending}
+ style={{ flex: 'none' }}
+ type={'fill'}
+ onClick={onCopyReview}
+ >
+ {t('acceptance.bar.copyReview')}
+ </Button>
+ )}
{/* Last words before the repair leaves — a global note the next
round reads, for what the queued per-check feedback missed. */}
<Button
@@ -303,14 +325,17 @@ const DecisionBar = memo<DecisionBarProps>(
>
{t('acceptance.bar.addComment')}
</Button>
- <Button
- disabled={pending}
- style={{ flex: 'none' }}
- type={'primary'}
- onClick={onCopyReview}
- >
- {t('acceptance.bar.copyReview')}
- </Button>
+ {rerunAvailable && (
+ <Button
+ disabled={pending}
+ loading={rerunPending}
+ style={{ flex: 'none' }}
+ type={'primary'}
+ onClick={onRerun}
+ >
+ {t('acceptance.bar.rerun')}
+ </Button>
+ )}
</>
) : (
// Clean review — accept carries primary weight only once every
diff --git a/src/features/Acceptance/Viewer/index.tsx b/src/features/Acceptance/Viewer/index.tsx
index 93e5a34b999..28a030f25e4 100644
--- a/src/features/Acceptance/Viewer/index.tsx
+++ b/src/features/Acceptance/Viewer/index.tsx
@@ -38,9 +38,13 @@ const styles = createStaticStyles(({ css }) => ({
interface AcceptancePageProps {
acceptanceId?: string;
+ onDraftToComposer?: (text: string) => boolean;
}
-const AcceptancePage = ({ acceptanceId: explicitAcceptanceId }: AcceptancePageProps) => {
+const AcceptancePage = ({
+ acceptanceId: explicitAcceptanceId,
+ onDraftToComposer,
+}: AcceptancePageProps) => {
const params = useParams<{ acceptanceId: string; checkId: string }>();
const acceptanceId = explicitAcceptanceId ?? extractUuid(params.acceptanceId);
const embedded = Boolean(explicitAcceptanceId);
@@ -79,7 +83,7 @@ const AcceptancePage = ({ acceptanceId: explicitAcceptanceId }: AcceptancePagePr
reportSlot={<AcceptanceViewReportLink />}
/>
<AcceptanceCheckInventory toolbar={<AcceptanceCheckOwnerToolbar />} />
- <AcceptanceDecision />
+ <AcceptanceDecision onDraftToComposer={onDraftToComposer} />
</>
)}
</Flexbox>
diff --git a/src/features/Acceptance/Viewer/repairRerun.test.ts b/src/features/Acceptance/Viewer/repairRerun.test.ts
new file mode 100644
index 00000000000..f8da9085277
--- /dev/null
+++ b/src/features/Acceptance/Viewer/repairRerun.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { dispatchRepairRerun } from './repairRerun';
+
+describe('dispatchRepairRerun', () => {
+ it('marks repairing after a successful dispatch', async () => {
+ const markRepairing = vi.fn().mockResolvedValue(undefined);
+
+ const outcome = await dispatchRepairRerun({
+ dispatch: vi.fn().mockResolvedValue(undefined),
+ markRepairing,
+ });
+
+ expect(outcome).toEqual({ dispatched: true, markFailed: false });
+ expect(markRepairing).toHaveBeenCalledTimes(1);
+ });
+
+ it('propagates a dispatch failure so the caller may retry', async () => {
+ const markRepairing = vi.fn();
+
+ await expect(
+ dispatchRepairRerun({
+ dispatch: vi.fn().mockRejectedValue(new Error('network')),
+ markRepairing,
+ }),
+ ).rejects.toThrow('network');
+ // Nothing started server-side — the repairing stamp must not run.
+ expect(markRepairing).not.toHaveBeenCalled();
+ });
+
+ it('reports a dispatched run even when the repairing stamp fails', async () => {
+ // Codex P1: a failure AFTER the dispatch must not read as retryable — the
+ // repair run is already live, and retrying would double-run it.
+ const outcome = await dispatchRepairRerun({
+ dispatch: vi.fn().mockResolvedValue(undefined),
+ markRepairing: vi.fn().mockRejectedValue(new Error('stamp failed')),
+ });
+
+ expect(outcome).toEqual({ dispatched: true, markFailed: true });
+ });
+});
diff --git a/src/features/Acceptance/Viewer/repairRerun.ts b/src/features/Acceptance/Viewer/repairRerun.ts
new file mode 100644
index 00000000000..d4ef58f13ed
--- /dev/null
+++ b/src/features/Acceptance/Viewer/repairRerun.ts
@@ -0,0 +1,33 @@
+export interface RepairRerunOutcome {
+ /** The repair prompt reached the origin conversation — the agent run has
+ started, so offering a retry would double-run the repair. */
+ dispatched: boolean;
+ /** Post-dispatch bookkeeping (the `repairing` stamp) failed. Surface it if
+ needed, but never re-enable the dispatch: the run is already live and the
+ aggregate status converges when the next round lands. */
+ markFailed: boolean;
+}
+
+/**
+ * The standalone send-back is two server calls with different retry semantics:
+ * a failed dispatch is safe to retry, while anything after a successful
+ * dispatch is not. Collapse that boundary into one outcome so the caller
+ * cannot accidentally treat "mark failed" as "dispatch failed".
+ */
+export const dispatchRepairRerun = async ({
+ dispatch,
+ markRepairing,
+}: {
+ dispatch: () => Promise<unknown>;
+ markRepairing: () => Promise<unknown>;
+}): Promise<RepairRerunOutcome> => {
+ // Let a dispatch failure propagate — nothing started, the caller may retry.
+ await dispatch();
+
+ try {
+ await markRepairing();
+ return { dispatched: true, markFailed: false };
+ } catch {
+ return { dispatched: true, markFailed: true };
+ }
+};
diff --git a/src/features/Conversation/Markdown/plugins/LocalFile/index.ts b/src/features/Conversation/Markdown/plugins/LocalFile/index.ts
index b68691e1bd8..b1fe3189e6b 100644
--- a/src/features/Conversation/Markdown/plugins/LocalFile/index.ts
+++ b/src/features/Conversation/Markdown/plugins/LocalFile/index.ts
@@ -11,7 +11,10 @@ import RenderComponent from './Render';
const LocalFileElement: MarkdownElement = {
Component: RenderComponent as FC<MarkdownElementProps>,
remarkPlugin: createRemarkSelfClosingTagPlugin(LOCAL_FILE_TAG),
- scope: 'assistant',
+ // The chat input serializes attached files to `<localFile … />`, so user
+ // messages rendered from plain markdown (history replay / sync / share)
+ // need this plugin too — not only assistant output.
+ scope: 'all',
tag: LOCAL_FILE_TAG,
};
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/ProcessFold.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ProcessFold.tsx
index 206d4f1a388..ac6ebb6612d 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/ProcessFold.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/ProcessFold.tsx
@@ -29,7 +29,9 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
* package's `:hover` background rule without an `!important`.
*/
const HEADER_STYLE = { background: 'transparent', margin: 0 } as const;
-const TRIGGER_STYLE = { padding: 0 } as const;
+/** `font: inherit` drops the trigger's built-in 500 weight so the summary row
+ * reads as plain body text instead of a heading. */
+const TRIGGER_STYLE = { font: 'inherit', padding: 0 } as const;
/** The stripped header has no padding of its own, so the expanded process would
* otherwise start flush against it. */
const CONTENT_STYLE = { paddingBlockStart: 8 } as const;
diff --git a/src/features/Conversation/Messages/User/useMarkdown.test.ts b/src/features/Conversation/Messages/User/useMarkdown.test.ts
new file mode 100644
index 00000000000..95be64b4fdc
--- /dev/null
+++ b/src/features/Conversation/Messages/User/useMarkdown.test.ts
@@ -0,0 +1,42 @@
+import { renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { markdownElements } from '../../Markdown/plugins';
+import { useMarkdown } from './useMarkdown';
+
+// The hook only wires plugins/components; stub the long-content preview so the
+// test does not pull the full store tree.
+vi.mock('./components/ContentPreview', () => ({
+ default: () => null,
+}));
+
+const remarkPluginFor = (tag: string) =>
+ markdownElements.find((el) => el.tag === tag)?.remarkPlugin;
+
+describe('useMarkdown (user message pipeline)', () => {
+ it('includes the localFile plugin so file chips survive plain-markdown user messages', () => {
+ const { result } = renderHook(() => useMarkdown('u1'));
+
+ const remarkPlugins = result.current.remarkPlugins ?? [];
+
+ // The chat input serializes attachments to `<localFile … />`. When a user
+ // message renders from plain `content` (history replay / sync / share)
+ // instead of Lexical editorData, dropping this plugin silently swallows
+ // the chip. Before the fix, LocalFile was `scope: 'assistant'`.
+ const localFilePlugin = remarkPluginFor('localFile');
+ expect(localFilePlugin).toBeTruthy();
+ expect(remarkPlugins).toContain(localFilePlugin);
+ });
+
+ it('still excludes assistant-scoped plugins', () => {
+ const { result } = renderHook(() => useMarkdown('u2'));
+
+ const remarkPlugins = result.current.remarkPlugins ?? [];
+
+ const assistantScoped = markdownElements.find(
+ (el) => el.scope === 'assistant' && el.remarkPlugin,
+ );
+ expect(assistantScoped).toBeTruthy();
+ expect(remarkPlugins).not.toContain(assistantScoped!.remarkPlugin);
+ });
+});
diff --git a/src/features/Conversation/Messages/useChatMarkdown.test.tsx b/src/features/Conversation/Messages/useChatMarkdown.test.tsx
index 164a8815cf6..2f71a95fba8 100644
--- a/src/features/Conversation/Messages/useChatMarkdown.test.tsx
+++ b/src/features/Conversation/Messages/useChatMarkdown.test.tsx
@@ -43,7 +43,7 @@ describe('useChatMarkdown (assistant / grouped message pipeline)', () => {
const { result } = renderHook(() => useChatMarkdown({ id: 'a2', isGenerating: false }));
const remarkPlugins = result.current.markdownProps.remarkPlugins ?? [];
- // Sanity: an assistant-scoped plugin (e.g. LocalFile) is still wired in, so
+ // Sanity: an assistant-scoped plugin (e.g. LobeThinking) is still wired in, so
// the filter narrowed the set rather than emptying it.
const assistantScoped = markdownElements.find(
(el) => el.scope === 'assistant' && el.remarkPlugin,
diff --git a/src/features/LocalFile/LocalFile.tsx b/src/features/LocalFile/LocalFile.tsx
index 5fdf40d9d5a..9338d4ec3a4 100644
--- a/src/features/LocalFile/LocalFile.tsx
+++ b/src/features/LocalFile/LocalFile.tsx
@@ -1,12 +1,13 @@
import { Flexbox, Popover } from '@lobehub/ui';
import { Button } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
-import { ExternalLink, FolderOpen } from 'lucide-react';
+import { ExternalLink, EyeIcon, FolderOpen } from 'lucide-react';
import React from 'react';
import { useTranslation } from 'react-i18next';
import FileIcon from '@/components/FileIcon';
-import { localFileService } from '@/services/electron/localFileService';
+
+import { useLocalFileActions } from './useLocalFileActions';
const styles = createStaticStyles(({ css }) => ({
container: css`
@@ -22,6 +23,11 @@ const styles = createStaticStyles(({ css }) => ({
color: ${cssVar.colorText};
background: ${cssVar.colorFillTertiary};
}
+
+ &:focus-visible {
+ outline: 2px solid ${cssVar.colorPrimaryBorder};
+ outline-offset: 1px;
+ }
`,
title: css`
overflow: hidden;
@@ -52,16 +58,8 @@ export const LocalFile = ({
readonly = false,
}: LocalFileProps) => {
const { t } = useTranslation('components');
-
- const handleOpenFile = () => {
- if (!path) return;
- localFileService.openLocalFileOrFolder(path, isDirectory);
- };
-
- const handleOpenFolder = () => {
- if (!path) return;
- localFileService.openFileFolder(path);
- };
+ const { canPreview, handleClick, handleOpenFile, handleOpenFolder, handlePreview } =
+ useLocalFileActions({ isDirectory, path, readonly });
const fileContent = (
<Flexbox
@@ -69,8 +67,21 @@ export const LocalFile = ({
align={'center'}
className={styles.container}
gap={4}
+ // Inline chip, not a <button> (block layout inside markdown prose) — so
+ // give the clickable state complete button semantics by hand.
+ role={handleClick ? 'button' : undefined}
style={{ display: 'inline-flex', verticalAlign: 'middle' }}
- onClick={isDirectory ? handleOpenFile : undefined}
+ tabIndex={handleClick ? 0 : undefined}
+ onClick={handleClick}
+ onKeyDown={
+ handleClick
+ ? (event) => {
+ if (event.key !== 'Enter' && event.key !== ' ') return;
+ event.preventDefault();
+ handleClick();
+ }
+ : undefined
+ }
>
<FileIcon fileName={name} isDirectory={isDirectory} size={22} variant={'raw'} />
<Flexbox horizontal align={'baseline'} gap={4} style={{ overflow: 'hidden', width: '100%' }}>
@@ -84,9 +95,19 @@ export const LocalFile = ({
return fileContent;
}
- // File: show popover with two actions
+ // File: show popover with actions
const popoverContent = (
<Flexbox horizontal gap={4} padding={4}>
+ {canPreview && (
+ <Button
+ icon={EyeIcon}
+ size="small"
+ title={t('LocalFile.action.preview')}
+ onClick={handlePreview}
+ >
+ {t('LocalFile.action.preview')}
+ </Button>
+ )}
<Button
icon={ExternalLink}
size="small"
diff --git a/src/features/LocalFile/useLocalFileActions.test.ts b/src/features/LocalFile/useLocalFileActions.test.ts
new file mode 100644
index 00000000000..8cb0128676a
--- /dev/null
+++ b/src/features/LocalFile/useLocalFileActions.test.ts
@@ -0,0 +1,111 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { useChatStore } from '@/store/chat';
+import { createLocalFileTabId } from '@/store/chat/slices/portal/helpers';
+
+import { useLocalFileActions } from './useLocalFileActions';
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...((await importOriginal()) as Record<string, unknown>),
+ isDesktop: true,
+}));
+
+const openLocalFileOrFolder = vi.hoisted(() => vi.fn());
+
+vi.mock('@/services/electron/localFileService', () => ({
+ localFileService: {
+ openFileFolder: vi.fn(),
+ openLocalFileOrFolder,
+ },
+}));
+
+const setWorkingDirectory = (workingDirectory: string) => {
+ useChatStore.setState({
+ activeAgentId: 'agent-1',
+ activeTopicId: 'topic-1',
+ topicDataMap: {
+ 'agent_agent-1': {
+ items: [{ id: 'topic-1', metadata: { workingDirectory } }],
+ total: 1,
+ },
+ } as any,
+ });
+};
+
+describe('useLocalFileActions', () => {
+ afterEach(() => {
+ useChatStore.setState(useChatStore.getInitialState());
+ vi.clearAllMocks();
+ });
+
+ it('opens the right-side portal preview when clicking a file chip', () => {
+ setWorkingDirectory('/Users/me/project');
+
+ const { result } = renderHook(() =>
+ useLocalFileActions({ path: '/Users/me/project/Deck_v8.pptx' }),
+ );
+
+ expect(result.current.canPreview).toBe(true);
+ result.current.handleClick!();
+
+ expect(useChatStore.getState().openLocalFiles).toEqual([
+ {
+ allowExternalFilePreview: false,
+ filePath: '/Users/me/project/Deck_v8.pptx',
+ id: createLocalFileTabId({
+ filePath: '/Users/me/project/Deck_v8.pptx',
+ workingDirectory: '/Users/me/project',
+ }),
+ workingDirectory: '/Users/me/project',
+ },
+ ]);
+ expect(useChatStore.getState().showPortal).toBe(true);
+ expect(openLocalFileOrFolder).not.toHaveBeenCalled();
+ });
+
+ it('marks files outside the current workspace as external previews', () => {
+ setWorkingDirectory('/Users/me/project');
+
+ const { result } = renderHook(() => useLocalFileActions({ path: '/tmp/demo.html' }));
+
+ result.current.handleClick!();
+
+ expect(useChatStore.getState().openLocalFiles).toEqual([
+ {
+ allowExternalFilePreview: true,
+ filePath: '/tmp/demo.html',
+ id: createLocalFileTabId({ filePath: '/tmp/demo.html', workingDirectory: '/tmp' }),
+ workingDirectory: '/tmp',
+ },
+ ]);
+ });
+
+ it('keeps opening directories in the system instead of the portal', () => {
+ setWorkingDirectory('/Users/me/project');
+
+ const { result } = renderHook(() =>
+ useLocalFileActions({ isDirectory: true, path: '/Users/me/project/docs' }),
+ );
+
+ expect(result.current.canPreview).toBe(false);
+ result.current.handleClick!();
+
+ expect(openLocalFileOrFolder).toHaveBeenCalledWith('/Users/me/project/docs', true);
+ expect(useChatStore.getState().openLocalFiles).toHaveLength(0);
+ });
+
+ it('exposes no click action in readonly mode (share pages)', () => {
+ setWorkingDirectory('/Users/me/project');
+
+ const { result } = renderHook(() =>
+ useLocalFileActions({ path: '/Users/me/project/Deck_v8.pptx', readonly: true }),
+ );
+
+ expect(result.current.canPreview).toBe(false);
+ expect(result.current.handleClick).toBeUndefined();
+ });
+});
diff --git a/src/features/LocalFile/useLocalFileActions.ts b/src/features/LocalFile/useLocalFileActions.ts
new file mode 100644
index 00000000000..b9f472c28f0
--- /dev/null
+++ b/src/features/LocalFile/useLocalFileActions.ts
@@ -0,0 +1,60 @@
+import { isDesktop } from '@lobechat/const';
+
+import { parseLocalFileHref } from '@/features/Conversation/Markdown/plugins/LocalFileLink/parse';
+import { localFileService } from '@/services/electron/localFileService';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+
+interface UseLocalFileActionsParams {
+ isDirectory?: boolean;
+ path?: string;
+ readonly?: boolean;
+}
+
+export const useLocalFileActions = ({
+ isDirectory = false,
+ path,
+ readonly = false,
+}: UseLocalFileActionsParams) => {
+ const openLocalFile = useChatStore((s) => s.openLocalFile);
+ const workingDirectory = useChatStore(topicSelectors.currentTopicWorkingDirectory);
+
+ const parsed =
+ isDesktop && !readonly && !isDirectory ? parseLocalFileHref(path, { workingDirectory }) : null;
+ const allowExternalFilePreview =
+ !!parsed && (!workingDirectory || parsed.workingDirectory !== workingDirectory);
+
+ const handlePreview = () => {
+ if (!parsed) return;
+ openLocalFile({
+ allowExternalFilePreview,
+ filePath: parsed.filePath,
+ workingDirectory: parsed.workingDirectory,
+ });
+ };
+
+ const handleOpenFile = () => {
+ if (!path) return;
+ localFileService.openLocalFileOrFolder(path, isDirectory);
+ };
+
+ const handleOpenFolder = () => {
+ if (!path) return;
+ localFileService.openFileFolder(path);
+ };
+
+ const handleClick = readonly
+ ? undefined
+ : () => {
+ if (isDirectory) return handleOpenFile();
+ if (parsed) return handlePreview();
+ };
+
+ return {
+ canPreview: !!parsed,
+ handleClick,
+ handleOpenFile,
+ handleOpenFolder,
+ handlePreview,
+ };
+};
diff --git a/src/features/Portal/Acceptance/Body.test.tsx b/src/features/Portal/Acceptance/Body.test.tsx
index 880dbb2cb0a..572e8ef1682 100644
--- a/src/features/Portal/Acceptance/Body.test.tsx
+++ b/src/features/Portal/Acceptance/Body.test.tsx
@@ -1,10 +1,12 @@
import { render } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { draftToMainComposer, useComposerDraftBus } from '@/features/Conversation/composerDraftBus';
import Body from './Body';
const mocks = vi.hoisted(() => ({
- acceptanceId: undefined as string | undefined,
+ captured: { onDraftToComposer: undefined as undefined | ((text: string) => boolean) },
}));
vi.mock('@/store/chat', () => ({
@@ -28,8 +30,11 @@ vi.mock('@/features/Conversation/store', () => ({
}));
vi.mock('@/features/Acceptance', () => ({
- AcceptanceViewer: (props: { acceptanceId?: string }) => {
- mocks.acceptanceId = props.acceptanceId;
+ AcceptanceViewer: (props: {
+ initialCheckId?: string;
+ onDraftToComposer?: (text: string) => boolean;
+ }) => {
+ mocks.captured.onDraftToComposer = props.onDraftToComposer;
return null;
},
OriginConversationProvider: ({ children }: { children?: React.ReactNode }) => children,
@@ -37,9 +42,33 @@ vi.mock('@/features/Acceptance', () => ({
vi.mock('@/features/Acceptance/Viewer/TopicPanel', () => ({ default: () => null }));
-describe('Portal Acceptance Body', () => {
+describe('Portal Acceptance Body — draftToComposer via the global bus', () => {
+ beforeEach(() => {
+ useComposerDraftBus.setState({ attached: false, draft: null });
+ });
+
it('renders outside ConversationProvider without touching the context store', () => {
expect(() => render(<Body />)).not.toThrow();
- expect(mocks.acceptanceId).toBe('acc-1');
+ // The poster is the plain bus function — no context-store closure involved.
+ expect(mocks.captured.onDraftToComposer).toBe(draftToMainComposer);
+ });
+
+ it('posts the draft to the bus when a receiver is attached', () => {
+ useComposerDraftBus.setState({ attached: true });
+ render(<Body />);
+
+ const ok = mocks.captured.onDraftToComposer?.('please fix X');
+
+ expect(ok).toBe(true);
+ expect(useComposerDraftBus.getState().draft).toEqual({ text: 'please fix X' });
+ });
+
+ it('reports failure (so the caller skips its toast) when no composer is listening', () => {
+ render(<Body />);
+
+ const ok = mocks.captured.onDraftToComposer?.('please fix X');
+
+ expect(ok).toBe(false);
+ expect(useComposerDraftBus.getState().draft).toBeNull();
});
});
diff --git a/src/features/Portal/Acceptance/Body.tsx b/src/features/Portal/Acceptance/Body.tsx
index 1555dead7bc..8ca20b1506d 100644
--- a/src/features/Portal/Acceptance/Body.tsx
+++ b/src/features/Portal/Acceptance/Body.tsx
@@ -2,15 +2,21 @@ import { memo } from 'react';
import { AcceptanceViewer, OriginConversationProvider } from '@/features/Acceptance';
import TopicPanel from '@/features/Acceptance/Viewer/TopicPanel';
+import { draftToMainComposer } from '@/features/Conversation/composerDraftBus';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
const Body = memo(() => {
const acceptanceId = useChatStore(chatPortalSelectors.acceptancePortalId);
+ // The portal pane is a layout SIBLING of the conversation column, not a
+ // descendant of its ConversationProvider — reading useConversationStore here
+ // throws ("no zustand provider as an ancestor") and blanks the page. Drafts
+ // go through the global composerDraftBus; ComposerDraftReceiver applies them
+ // inside the provider (setDocument + inputMessage sync + focus).
return (
<OriginConversationProvider TopicPanel={TopicPanel}>
- <AcceptanceViewer acceptanceId={acceptanceId} />
+ <AcceptanceViewer acceptanceId={acceptanceId} onDraftToComposer={draftToMainComposer} />
</OriginConversationProvider>
);
});