Skip to content

Commit 1d4c43d

Browse files
fix(web): retain thread chips in question answers
1 parent 36f87ed commit 1d4c43d

8 files changed

Lines changed: 207 additions & 42 deletions

File tree

‎apps/web/src/components/ComposerPromptEditorTiptap.tsx‎

Lines changed: 30 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,8 @@ export interface ComposerPromptEditorProps {
144144
richTextEnabled?: boolean;
145145
/** Preserve editor answers verbatim, without Markdown or context chips. */
146146
literalText?: boolean;
147+
/** Hydrate self-contained thread links only while editing a question answer. */
148+
answerThreadLinks?: boolean;
147149
/** Draft records behind the prompt's context references, keyed by context id. */
148150
contextRecords: ComposerDraftContextRecords;
149151
/** Structured clipboard payload for the given referenced ids, or null to skip. */
@@ -791,7 +793,7 @@ export function ComposerPromptEditorTiptap(props: ComposerPromptEditorProps) {
791793
// Every mode initializes from the controlled value, preserving the draft.
792794
return (
793795
<ComposerPromptEditorTiptapInner
794-
key={props.literalText ? "literal" : props.richTextEnabled ? "rich" : "plain"}
796+
key={`${props.literalText ? "literal" : props.richTextEnabled ? "rich" : "plain"}:${props.answerThreadLinks ? "answer" : "draft"}`}
795797
{...props}
796798
/>
797799
);
@@ -823,6 +825,7 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
823825
cursor,
824826
richTextEnabled,
825827
literalText = false,
828+
answerThreadLinks = false,
826829
contextRecords,
827830
buildContextClipboardFragment,
828831
importContextFragment,
@@ -856,13 +859,15 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
856859
0,
857860
Math.min(text.length, Number.isFinite(position) ? Math.floor(position) : text.length),
858861
)
859-
: clampCollapsedComposerCursor(text, position),
860-
[literalText],
862+
: clampCollapsedComposerCursor(text, position, false, answerThreadLinks),
863+
[literalText, answerThreadLinks],
861864
);
862865
const expandEditorCursor = useCallback(
863866
(text: string, position: number) =>
864-
literalText ? position : expandCollapsedComposerCursor(text, position),
865-
[literalText],
867+
literalText
868+
? position
869+
: expandCollapsedComposerCursor(text, position, false, answerThreadLinks),
870+
[literalText, answerThreadLinks],
866871
);
867872

868873
const onChangeRef = useRef(onChange);
@@ -1003,11 +1008,11 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
10031008
const suppressTrigger =
10041009
literalText ||
10051010
inCodeBlock ||
1006-
isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "left") ||
1007-
isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "right");
1011+
isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "left", answerThreadLinks) ||
1012+
isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "right", answerThreadLinks);
10081013
onChangeRef.current(nextValue, nextCursor, nextExpandedCursor, suppressTrigger, contextIds);
10091014
},
1010-
[clampEditorCursor, literalText],
1015+
[clampEditorCursor, literalText, answerThreadLinks],
10111016
);
10121017

10131018
const editorAttributes = useMemo(
@@ -1165,7 +1170,7 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
11651170
description: shortDescription || found.description?.trim() || null,
11661171
};
11671172
},
1168-
{ styling: richText, literalText },
1173+
{ styling: richText, literalText, answerThreadLinks },
11691174
),
11701175
editable: !disabled,
11711176
editorProps: {
@@ -1413,7 +1418,9 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
14131418
? importPastedComposerText(clipboardData, importFragment)
14141419
: pastedText;
14151420
// Complete chips at paste boundaries just as autocomplete does.
1416-
const tokens = literalText ? [] : collectComposerPromptInlineTokens(`${text}\n`);
1421+
const tokens = literalText
1422+
? []
1423+
: collectComposerPromptInlineTokens(`${text}\n`, answerThreadLinks);
14171424
const lastToken = tokens.at(-1);
14181425
if (
14191426
(lastToken?.type === "mention" || lastToken?.type === "skill") &&
@@ -1446,7 +1453,7 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
14461453
insertMarkdownParagraphs(
14471454
text,
14481455
skillLabelFor,
1449-
{ styling: richText, blocks: !nested, literalText, literalLength },
1456+
{ styling: richText, blocks: !nested, literalText, literalLength, answerThreadLinks },
14501457
(content) => {
14511458
// Tagged on the same transaction insertContent builds, so the
14521459
// paste is one undo step of its own.
@@ -1564,7 +1571,7 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
15641571
citationRequestRef.current?.value === value ? citationRequestRef.current : null;
15651572
if (previousSnapshot.value !== value) {
15661573
editor.commands.setContent(
1567-
buildDocJson(value, skillLabelFor, { styling: richText, literalText }),
1574+
buildDocJson(value, skillLabelFor, { styling: richText, literalText, answerThreadLinks }),
15681575
{
15691576
emitUpdate: false,
15701577
},
@@ -1603,6 +1610,7 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
16031610
editor,
16041611
expandEditorCursor,
16051612
literalText,
1613+
answerThreadLinks,
16061614
richText,
16071615
skillLabelFor,
16081616
value,
@@ -1661,6 +1669,8 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
16611669
: collapseExpandedComposerCursor(
16621670
snapshotRef.current.value,
16631671
snapshotRef.current.value.length,
1672+
false,
1673+
answerThreadLinks,
16641674
),
16651675
);
16661676
},
@@ -1723,7 +1733,7 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
17231733
: edgeRect.bottom - caretRect.bottom < threshold;
17241734
},
17251735
}),
1726-
[editor, focusAt, literalText, readSnapshot],
1736+
[editor, focusAt, literalText, answerThreadLinks, readSnapshot],
17271737
);
17281738

17291739
const handleCopyCut = useCallback(
@@ -1837,7 +1847,13 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
18371847
function insertMarkdownParagraphs(
18381848
value: string,
18391849
skillLabelFor: (name: string) => SkillMeta,
1840-
options: { styling: boolean; blocks?: boolean; literalText?: boolean; literalLength?: number },
1850+
options: {
1851+
styling: boolean;
1852+
blocks?: boolean;
1853+
literalText?: boolean;
1854+
literalLength?: number;
1855+
answerThreadLinks?: boolean;
1856+
},
18411857
insertContent: (content: JSONContent[] | JSONContent) => void,
18421858
): void {
18431859
const blocks = buildTiptapContent(value, skillLabelFor, options);

‎apps/web/src/components/chat/ChatComposer.tsx‎

Lines changed: 42 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { collectThreadLinks } from "@t3tools/shared/threadLinks";
12
import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills";
23
import { useComposerTypingGuard } from "./useComposerTypingGuard";
34
import { DESKTOP_PASTE_AS_TEXT_EVENT } from "../../lib/desktopPasteAsText";
@@ -1826,6 +1827,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
18261827
const pendingUserInputs = holdingUserInput ? [] : incomingPendingUserInputs;
18271828
const activePendingProgress = holdingUserInput ? null : incomingPendingProgress;
18281829
const activePendingIsResponding = !holdingUserInput && incomingPendingIsResponding;
1830+
const answerThreadLinks = activePendingProgress?.activeQuestion != null;
18291831
const isLiteralPendingAnswer = activePendingProgress?.activeQuestion?.initialAnswer !== undefined;
18301832
// Opening a running thread resyncs for a few frames. Show the sync row, and
18311833
// hide the tasks row for it, only when the sync lasts. Logic that depends on
@@ -1959,12 +1961,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
19591961
terminalContexts: composerTerminalContexts,
19601962
reviewComments: composerReviewComments,
19611963
previewAnnotations: composerPreviewAnnotations,
1962-
threadContexts: composerThreadContexts,
1964+
threadContexts: answerThreadLinks
1965+
? collectThreadLinks(activePendingProgress?.customAnswer ?? "").map(
1966+
({ threadId, label }) => threadContextRecord({ environmentId, threadId }, label),
1967+
)
1968+
: composerThreadContexts,
19631969
images: composerImages,
19641970
files: composerFiles,
19651971
uploadsByImageId,
19661972
}),
19671973
[
1974+
answerThreadLinks,
1975+
activePendingProgress?.customAnswer,
1976+
environmentId,
19681977
composerFiles,
19691978
composerImages,
19701979
composerPreviewAnnotations,
@@ -2421,7 +2430,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
24212430
// ------------------------------------------------------------------
24222431
const [composerCursor, setComposerCursor] = useState(() => {
24232432
const value = isLiteralPendingAnswer ? (activePendingProgress?.customAnswer ?? prompt) : prompt;
2424-
return collapseExpandedComposerCursor(value, value.length, isLiteralPendingAnswer);
2433+
return collapseExpandedComposerCursor(
2434+
value,
2435+
value.length,
2436+
isLiteralPendingAnswer,
2437+
answerThreadLinks,
2438+
);
24252439
});
24262440
const {
24272441
trigger: composerTrigger,
@@ -3529,14 +3543,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
35293543
}
35303544

35313545
promptRef.current = nextCustomAnswer;
3532-
const { cursor, trigger } = composerStateAtPromptEnd(nextCustomAnswer, isLiteralPendingAnswer);
3546+
const { cursor, trigger } = composerStateAtPromptEnd(
3547+
nextCustomAnswer,
3548+
isLiteralPendingAnswer,
3549+
answerThreadLinks,
3550+
);
35333551
setComposerCursor(cursor);
35343552
resetComposerTrigger(trigger);
35353553
setComposerHighlightedItemId(null);
35363554
}, [
35373555
activePendingProgress?.customAnswer,
35383556
activePendingProgress?.activeQuestion?.id,
35393557
isLiteralPendingAnswer,
3558+
answerThreadLinks,
35403559
activePendingUserInput?.requestId,
35413560
prompt,
35423561
promptRef,
@@ -3551,7 +3570,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
35513570
setComposerHighlightedSearchKey(null);
35523571
setComposerSubmissionError(null);
35533572
setProviderInputSubmissionError(null);
3554-
const { cursor, trigger } = composerStateAtPromptEnd(promptRef.current, isLiteralPendingAnswer);
3573+
const { cursor, trigger } = composerStateAtPromptEnd(
3574+
promptRef.current,
3575+
isLiteralPendingAnswer,
3576+
answerThreadLinks,
3577+
);
35553578
setComposerCursor(cursor);
35563579
resetComposerTrigger(trigger);
35573580
setIsDragOverComposer(false);
@@ -3560,6 +3583,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
35603583
draftId,
35613584
activeThreadId,
35623585
isLiteralPendingAnswer,
3586+
answerThreadLinks,
35633587
promptRef,
35643588
resetComposerTrigger,
35653589
setIsComposerScrollCollapsed,
@@ -3900,11 +3924,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
39003924
next.text,
39013925
options?.expandedCursorAfterReplace ?? next.cursor,
39023926
isLiteralPendingAnswer,
3927+
answerThreadLinks,
39033928
);
39043929
const nextExpandedCursor = expandCollapsedComposerCursor(
39053930
next.text,
39063931
nextCursor,
39073932
isLiteralPendingAnswer,
3933+
answerThreadLinks,
39083934
);
39093935
if (options?.citationComment) {
39103936
composerEditorRef.current?.requestCitationComment({
@@ -3943,6 +3969,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
39433969
activePendingProgress?.activeQuestion,
39443970
activePendingUserInput,
39453971
isLiteralPendingAnswer,
3972+
answerThreadLinks,
39463973
onChangeActivePendingUserInputCustomAnswer,
39473974
onTypingGuardDraftChange,
39483975
promptRef,
@@ -3968,10 +3995,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
39683995
promptRef.current,
39693996
composerCursor,
39703997
isLiteralPendingAnswer,
3998+
answerThreadLinks,
39713999
),
39724000
contextIds: isLiteralPendingAnswer ? [] : collectInlineContextIds(promptRef.current),
39734001
};
3974-
}, [composerCursor, isLiteralPendingAnswer, promptRef]);
4002+
}, [composerCursor, isLiteralPendingAnswer, answerThreadLinks, promptRef]);
39754003

39764004
const resolveActiveComposerTrigger = useCallback((): {
39774005
snapshot: { value: string; cursor: number; expandedCursor: number };
@@ -6505,14 +6533,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
65056533
promptForState,
65066534
options?.cursor ?? 0,
65076535
isLiteralPendingAnswer,
6536+
answerThreadLinks,
65086537
);
65096538
setComposerHighlightedItemId(null);
65106539
setComposerCursor(cursor);
65116540
resetComposerTrigger(
65126541
options?.detectTrigger && !isLiteralPendingAnswer
65136542
? detectComposerTrigger(
65146543
promptForState,
6515-
expandCollapsedComposerCursor(promptForState, cursor),
6544+
expandCollapsedComposerCursor(
6545+
promptForState,
6546+
cursor,
6547+
isLiteralPendingAnswer,
6548+
answerThreadLinks,
6549+
),
65166550
)
65176551
: null,
65186552
);
@@ -6615,6 +6649,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
66156649
isComposerApprovalState,
66166650
isChoiceOnlyPendingQuestion,
66176651
isLiteralPendingAnswer,
6652+
answerThreadLinks,
66186653
pendingUserInputs.length,
66196654
projectSelectionRequired,
66206655
applyPromptReplacement,
@@ -7479,6 +7514,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
74797514
editorRef={composerEditorRef}
74807515
richTextEnabled={settings.composerRichTextEnabled}
74817516
literalText={isLiteralPendingAnswer}
7517+
answerThreadLinks={answerThreadLinks}
74827518
isPathQueryActive={() =>
74837519
resolveActiveComposerTrigger().trigger?.kind === "path"
74847520
}

‎apps/web/src/components/chat/composerThreadReference.test.ts‎

Lines changed: 52 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
11
// @vitest-environment jsdom
22

3-
import { Editor } from "@tiptap/core";
3+
import { Editor, Node } from "@tiptap/core";
44
import StarterKit from "@tiptap/starter-kit";
55
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
66
import { afterEach, describe, expect, it } from "vite-plus/test";
7-
import { detectComposerTrigger, replaceTextRange } from "../../composer-logic";
7+
import {
8+
collapseExpandedComposerCursor,
9+
detectComposerTrigger,
10+
replaceTextRange,
11+
} from "../../composer-logic";
812
import { buildDocJson, serializeEditorDoc } from "../../composer-rich-text-doc";
913
import { threadContextRecord } from "../../lib/composerContextRecords";
1014
import { collectInlineContextIds } from "../../lib/composerContextReferences";
@@ -18,6 +22,19 @@ const record = threadContextRecord(
1822
},
1923
"Parser [design]",
2024
);
25+
const contextReference = Node.create({
26+
name: "composer-context-reference",
27+
group: "inline",
28+
inline: true,
29+
atom: true,
30+
renderHTML: () => ["span"],
31+
addAttributes: () => ({
32+
kind: { default: "" },
33+
contextId: { default: "" },
34+
label: { default: "" },
35+
source: { default: "" },
36+
}),
37+
});
2138
let editor: Editor | undefined;
2239
afterEach(() => editor?.destroy());
2340

@@ -28,11 +45,15 @@ describe("thread references in question answers", () => {
2845
const replacement = `${composerThreadReferenceText(record, true)} `;
2946
const next = replaceTextRange(draft, trigger.rangeStart, trigger.rangeEnd + 1, replacement);
3047
editor = new Editor({
31-
extensions: [StarterKit.configure({ link: false })],
32-
content: buildDocJson(next.text, (name) => ({ label: name, description: null })),
48+
extensions: [StarterKit.configure({ link: false }), contextReference],
49+
content: buildDocJson(next.text, (name) => ({ label: name, description: null }), {
50+
answerThreadLinks: true,
51+
}),
3352
});
34-
// The answer is plain text, so Markdown offsets and editor offsets agree.
35-
editor.commands.setTextSelection(next.cursor + 1);
53+
// The link occupies one editor character while retaining its full wire source.
54+
editor.commands.setTextSelection(
55+
collapseExpandedComposerCursor(next.text, next.cursor, false, true) + 1,
56+
);
3657
editor.commands.insertContent("now ");
3758
const edited = serializeEditorDoc(editor.state.doc).value;
3859
const answers = buildPendingUserInputAnswers(
@@ -51,11 +72,36 @@ describe("thread references in question answers", () => {
5172
q: "Speak with [Parser design](t3-thread://v1/fixture-peer) now to figure this out.",
5273
});
5374
expect(collectInlineContextIds(edited)).toEqual([]);
75+
76+
// Revisit the saved answer: rebuild the atom, select it and delete it as a unit.
77+
editor.commands.setContent(
78+
buildDocJson(edited, (name) => ({ label: name, description: null }), {
79+
answerThreadLinks: true,
80+
}),
81+
);
82+
const chipPosition = "Speak with ".length + 1;
83+
const chip = editor.state.doc.nodeAt(chipPosition)!;
84+
expect(chip.type.name).toBe("composer-context-reference");
85+
expect(chip.attrs).toMatchObject({
86+
kind: "thread",
87+
contextId: record.contextId,
88+
label: "Parser design",
89+
});
90+
editor.commands.setNodeSelection(chipPosition);
91+
editor.commands.deleteSelection();
92+
expect(serializeEditorDoc(editor.state.doc).value).toBe("Speak with now to figure this out.");
5493
});
5594

5695
it("keeps normal message references bound to their context record", () => {
5796
expect(collectInlineContextIds(composerThreadReferenceText(record, false))).toEqual([
5897
record.contextId,
5998
]);
99+
const link = composerThreadReferenceText(record, true);
100+
editor = new Editor({
101+
extensions: [StarterKit.configure({ link: false }), contextReference],
102+
content: buildDocJson(link, (name) => ({ label: name, description: null })),
103+
});
104+
expect(editor.state.doc.textContent).toBe(link);
105+
expect(serializeEditorDoc(editor.state.doc).value).toBe(link);
60106
});
61107
});

0 commit comments

Comments
 (0)