Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(chat): make question file and URL references clickable

Lizieec54f5ed5cc
diff --git a/apps/desktop/scripts/fixtures/ask-user-question/ask-user-question-fixture.tsx b/apps/desktop/scripts/fixtures/ask-user-question/ask-user-question-fixture.tsx
new file mode 100644
index 0000000000..16fdc1f1a5
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/ask-user-question/ask-user-question-fixture.tsx
@@ -0,0 +1,28 @@
+import { useState } from 'react';
+import { mountPage, forbid } from '../../ui-page/harness';
+import { AskUserQuestionPrompt } from '../../../src/renderer/components/new-chat/AskUserQuestionPrompt';
+import type { AskUserDraft, AskUserViewerState } from '../../../src/renderer/lib/makerChatStore';
+
+function Fixture({ question }: { question: string }) {
+ const [draft, setDraft] = useState<AskUserDraft | null>(null);
+ const [viewerState, setViewerState] = useState<AskUserViewerState>('expanded');
+ return <main className="mx-auto w-full max-w-[720px] min-w-0 p-4">
+ <AskUserQuestionPrompt sessionId="question-evidence" workingDir="/project"
+ pending={{ requestId: 'review', questions: [{ header: '确认原型', question, options: [
+ { label: '可以,按这版实现' }, { label: '还需要调整' },
+ ] }] }}
+ onAnswer={forbid('answer question')}
+ draft={draft} onDraftChange={setDraft} viewerState={viewerState} onViewerStateChange={setViewerState} />
+ </main>;
+}
+
+void mountPage({
+ host: {
+ resolvePathBatch: async ({ hrefs }: { hrefs: string[] }) => Object.fromEntries(hrefs.map((href) => [href,
+ href === 'missing.html' ? { status: 'none', candidates: [] }
+ : href === 'ambiguous.html' ? { status: 'multiple', candidates: ['/project/a/ambiguous.html', '/project/b/ambiguous.html'] }
+ : { status: 'unique', candidates: [href.startsWith('/') ? href : '/project/' + href], kind: 'file' },
+ ])),
+ },
+ render: (ctx) => <Fixture question={String(ctx.data.question)} />,
+});
diff --git a/apps/desktop/scripts/fixtures/ask-user-question/ui-page.mjs b/apps/desktop/scripts/fixtures/ask-user-question/ui-page.mjs
new file mode 100644
index 0000000000..809c1addf2
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/ask-user-question/ui-page.mjs
@@ -0,0 +1,24 @@
+import assert from 'node:assert/strict';
+
+export default {
+ name: 'ask-user-question',
+ entry: './ask-user-question-fixture.tsx',
+ viewport: { width: 800, height: 600 },
+ real: 'AskUserQuestionPrompt, question reference parsing, verified file links, URL links, prompt shell and themes',
+ notCovered: 'Actual host file contents, browser navigation and remote connectivity; navigation is covered by component tests',
+ cases: {
+ default: { about: 'Question with a bare HTML filename and URL', data: { question: '请查看 sidebar-layout-v1.html 后确认这版交互形态是否可以进入正式实现。也可以查看 https://example.com/prototype。' } },
+ narrow: { about: 'Long references at 320 px', viewport: { width: 320, height: 600 }, data: { question: '请查看 sidebar-layout-v1.html 或 https://example.com/prototypes/a-very-long-prototype-name-before-approval 后确认。' } },
+ unresolved: { about: 'Missing and ambiguous references remain plain text', data: { question: '请查看 missing.html 和 ambiguous.html,文件尚未找到或有重名时保持普通文字。' } },
+ },
+ async ready(page) {
+ await page.getByText('确认原型').waitFor();
+ },
+ async check(page, ui) {
+ if (ui.case !== 'unresolved') await page.getByRole('link', { name: 'sidebar-layout-v1.html' }).waitFor();
+ assert.equal(await page.getByRole('link').count(), ui.case === 'unresolved' ? 0 : 2);
+ if (ui.case !== 'unresolved') {
+ assert.equal(await page.getByRole('link', { name: 'sidebar-layout-v1.html' }).evaluate((node) => getComputedStyle(node).textDecorationLine), 'underline');
+ }
+ },
+};
diff --git a/apps/desktop/src/renderer/__tests__/askUserQuestionActionLabels.test.tsx b/apps/desktop/src/renderer/__tests__/askUserQuestionActionLabels.test.tsx
index b0ce842ed1..21a5be6118 100644
--- a/apps/desktop/src/renderer/__tests__/askUserQuestionActionLabels.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/askUserQuestionActionLabels.test.tsx
@@ -6,8 +6,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import i18n from '@/i18n';
import type { PendingAskUser } from '@/lib/makerChatStore';
+import { _clearSmartResolveCache } from '@/lib/localPathResolver';
import { AskUserQuestionPrompt } from '../components/new-chat/AskUserQuestionPrompt';
+const links = vi.hoisted(() => ({ html: vi.fn(), url: vi.fn() }));
+vi.mock('@/components/chat/useOpenWithMenu', async (original) => ({
+ ...await original<typeof import('@/components/chat/useOpenWithMenu')>(),
+ openHtmlFileByPreference: links.html,
+ activateMessageUrl: links.url,
+}));
+
beforeEach(async () => {
await i18n.changeLanguage('en');
});
@@ -34,6 +42,42 @@ function renderAskUser(
}
describe('AskUserQuestionPrompt action labels', () => {
+ // Unit regression: the existing answer tests never opened evidence in a title.
+ // Minimal input: a bare HTML filename + URL. The real prompt/resolver must
+ // open the correct origin without answering, and preserve the original answer key.
+ it.each([null, 'ssh-host'])('opens verified question evidence for origin %s without answering', async (remoteHostId) => {
+ _clearSmartResolveCache();
+ links.html.mockClear();
+ links.url.mockImplementation((event) => event.preventDefault());
+ const resolvePathBatch = vi.fn(async ({ hrefs }: { hrefs: string[] }) => Object.fromEntries(hrefs.map((href) => [href,
+ href === 'sidebar-layout-v1.html'
+ ? { status: 'unique', candidates: ['/repo/sidebar-layout-v1.html'], kind: 'file' }
+ : { status: 'none', candidates: [] },
+ ])));
+ const chatStat = vi.fn(async ({ absPath }: { absPath: string }) => ({
+ verdict: absPath.endsWith('missing.html') ? 'nonfile' : 'file',
+ }));
+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { resolvePathBatch, fileBrowser: { chatStat } } });
+ const question = '请查看 sidebar-layout-v1.html 或 https://example.com/view。 missing.html';
+ const onAnswer = vi.fn();
+ const view = render(createElement(AskUserQuestionPrompt, {
+ sessionId: 'evidence', workingDir: '/repo', remoteHostId,
+ pending: { requestId: 'review', questions: [{ question, options: [{ label: 'Accept' }] }] },
+ onAnswer, viewerState: 'expanded', onViewerStateChange: vi.fn(), draft: null, onDraftChange: vi.fn(),
+ }));
+ const file = await view.findByRole('link', { name: 'sidebar-layout-v1.html' });
+ fireEvent.click(file);
+ fireEvent.keyDown(file, { key: 'Enter' });
+ expect(links.html).toHaveBeenCalledWith('evidence', '/repo/sidebar-layout-v1.html', expect.any(Function),
+ expect.objectContaining({ workingDir: '/repo', origin: remoteHostId ? { kind: 'ssh', remoteHostId } : { kind: 'local' } }));
+ fireEvent.click(view.getByRole('link', { name: 'https://example.com/view' }));
+ expect(links.url).toHaveBeenCalledWith(expect.anything(), 'evidence', 'https://example.com/view', expect.any(Function));
+ expect(onAnswer).not.toHaveBeenCalled();
+ expect(view.queryByRole('link', { name: 'missing.html' })).toBeNull();
+ if (remoteHostId) expect(resolvePathBatch).not.toHaveBeenCalled();
+ fireEvent.click(view.getByText('Accept'));
+ expect(onAnswer).toHaveBeenCalledWith('review', { [question]: 'Accept' });
+ });
it('distinguishes updating an answer from keeping it when revisiting a middle question', async () => {
const view = renderAskUser({
requestId: 'req-revisit',
diff --git a/apps/desktop/src/renderer/__tests__/cardShortcutYield.test.tsx b/apps/desktop/src/renderer/__tests__/cardShortcutYield.test.tsx
index 4588860ddb..dbaf7d5093 100644
--- a/apps/desktop/src/renderer/__tests__/cardShortcutYield.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/cardShortcutYield.test.tsx
@@ -12,7 +12,8 @@ import userEvent from '@testing-library/user-event';
import { createElement } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-vi.mock('react-i18next', () => ({
+vi.mock('react-i18next', async (original) => ({
+ ...await original<typeof import('react-i18next')>(),
useTranslation: () => ({ t: (key: string) => key }),
}));
diff --git a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
index a5b1f81752..e6603b6875 100644
--- a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
+++ b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
@@ -117,6 +117,7 @@ import { SessionHandoffCard } from './SessionHandoffCard';
import { SessionLinkChip } from './SessionLinkChip';
import { ProjectLinkChip } from './ProjectLinkChip';
import { ImageLightbox } from './ImageLightbox';
+import { splitQuestionReferences } from '@cindy/maker-shared/interaction';
import { useImageClipboard } from './useImageClipboard';
import { ImageHoverPreview } from './ImageHoverPreview';
import { ImageMissingPlaceholder } from './ImageMissingPlaceholder';
@@ -1434,6 +1435,35 @@ async function activateResolvedLocalTarget(
});
}
+/** Evidence in a question uses the same verified targets and previews as messages. */
+export function QuestionReferenceText({ text }: { text: string }) {
+ const ctx = useChatSessionFile();
+ const [image, setImage] = useState<string | null>(null);
+ const [file, setFile] = useState<{ path: string; name: string; line?: number } | null>(null);
+ const [model, setModel] = useState<string | null>(null);
+ return <>
+ {splitQuestionReferences(text).map((part, index) => part.href ? (
+ <MarkdownTargetLink
+ key={index}
+ href={part.href}
+ workingDir={ctx.workingDir}
+ sessionId={ctx.sessionId}
+ remoteMediaOrigin={toRemoteMediaOrigin(ctx.origin, ctx.workingDir)}
+ isStreaming={false}
+ allowPrivilegedLinks
+ fromBarePath
+ anchorProps={{}}
+ setLightboxSrc={setImage}
+ setTextLightboxFile={setFile}
+ setModelLightboxPath={setModel}
+ >{part.text}</MarkdownTargetLink>
+ ) : part.text)}
+ {image && <ImageLightbox src={image} onClose={() => setImage(null)} />}
+ {file && <TextLightbox filePath={file.path} fileName={file.name} initialLine={file.line} onClose={() => setFile(null)} />}
+ {model && <ModelLightbox source={{ kind: 'local', absPath: model }} onClose={() => setModel(null)} />}
+ </>;
+}
+
function MarkdownTargetLink({
href,
children,
diff --git a/apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx b/apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx
index 7820535190..7643a0fa84 100644
--- a/apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx
@@ -26,6 +26,8 @@ import { ArrowRight } from 'lucide-react';
import { visibleAskOptions } from '@cindy/maker-shared';
import { InteractionPromptCardShell } from '@/components/interaction-portal';
+import { ChatSessionFileProvider, useChatSessionFile, useChatSessionFileValue } from '@/components/chat/ChatSessionFileContext';
+import { QuestionReferenceText } from '@/components/chat/MarkdownRenderer';
import { Tip } from '@/components/ui/tooltip';
import { useAutoResize } from '@/hooks/useAutoResize';
import { shouldCardShortcutYield } from '@/lib/editableKeyboardTarget';
@@ -71,6 +73,9 @@ function AutoGrowingAnswerTextarea({
// ---------------------------------------------------------------------------
interface AskUserQuestionPromptProps {
+ sessionId?: string;
+ workingDir?: string;
+ remoteHostId?: string | null;
pending: PendingAskUser;
onAnswer: (requestId: string, answers: Record<string, string>) => void;
/**
@@ -105,8 +110,14 @@ interface AskUserQuestionPromptProps {
export function AskUserQuestionPrompt({
sessionId,
+ workingDir,
+ remoteHostId,
...props
-}: AskUserQuestionPromptProps & { sessionId: string | undefined }) {
+}: AskUserQuestionPromptProps) {
+ const inheritedFileContext = useChatSessionFile();
+ const ownFileContext = useChatSessionFileValue(sessionId, workingDir ?? '', remoteHostId);
+ const fileContext = workingDir === undefined && inheritedFileContext.sessionId === sessionId
+ ? inheritedFileContext : ownFileContext;
// Match the store's content comparison, including option order and metadata.
// Fixed field order avoids treating JSON property order as a new question;
// absent and empty options are equivalent, as in the reducer.
@@ -119,7 +130,9 @@ export function AskUserQuestionPrompt({
const formKey = JSON.stringify([sessionId, props.pending.requestId, questionsIdentity]);
// Repeated snapshots keep this form mounted. A changed session, request or
// question starts from its own draft (cleared by the store on content changes).
- return <AskUserQuestionForm key={formKey} {...props} />;
+ return <ChatSessionFileProvider value={fileContext}>
+ <AskUserQuestionForm key={formKey} {...props} />
+ </ChatSessionFileProvider>;
}
function AskUserQuestionForm({
@@ -701,8 +714,8 @@ function AskUserQuestionForm({
{/* Question Row (header chip moved to top header bar above) */}
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between">
- <span className="text-15 font-medium text-[var(--ask-header-text)]">
- {currentQ?.question}
+ <span className="min-w-0 break-words text-15 font-medium text-[var(--ask-header-text)]">
+ <QuestionReferenceText text={currentQ?.question ?? ''} />
</span>
{pageIndicator && (
<span className="ml-4 shrink-0 text-13 text-[var(--ask-page-text)]">
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 73d33c38b4..4f62ab61ff 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -5620,6 +5620,8 @@ function CCAgentSessionContent({
) : pendingAskUser ? (
<AskUserQuestionPrompt
sessionId={sessionId}
+ workingDir={session?.workingDir ?? ''}
+ remoteHostId={session?.remoteHostId}
pending={pendingAskUser}
onAnswer={answerUserQuestion}
viewerState={askUserViewerState}
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 697ddd82a9..09a76b31a0 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -10144,6 +10144,7 @@ function SessionScreenContent() {
queueFooter={(
<>
{companionInlineInteraction && !shareSelectionActive ? <InteractionPanel
+ fileContext={chatFilePathContextValue}
embedded
companion={companionChat}
companionIdentity={companionInteractionIdentity}
@@ -10374,6 +10375,7 @@ function SessionScreenContent() {
不给收起入口:收起态的文案与 a11y 都是「先不答、稍后回答」,套在它身上是
错的语义。 */}
<InteractionPanel
+ fileContext={chatFilePathContextValue}
companion={companionChat}
companionIdentity={companionInteractionIdentity}
deviceId={deviceId}
@@ -10410,6 +10412,7 @@ function SessionScreenContent() {
testID="interaction.bottomScroll"
>
<InteractionPanel
+ fileContext={chatFilePathContextValue}
companion={companionChat}
companionIdentity={companionInteractionIdentity}
safeAreaBottomInset={insets.bottom}
@@ -10437,6 +10440,7 @@ function SessionScreenContent() {
testID="interaction.bottomScroll"
>
<InteractionPanel
+ fileContext={chatFilePathContextValue}
companion={companionChat}
companionIdentity={companionInteractionIdentity}
safeAreaBottomInset={insets.bottom}
diff --git a/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx b/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx
index f48e5ac5a9..77dd99cfcb 100644
--- a/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx
+++ b/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx
@@ -9,6 +9,16 @@ import { InteractionPanel, PluginSetupMessageContent } from '@/session/Interacti
import { remoteSessionStore, useSessionPendingInteractions } from '@/session/remoteSessionStore';
import { clearAllInteractionDrafts, readAskUserDraft, readPlanReviewDraft } from '@/session/interactionDraftStore';
import { forwardNavigationLock } from '@/utils/navigationLock';
+import type { ChatFilePathContextValue } from '@/session/chatFilePathContext';
+import { _clearRemotePathVerdictCache } from '@/session/remotePathVerdict';
+
+const evidence = vi.hoisted(() => ({ openURL: vi.fn() }));
+// As in LegendList, setters are inert outside a list item. The composer card
+// needs ordinary React state to upgrade a reference after its remote stat.
+vi.mock('@legendapp/list/react-native', async () => {
+ const { useState } = await import('react');
+ return { useRecyclingState: (initial: unknown) => [useState(initial)[0], () => {}] };
+});
const { resolveInteraction, invoke, push } = vi.hoisted(() => ({ resolveInteraction: vi.fn(), invoke: vi.fn(), push: vi.fn() }));
const asyncReply = vi.hoisted(() => ({
@@ -36,11 +46,11 @@ vi.mock('react-native', async () => {
children?: ReactNode; onPress?: () => void; disabled?: boolean; testID?: string;
}) => createElement(tag, { onClick: onPress, disabled, 'data-testid': testID }, children);
// Text keeps its onTextLayout so a test can report how many lines a label took.
- const Text = ({ children, onTextLayout }: { children?: ReactNode; onTextLayout?: (event: { nativeEvent: { lines: unknown[] } }) => void }) => {
+ const Text = ({ children, onTextLayout, onPress, testID }: { children?: ReactNode; onTextLayout?: (event: { nativeEvent: { lines: unknown[] } }) => void; onPress?: () => void; testID?: string }) => {
if (onTextLayout) textLayouts.set(String(children), onTextLayout);
- return createElement('span', null, children);
+ return createElement('span', { onClick: onPress, 'data-testid': testID }, children);
};
- return { View: view('div'), Text, Pressable: view('button'),
+ return { View: view('div'), Text, Pressable: view('button'), Linking: { openURL: evidence.openURL },
ScrollView: view('div'), Image: () => null,
useWindowDimensions: () => ({ width: 390, height: 844 }),
StyleSheet: { create: (s: unknown) => s, hairlineWidth: 1 } };
@@ -71,9 +81,9 @@ let root: Root;
let host: HTMLDivElement;
const requestId = 'codex:test:0';
const onError = vi.fn();
-function Harness({ companion = false, deviceId = 'd1' }: { companion?: boolean; deviceId?: string }) {
+function Harness({ companion = false, deviceId = 'd1', fileContext }: { companion?: boolean; deviceId?: string; fileContext?: ChatFilePathContextValue }) {
const interactions = useSessionPendingInteractions('s1');
- return <InteractionPanel companion={companion} deviceId={deviceId} sessionId="s1" interactions={interactions} onError={onError} />;
+ return <InteractionPanel companion={companion} deviceId={deviceId} sessionId="s1" fileContext={fileContext} interactions={interactions} onError={onError} />;
}
function CollapsibleHarness() {
const interactions = useSessionPendingInteractions('s1');
@@ -84,6 +94,8 @@ function CollapsibleHarness() {
beforeEach(() => {
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
vi.resetAllMocks();
+ _clearRemotePathVerdictCache();
+ evidence.openURL.mockResolvedValue(undefined);
routeParams.deviceId = 'd1'; routeParams.sessionId = 's1';
forwardNavigationLock.reset();
remoteSessionStore.clear();
@@ -106,6 +118,30 @@ async function type(id: string, value: string) {
});
}
+// Unit regression: receipt tests never opened evidence in a question title.
+// Minimal input: a bare HTML filename + URL. Real card + remote stat must open
+// the controlled computer's file without resolving the question.
+it('opens question files on the controlled computer and URLs without resolving the question', async () => {
+ const onOpenPath = vi.fn();
+ const fileContext: ChatFilePathContextValue = {
+ deviceId: 'd1', sessionId: 's1', workdir: '/repo', onOpenPath,
+ statPath: vi.fn(async (absPath: string) => ({ kind: absPath.endsWith('missing.html') ? 'missing' as const : 'file' as const, resolvedPath: absPath })),
+ };
+ remoteSessionStore.setPendingInteractions('s1', [{ request: {
+ kind: 'ask_user_question', requestId,
+ questions: [{ question: '请查看 sidebar-layout-v1.html 和 https://example.com/view。 missing.html' }],
+ } }]);
+ await act(async () => root.render(<Harness fileContext={fileContext} />));
+ await click('message.markdownPathChip');
+ expect(onOpenPath).toHaveBeenCalledWith({ kind: 'file', absPath: '/repo/sidebar-layout-v1.html', relPath: 'sidebar-layout-v1.html' });
+ expect(host.querySelectorAll('[data-testid="message.markdownPathChip"]')).toHaveLength(1);
+ const url = Array.from(host.querySelectorAll('span')).find((element) => element.textContent === 'https://example.com/view')!;
+ await act(async () => url.click());
+ expect(evidence.openURL).toHaveBeenCalledWith('https://example.com/view');
+ expect(resolveInteraction).not.toHaveBeenCalled();
+ expect(host.querySelector('[data-testid="interaction.ask.card"]')).not.toBeNull();
+});
+
it.each(['push-first', 'receipt-first', 'lost-receipt', 'other-client'] as const)(
'finalizes retained answers without stale snapshot resurrection: %s',
async (order) => {
diff --git a/apps/mobile/src/__tests__/chatPathCandidate.test.ts b/apps/mobile/src/__tests__/chatPathCandidate.test.ts
index b8ef6acb7a..72250e5c61 100644
--- a/apps/mobile/src/__tests__/chatPathCandidate.test.ts
+++ b/apps/mobile/src/__tests__/chatPathCandidate.test.ts
@@ -9,7 +9,8 @@ import ts from 'typescript';
const rendererTree = ts.createSourceFile('renderer.tsx', readFileSync(join(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const pathFunctions = new Set(['ChatPathChipSpan', 'LinkPathChipSpan', 'clickableInlineStyle', 'underlineDecoration']);
-const pathCode = rendererTree.statements.filter((node) => ts.isFunctionDeclaration(node) && node.name && pathFunctions.has(node.name.text)).map((node) => node.getText(rendererTree)).join('\n');
+const spanTree = ts.createSourceFile('span.tsx', readFileSync(join(process.cwd(), 'src/session/ChatPathChipSpan.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+const pathCode = [rendererTree, spanTree].flatMap((tree) => tree.statements.filter((node) => ts.isFunctionDeclaration(node) && node.name && pathFunctions.has(node.name.text)).map((node) => node.getText(tree).replace(/^export /, ''))).join('\n');
const compiledPath = ts.transpileModule(pathCode, { compilerOptions: { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2022 } }).outputText;
const flattenStyle = (value: any): any => Array.isArray(value) ? Object.assign({}, ...value.map(flattenStyle)) : value ?? {};
const pathContext = React.createContext<any>(null);
diff --git a/apps/mobile/src/session/ChatPathChipSpan.tsx b/apps/mobile/src/session/ChatPathChipSpan.tsx
new file mode 100644
index 0000000000..08d9e3de7d
--- /dev/null
+++ b/apps/mobile/src/session/ChatPathChipSpan.tsx
@@ -0,0 +1,132 @@
+import { useCallback, useContext, useEffect, useMemo, type Dispatch, type SetStateAction } from 'react';
+import type { StyleProp, TextStyle } from 'react-native';
+import { useRecyclingState } from '@legendapp/list/react-native';
+import { Text } from '@/components/AppText';
+import { canOpenChatPathChip, resolveChatAbsPath, toWorkdirRel, type ChatPathCandidate } from '@/session/chatPathCandidate';
+import { ChatFilePathContext, type ChatFilePathTarget } from '@/session/chatFilePathContext';
+import { peekRemotePathVerdict, peekRemotePathVerdictForRender, remotePathVerdictKey, subscribeRemotePathVerdictChange, verifyRemotePathCached, type RemotePathVerdict } from '@/session/remotePathVerdict';
+
+type PathStateHook = <T>(initial: T | (() => T)) => readonly [T, Dispatch<SetStateAction<T>>];
+
+/**
+ * 文件/目录路径 chip 的共享执行体(远程会话文件交互,对齐桌面 #631 的 chip 点亮
+ * 语义)。inline code 与本地路径链接两种形态共用:候选先经被控端精确 stat 验证——
+ * 文件/目录点亮可点(文件 → Quick Look 预览页;目录 → 文件浏览器定位),明确
+ * 不存在保持纯文本,链路断等无法判定时乐观点亮(点击后预览页自己的错误 UX 兜底)。
+ * workdir 外的绝对路径同样候选(对齐桌面):文件走被控端 absPath 取件通道预览,
+ * 目录因文件浏览器只认 workdir 内而保持纯文本(canOpenChatPathChip)。
+ * 无会话上下文(context null)/ 流式中 → plainStyle 纯文本渲染。
+ */
+export function ChatPathChipSpan({
+ candidate,
+ chipStyle,
+ display,
+ plainStyle,
+ SpanText,
+ streaming,
+ usePathState = useRecyclingState,
+}: {
+ candidate: ChatPathCandidate | null;
+ chipStyle: StyleProp<TextStyle>;
+ /** span 显示文本(code 形态 = 原文;链接形态 = 链接 label)。 */
+ display: string;
+ plainStyle: StyleProp<TextStyle>;
+ SpanText: typeof Text;
+ streaming?: boolean;
+ /** Composer cards live outside LegendList, whose state setters require a list item. */
+ usePathState?: PathStateHook;
+}) {
+ const ctx = useContext(ChatFilePathContext);
+ // workdir 外候选不再一票否决:relPath 为 null 表示 workdir 外,文件仍可经
+ // absPath 通道打开,可开性由 canOpenChatPathChip 在 verdict 定 kind 后裁决。
+ const target = useMemo(() => {
+ if (!ctx || !candidate) return null;
+ const absPath = resolveChatAbsPath(candidate.href, ctx.workdir);
+ return { absPath, relPath: toWorkdirRel(ctx.workdir, absPath) };
+ }, [candidate, ctx]);
+ // verdict 是**缓存的纯派生**,chip 不自己存结论:ForRender 版会把 TTL 未过期的负缓存
+ // 回成 'unknown',于是断链期间的乐观点亮也来自缓存。自存一份的话收不到缓存变化 ——
+ // 同一路径出现在多个 chip 上时,A 按 unknown 点亮、B 拿到确定的 nonfile,A 会一直
+ // 带着下划线可点(PR #1144 review 实捉,桌面同款)。
+ const readVerdict = useCallback(
+ () =>
+ ctx && target
+ ? peekRemotePathVerdictForRender(ctx.deviceId, ctx.workdir, target.absPath)
+ : undefined,
+ [ctx, target],
+ );
+ const [verdict, setVerdict] = usePathState<RemotePathVerdict | undefined>(readVerdict);
+
+ // 本 key 的缓存变化(确定态落库 / 负缓存到期)→ 递增,**驱动下面的验证副作用重跑**。
+ // 按 key 过滤:一屏几十个 chip 各自订阅,全量广播会让首屏 N 次 stat 引发 N×N 次重渲染。
+ //
+ // ⚠️ 这里必须递增一个计数、不能只 setVerdict(readVerdict()):`readVerdict` 是
+ // `[ctx, target]` 的稳定 useCallback,通知**不改变验证副作用的任何依赖**,那个副作用
+ // 就不会重跑 → 再也不发 verifyRemotePathCached。TTL 到期时负缓存已被删、又没有确定态,
+ // ForRender 回 undefined,于是 chip 只完成「降级成纯文本」、没完成「重验」,挂载期间
+ // 永不自愈 —— 比重构前(一直乐观点亮)更糟。桌面同一处把 cacheGen 放进了验证副作用的
+ // 依赖,手机漏了这一环(PR #1144 review 实捉:第 10 轮重构只做对了桌面那一半)。
+ const [cacheGen, setCacheGen] = usePathState(0);
+ useEffect(() => {
+ if (!ctx || !target) return;
+ const mine = remotePathVerdictKey(ctx.deviceId, ctx.workdir, target.absPath);
+ return subscribeRemotePathVerdictChange((key) => {
+ if (key === mine) setCacheGen((n) => n + 1);
+ });
+ }, [ctx, target]);
+
+ useEffect(() => {
+ // 无条件按当前缓存重新派生(升级 / 降级同一条路)。
+ setVerdict(readVerdict());
+ if (!ctx || !target) return;
+ // 有确定结论就不必重验;unknown 的限流由 verifyRemotePathCached 的负缓存承担。
+ if (peekRemotePathVerdict(ctx.deviceId, ctx.workdir, target.absPath)) return;
+ // 流式中不发验证:半截路径会产生大量无意义 stat(与桌面 isStreaming gate 同理)。
+ if (streaming) return;
+ let cancelled = false;
+ void verifyRemotePathCached(ctx.deviceId, ctx.workdir, target.absPath, ctx.statPath).then(() => {
+ // 不看返回值:结论已落缓存,统一重新派生。
+ if (!cancelled) setVerdict(readVerdict());
+ });
+ return () => {
+ cancelled = true;
+ };
+ // cacheGen:本 key 的缓存状态变化(TTL 到期 / 别处写入确定态)→ 重新派生 + 必要时重验。
+ }, [ctx, streaming, target, readVerdict, cacheGen]);
+
+ // 点亮门槛分两档(见 ChatPathCandidate.ambiguousShape 的说明):
+ // - 形状明确是路径(绝对路径 / 尾斜杠目录 / 分隔符+扩展名):unknown(链路断 /
+ // stat 异常)照旧乐观点亮,绝不因断链把整条消息的 chip 全灭掉;
+ // - 歧义形状(裸名 `array.map`、分隔符无扩展 `and/or`——与 `package.json`、
+ // `src/components` 词法同形,分不开):必须等远端明确回 file / directory 才点亮。
+ // 否则链路一抖,满屏普通行内 code 都变成可点的假链接——「可点」的视觉信号一旦
+ // 不可信,加强它只会让误判更醒目(DESIGN.md §14.5 规则 5)。
+ const verdictAllowsLit = candidate?.ambiguousShape
+ ? verdict === 'file' || verdict === 'directory'
+ : verdict !== undefined && verdict !== 'nonfile';
+ const lit = !!ctx && !!candidate && !!target && verdictAllowsLit;
+ if (!lit) {
+ return <SpanText style={plainStyle}>{display}</SpanText>;
+ }
+ const kind: 'file' | 'directory' =
+ verdict === 'directory' || (verdict === 'unknown' && candidate.directoryShape) ? 'directory' : 'file';
+ if (!canOpenChatPathChip(kind, target.relPath)) {
+ return <SpanText style={plainStyle}>{display}</SpanText>;
+ }
+ const chipTarget: ChatFilePathTarget = {
+ kind,
+ relPath: target.relPath,
+ absPath: target.absPath,
+ ...(kind === 'file' && candidate.line !== undefined ? { line: candidate.line } : {}),
+ };
+ return (
+ <SpanText
+ onLongPress={ctx.onLongPressPath ? () => ctx.onLongPressPath?.(chipTarget) : undefined}
+ onPress={() => ctx.onOpenPath(chipTarget)}
+ style={chipStyle}
+ testID="message.markdownPathChip"
+ >
+ {display}
+ </SpanText>
+ );
+}
diff --git a/apps/mobile/src/session/InteractionPanel.tsx b/apps/mobile/src/session/InteractionPanel.tsx
index 8b5bafac34..4e58b108ae 100644
--- a/apps/mobile/src/session/InteractionPanel.tsx
+++ b/apps/mobile/src/session/InteractionPanel.tsx
@@ -35,6 +35,8 @@ import {
type ViewStyle,
} from 'react-native';
import { Text, TextInput } from '@/components/AppText';
+import { ChatFilePathContext, type ChatFilePathContextValue } from '@/session/chatFilePathContext';
+import { QuestionReferenceText } from '@/session/QuestionReferenceText';
import { formatRemoteError } from '@/device-link/remoteStatus';
import { useMobileMakerTransport } from '@/device-link/useMobileMakerTransport';
import { asyncQuestionNeedsSupplement, formatAsyncQuestionSupplement } from '@cindy/maker-shared/interaction';
@@ -129,7 +131,8 @@ const CompanionInteractionContext = createContext(false);
export interface CompanionInteractionIdentity { name: string; avatar?: ReactNode }
const CompanionIdentityContext = createContext<CompanionInteractionIdentity | null>(null);
-export function InteractionPanel({ companionIdentity, hangFromAvatar = false, ...props }: Parameters<typeof InteractionPanelContent>[0] & {
+export function InteractionPanel({ companionIdentity, hangFromAvatar = false, fileContext, ...props }: Parameters<typeof InteractionPanelContent>[0] & {
+ fileContext?: ChatFilePathContextValue | null;
companion?: boolean;
companionIdentity?: CompanionInteractionIdentity | null;
/**
@@ -139,7 +142,9 @@ export function InteractionPanel({ companionIdentity, hangFromAvatar = false, ..
hangFromAvatar?: boolean;
}) {
const identity = props.companion === true && companionIdentity?.name ? companionIdentity : null;
- const content = <InteractionPanelContent {...props} />;
+ const panel = <InteractionPanelContent {...props} />;
+ const content = fileContext === undefined ? panel
+ : <ChatFilePathContext.Provider value={fileContext}>{panel}</ChatFilePathContext.Provider>;
return <CompanionInteractionContext.Provider value={props.companion === true}>
<CompanionIdentityContext.Provider value={identity}>
<CompanionHungContext.Provider value={hangFromAvatar && !!identity?.avatar}>
@@ -1051,7 +1056,7 @@ function AskUserQuestionForm({
return (
<View style={cardStyle(styles, touchLayout, companion)} testID="interaction.ask.card">
<Text style={styles.kind}>{t('interaction.panel.awaitingAnswer')}</Text>
- <Text style={styles.askQuestion} testID="interaction.ask.question">{presentation.title}</Text>
+ <Text style={styles.askQuestion} testID="interaction.ask.question"><QuestionReferenceText text={presentation.title} /></Text>
<Text style={styles.askMetaCaption}>{presentation.summary.detail}</Text>
<InteractionActions touchLayout={touchLayout}>
<ResolveButton
@@ -1158,7 +1163,7 @@ function AskUserQuestionForm({
<Text style={styles.pageText}>{presentation.pageLabel}</Text>
</View>
</View>
- <Text style={styles.askQuestion} testID="interaction.ask.question">{presentation.title}</Text>
+ <Text style={styles.askQuestion} testID="interaction.ask.question"><QuestionReferenceText text={presentation.title} /></Text>
<Text style={styles.askMetaCaption}>{metaCaption}</Text>
{options.length > 0 ? (
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index 6372e7823f..6a704ba32b 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -244,24 +244,13 @@ import {
type SessionDeepLinkTarget,
} from '@/session/sessionLinks';
import {
- canOpenChatPathChip,
chatPathLabelReadsAsFileReference,
classifyChatPathLinkTarget,
classifyInlineCodePathCandidate,
- resolveChatAbsPath,
- toWorkdirRel,
- type ChatPathCandidate,
} from '@/session/chatPathCandidate';
-import { ChatFilePathContext, type ChatFilePathTarget } from '@/session/chatFilePathContext';
+import { ChatFilePathContext } from '@/session/chatFilePathContext';
import { MailLinkSpan } from '@/session/MailLinkSpan';
-import {
- peekRemotePathVerdict,
- peekRemotePathVerdictForRender,
- remotePathVerdictKey,
- subscribeRemotePathVerdictChange,
- verifyRemotePathCached,
- type RemotePathVerdict,
-} from '@/session/remotePathVerdict';
+import { ChatPathChipSpan } from '@/session/ChatPathChipSpan';
import {
useRemoteDeviceIdentity,
useRemoteSessionMessages,
@@ -6085,126 +6074,6 @@ function MarkdownBodyBase({
);
}
-/**
- * 文件/目录路径 chip 的共享执行体(远程会话文件交互,对齐桌面 #631 的 chip 点亮
- * 语义)。inline code 与本地路径链接两种形态共用:候选先经被控端精确 stat 验证——
- * 文件/目录点亮可点(文件 → Quick Look 预览页;目录 → 文件浏览器定位),明确
- * 不存在保持纯文本,链路断等无法判定时乐观点亮(点击后预览页自己的错误 UX 兜底)。
- * workdir 外的绝对路径同样候选(对齐桌面):文件走被控端 absPath 取件通道预览,
- * 目录因文件浏览器只认 workdir 内而保持纯文本(canOpenChatPathChip)。
- * 无会话上下文(context null)/ 流式中 → plainStyle 纯文本渲染。
- */
-function ChatPathChipSpan({
- candidate,
- chipStyle,
- display,
- plainStyle,
- SpanText,
- streaming,
-}: {
- candidate: ChatPathCandidate | null;
- chipStyle: StyleProp<TextStyle>;
- /** span 显示文本(code 形态 = 原文;链接形态 = 链接 label)。 */
- display: string;
- plainStyle: StyleProp<TextStyle>;
- SpanText: typeof Text;
- streaming?: boolean;
-}) {
- const ctx = useContext(ChatFilePathContext);
- // workdir 外候选不再一票否决:relPath 为 null 表示 workdir 外,文件仍可经
- // absPath 通道打开,可开性由 canOpenChatPathChip 在 verdict 定 kind 后裁决。
- const target = useMemo(() => {
- if (!ctx || !candidate) return null;
- const absPath = resolveChatAbsPath(candidate.href, ctx.workdir);
- return { absPath, relPath: toWorkdirRel(ctx.workdir, absPath) };
- }, [candidate, ctx]);
- // verdict 是**缓存的纯派生**,chip 不自己存结论:ForRender 版会把 TTL 未过期的负缓存
- // 回成 'unknown',于是断链期间的乐观点亮也来自缓存。自存一份的话收不到缓存变化 ——
- // 同一路径出现在多个 chip 上时,A 按 unknown 点亮、B 拿到确定的 nonfile,A 会一直
- // 带着下划线可点(PR #1144 review 实捉,桌面同款)。
- const readVerdict = useCallback(
- () =>
- ctx && target
- ? peekRemotePathVerdictForRender(ctx.deviceId, ctx.workdir, target.absPath)
- : undefined,
- [ctx, target],
- );
- const [verdict, setVerdict] = useRecyclingState<RemotePathVerdict | undefined>(readVerdict);
-
- // 本 key 的缓存变化(确定态落库 / 负缓存到期)→ 递增,**驱动下面的验证副作用重跑**。
- // 按 key 过滤:一屏几十个 chip 各自订阅,全量广播会让首屏 N 次 stat 引发 N×N 次重渲染。
- //
- // ⚠️ 这里必须递增一个计数、不能只 setVerdict(readVerdict()):`readVerdict` 是
- // `[ctx, target]` 的稳定 useCallback,通知**不改变验证副作用的任何依赖**,那个副作用
- // 就不会重跑 → 再也不发 verifyRemotePathCached。TTL 到期时负缓存已被删、又没有确定态,
- // ForRender 回 undefined,于是 chip 只完成「降级成纯文本」、没完成「重验」,挂载期间
- // 永不自愈 —— 比重构前(一直乐观点亮)更糟。桌面同一处把 cacheGen 放进了验证副作用的
- // 依赖,手机漏了这一环(PR #1144 review 实捉:第 10 轮重构只做对了桌面那一半)。
- const [cacheGen, setCacheGen] = useRecyclingState(0);
- useEffect(() => {
- if (!ctx || !target) return;
- const mine = remotePathVerdictKey(ctx.deviceId, ctx.workdir, target.absPath);
- return subscribeRemotePathVerdictChange((key) => {
- if (key === mine) setCacheGen((n) => n + 1);
- });
- }, [ctx, target]);
-
- useEffect(() => {
- // 无条件按当前缓存重新派生(升级 / 降级同一条路)。
- setVerdict(readVerdict());
- if (!ctx || !target) return;
- // 有确定结论就不必重验;unknown 的限流由 verifyRemotePathCached 的负缓存承担。
- if (peekRemotePathVerdict(ctx.deviceId, ctx.workdir, target.absPath)) return;
- // 流式中不发验证:半截路径会产生大量无意义 stat(与桌面 isStreaming gate 同理)。
- if (streaming) return;
- let cancelled = false;
- void verifyRemotePathCached(ctx.deviceId, ctx.workdir, target.absPath, ctx.statPath).then(() => {
- // 不看返回值:结论已落缓存,统一重新派生。
- if (!cancelled) setVerdict(readVerdict());
- });
- return () => {
- cancelled = true;
- };
- // cacheGen:本 key 的缓存状态变化(TTL 到期 / 别处写入确定态)→ 重新派生 + 必要时重验。
- }, [ctx, streaming, target, readVerdict, cacheGen]);
-
- // 点亮门槛分两档(见 ChatPathCandidate.ambiguousShape 的说明):
- // - 形状明确是路径(绝对路径 / 尾斜杠目录 / 分隔符+扩展名):unknown(链路断 /
- // stat 异常)照旧乐观点亮,绝不因断链把整条消息的 chip 全灭掉;
- // - 歧义形状(裸名 `array.map`、分隔符无扩展 `and/or`——与 `package.json`、
- // `src/components` 词法同形,分不开):必须等远端明确回 file / directory 才点亮。
- // 否则链路一抖,满屏普通行内 code 都变成可点的假链接——「可点」的视觉信号一旦
- // 不可信,加强它只会让误判更醒目(DESIGN.md §14.5 规则 5)。
- const verdictAllowsLit = candidate?.ambiguousShape
- ? verdict === 'file' || verdict === 'directory'
- : verdict !== undefined && verdict !== 'nonfile';
- const lit = !!ctx && !!candidate && !!target && verdictAllowsLit;
- if (!lit) {
- return <SpanText style={plainStyle}>{display}</SpanText>;
- }
- const kind: 'file' | 'directory' =
- verdict === 'directory' || (verdict === 'unknown' && candidate.directoryShape) ? 'directory' : 'file';
- if (!canOpenChatPathChip(kind, target.relPath)) {
- return <SpanText style={plainStyle}>{display}</SpanText>;
- }
- const chipTarget: ChatFilePathTarget = {
- kind,
- relPath: target.relPath,
- absPath: target.absPath,
- ...(kind === 'file' && candidate.line !== undefined ? { line: candidate.line } : {}),
- };
- return (
- <SpanText
- onLongPress={ctx.onLongPressPath ? () => ctx.onLongPressPath?.(chipTarget) : undefined}
- onPress={() => ctx.onOpenPath(chipTarget)}
- style={chipStyle}
- testID="message.markdownPathChip"
- >
- {display}
- </SpanText>
- );
-}
-
/**
* 「下划线 ⇔ 可点」的**唯一判据**(DESIGN.md §14.5 规则①要求双向成立:可点的一定有
* 下划线,有下划线的一定可点)。onPress 缺席时不给 `markdownLink`,所以在结构上
diff --git a/apps/mobile/src/session/QuestionReferenceText.tsx b/apps/mobile/src/session/QuestionReferenceText.tsx
new file mode 100644
index 0000000000..2e505102b4
--- /dev/null
+++ b/apps/mobile/src/session/QuestionReferenceText.tsx
@@ -0,0 +1,25 @@
+import { Fragment, useState } from 'react';
+import { Linking } from 'react-native';
+import { Text } from '@/components/AppText';
+import { splitQuestionReferences } from '@cindy/maker-shared/interaction';
+import { ChatPathChipSpan } from '@/session/ChatPathChipSpan';
+import { classifyChatPathLinkTarget } from '@/session/chatPathCandidate';
+
+/** Inline evidence inherits question typography; only verified links are underlined. */
+export function QuestionReferenceText({ text }: { text: string }) {
+ return <>{splitQuestionReferences(text).map((part, index) => {
+ if (!part.href) return <Fragment key={index}>{part.text}</Fragment>;
+ if (/^https?:\/\//i.test(part.href)) {
+ const href = part.href;
+ return <Text key={index} accessibilityRole="link" style={{ textDecorationLine: 'underline' }}
+ onPress={(event) => {
+ event.stopPropagation();
+ void Linking.openURL(href).catch(() => undefined);
+ }}>
+ {part.text}
+ </Text>;
+ }
+ return <ChatPathChipSpan key={index} candidate={classifyChatPathLinkTarget(part.href)}
+ display={part.text} plainStyle={undefined} chipStyle={{ textDecorationLine: 'underline' }} SpanText={Text} usePathState={useState} />;
+ })}</>;
+}
diff --git a/packages/maker-shared/src/__tests__/interaction.test.ts b/packages/maker-shared/src/__tests__/interaction.test.ts
index c67e1d7acb..4877b7f395 100644
--- a/packages/maker-shared/src/__tests__/interaction.test.ts
+++ b/packages/maker-shared/src/__tests__/interaction.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from 'vitest';
import {
+ splitQuestionReferences,
asyncQuestionNeedsSupplement,
formatAsyncQuestionSupplement,
buildAskQuestionProgressSummary,
@@ -39,6 +40,30 @@ import {
} from '../interaction.js';
describe('interaction shared model', () => {
+ // Unit regression: existing question presentation tests only covered prose.
+ // Bug: review questions hid the only way to open their evidence.
+ // exercise the shared presentation entry, including punctuation and unsafe links.
+ it('finds question evidence without consuming prose or unsupported link targets', () => {
+ expect(splitQuestionReferences('请查看 sidebar-layout-v1.html 或 https://example.com/view。再确认。')).toEqual([
+ { text: '请查看 ' },
+ { text: 'sidebar-layout-v1.html', href: 'sidebar-layout-v1.html' },
+ { text: ' 或 ' },
+ { text: 'https://example.com/view', href: 'https://example.com/view' },
+ { text: '。再确认。' },
+ ]);
+ expect(splitQuestionReferences('[查看原型](<docs/my prototype.html>) 与 `src/app.ts:42`')).toEqual([
+ { text: '查看原型', href: 'docs/my prototype.html' },
+ { text: ' 与 ' },
+ { text: 'src/app.ts:42', href: 'src/app.ts:42' },
+ ]);
+ expect(splitQuestionReferences('[坏链接](javascript:evil.html) data:evil.html')).toEqual([
+ { text: '[坏链接](javascript:evil.html) data:evil.html' },
+ ]);
+ expect(splitQuestionReferences('请查看 页面.html:42 和 docs/设计稿/index.html')).toEqual([
+ { text: '请查看 ' }, { text: '页面.html:42', href: '页面.html:42' },
+ { text: ' 和 ' }, { text: 'docs/设计稿/index.html', href: 'docs/设计稿/index.html' },
+ ]);
+ });
it('keeps original questions attached to late answers without including skipped questions', () => {
expect(formatAsyncQuestionSupplement([{ question: 'Scope?\nDetails?', header: 'Scope' }, { question: 'Skipped?' }],
{ Scope: 'Mobile too', 'Skipped?': '' })).toBe('> Scope?\n> Details?\n\nMobile too');
diff --git a/packages/maker-shared/src/interaction.ts b/packages/maker-shared/src/interaction.ts
index 23e6d9e226..e211324833 100644
--- a/packages/maker-shared/src/interaction.ts
+++ b/packages/maker-shared/src/interaction.ts
@@ -1,4 +1,5 @@
import { presentationText, type PresentationLocalizer } from './presentationLocalization.js';
+export { splitQuestionReferences } from './questionReferences.js';
export interface InteractionRequestLike {
kind?: string;
diff --git a/packages/maker-shared/src/questionReferences.ts b/packages/maker-shared/src/questionReferences.ts
new file mode 100644
index 0000000000..40e8c08a10
--- /dev/null
+++ b/packages/maker-shared/src/questionReferences.ts
@@ -0,0 +1,63 @@
+import { BARE_HTTP_URL_RE_SOURCE, clipBareHttpAutolinkText } from './urlTextBoundary.js';
+
+export interface QuestionReferencePart {
+ text: string;
+ href?: string;
+}
+
+// Questions are plain text with optional evidence references, not full Markdown.
+// Only identify candidates here: each client still verifies files using its
+// existing session-aware resolver before making them clickable.
+const FILE_REFERENCE = /^[^?#\n]+\.[A-Za-z0-9]{1,10}(?::[1-9]\d*(?::[1-9]\d*)?)?$/;
+const OTHER_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*:/;
+
+function isReference(href: string): boolean {
+ if (/^https?:\/\//i.test(href)) return true;
+ const drivePath = /^[A-Za-z]:/.test(href) && (href[2] === '/' || href.charCodeAt(2) === 92);
+ const withoutLine = href.replace(/:[1-9]\d*(?::[1-9]\d*)?$/, '');
+ if (OTHER_SCHEME.test(withoutLine) && !drivePath && !href.startsWith('file://')) return false;
+ if (href.startsWith('~/') || (href[0] === '~' && href.charCodeAt(1) === 92)) return false;
+ return FILE_REFERENCE.test(href);
+}
+
+/** Preserve prose and answer keys; recognize labelled links, code and bare files/URLs. */
+export function splitQuestionReferences(text: string): QuestionReferencePart[] {
+ const parts: QuestionReferencePart[] = [];
+ const append = (part: QuestionReferencePart) => {
+ const previous = parts.at(-1);
+ if (!part.href && previous && !previous.href) previous.text += part.text;
+ else if (part.text) parts.push(part);
+ };
+ const token = new RegExp(
+ [
+ /\[([^\]\n]+)\]\((?:<([^>\n]+)>|([^\s()]+(?:\([^\n()]*\)[^\s()]*)?))\)/.source,
+ /\u0060([^\u0060\n]+)\u0060/.source,
+ BARE_HTTP_URL_RE_SOURCE,
+ /(?<![^\s((【「"',、;;])[^\s,。!?;:()【】「」、()"'<>\[\]\u0060]+/.source,
+ ].join('|'),
+ 'g',
+ );
+ let from = 0;
+ for (const match of text.matchAll(token)) {
+ const index = match.index!;
+ append({ text: text.slice(from, index) });
+ const raw = match[0];
+ if (match[1] !== undefined) {
+ const href = (match[2] ?? match[3]).trim();
+ append(isReference(href) ? { text: match[1], href } : { text: raw });
+ } else if (match[4] !== undefined) {
+ append(isReference(match[4]) ? { text: match[4], href: match[4] } : { text: raw });
+ } else if (/^https?:\/\//i.test(raw)) {
+ const href = clipBareHttpAutolinkText(raw, { prefix: text.slice(0, index) });
+ append({ text: href, href });
+ append({ text: raw.slice(href.length) });
+ } else {
+ const href = raw.replace(/[.,;!?]+$/, '');
+ append(isReference(href) ? { text: href, href } : { text: href });
+ append({ text: raw.slice(href.length) });
+ }
+ from = index + raw.length;
+ }
+ append({ text: text.slice(from) });
+ return parts;
+}