Skip to content

Commit 1e379bc

Browse files
committed
feat(mobile): cite selected assistant text in the composer
1 parent 6328c84 commit 1e379bc

10 files changed

Lines changed: 170 additions & 16 deletions

‎apps/mobile/src/components/ComposerEditor.tsx‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { collectAssistantCitations } from "@t3tools/shared/assistantCitations";
12
import * as Dialog from "./ui/Dialog";
23
import { ComposerContextId } from "@t3tools/contracts";
34
import { useAtomValue } from "@effect/atom-react";
@@ -189,6 +190,37 @@ export function ComposerEditor({
189190
onInertChipPress?.();
190191
return;
191192
}
193+
const citation = collectAssistantCitations(selection.source)[0]?.citation;
194+
if (citation) {
195+
Dialog.alert(
196+
"Assistant quote",
197+
citation.comment
198+
? `${citation.text}\n\nYour comment: ${citation.comment}`
199+
: citation.text,
200+
[
201+
{ text: "Done", style: "cancel" },
202+
...(!props.readOnly && props.editable !== false
203+
? [
204+
{
205+
text: "Remove quote",
206+
style: "destructive" as const,
207+
onPress: () => {
208+
const current = draftKey
209+
? getComposerDraftSnapshot(draftKey).text
210+
: props.value;
211+
if (current.slice(selection.start, selection.end) === selection.source) {
212+
changeText(
213+
current.slice(0, selection.start) + current.slice(selection.end),
214+
);
215+
}
216+
},
217+
},
218+
]
219+
: []),
220+
],
221+
);
222+
return;
223+
}
192224
const path = composerMentionPath(selection.source, draft.context);
193225
if (path && onOpenMention) {
194226
onOpenMention(path);

‎apps/mobile/src/features/threads/ThreadDetailScreen.tsx‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import { voiceInputBlocksSubmission } from "@t3tools/client-runtime/voice-input";
2+
import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations";
3+
import type { AssistantCitation } from "@t3tools/contracts";
14
import { useOpenThreadInspector } from "./thread-inspector-navigation";
25
import { useSidebarWorkspaceTabs } from "../workspace/useSystemWorkspaceTabBar";
36
import { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext";
@@ -125,7 +128,11 @@ import { useAppearancePreferences } from "../settings/appearance/AppearancePrefe
125128
import { collectProviderUsageLimits } from "@t3tools/shared/usageLimits";
126129
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
127130
import type { StatusTone } from "../../components/StatusPill";
128-
import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
131+
import {
132+
captureComposerDraftInsertion,
133+
rememberComposerDraftSelection,
134+
getComposerDraftSnapshot,
135+
} from "../../state/use-composer-drafts";
129136
import { RenderErrorBoundary, RenderFailureView } from "../../components/RenderErrorBoundary";
130137
import {
131138
ANDROID_READING_MAX_WIDTH,
@@ -1284,6 +1291,33 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {
12841291
composerEditorRef.current?.blur();
12851292
};
12861293

1294+
const canCiteAssistantText =
1295+
props.composerDraftKey !== null &&
1296+
!props.isSavingQueuedEdit &&
1297+
!props.draftMode?.interactionLocked;
1298+
const handleCiteAssistantText = (citation: AssistantCitation) => {
1299+
if (!canCiteAssistantText || props.composerDraftKey === null) return;
1300+
const voice = voiceInputSession.getSnapshot();
1301+
if (voice.ownerKey === props.composerDraftKey && voiceInputBlocksSubmission(voice.state)) {
1302+
Dialog.alert(
1303+
"Finish voice input first",
1304+
"You can cite this text after recording or transcription finishes.",
1305+
);
1306+
return;
1307+
}
1308+
const { text: draft, start, end } = captureComposerDraftInsertion(props.composerDraftKey);
1309+
const before = draft.slice(0, start);
1310+
const insertion = `${before && !/\s$/.test(before) ? " " : ""}${serializeAssistantCitation(citation)} `;
1311+
const next = before + insertion + draft.slice(end);
1312+
const cursor = start + insertion.length;
1313+
rememberComposerDraftSelection(props.composerDraftKey, next, { start: cursor, end: cursor });
1314+
props.onChangeDraftMessage(next);
1315+
requestAnimationFrame(() => {
1316+
composerEditorRef.current?.focus();
1317+
composerEditorRef.current?.setSelection({ start: cursor, end: cursor });
1318+
});
1319+
};
1320+
12871321
const handleUseArtifactTemplate = (template: CodexArtifactTemplate) => {
12881322
const draftMessage =
12891323
props.composerDraftKey === null ? "" : getComposerDraftSnapshot(props.composerDraftKey).text;
@@ -1420,6 +1454,7 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {
14201454
onEndFollowEnabledChange={handleEndFollowEnabledChange}
14211455
skills={selectedProviderSkills}
14221456
onUseArtifactTemplate={handleUseArtifactTemplate}
1457+
onCiteAssistantText={canCiteAssistantText ? handleCiteAssistantText : undefined}
14231458
/>
14241459
</RenderErrorBoundary>
14251460
</View>

‎apps/mobile/src/features/threads/ThreadFeed.tsx‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import type { SelectableMarkdownTextProps } from "../../native/SelectableMarkdownText.types";
2+
import { ASSISTANT_CITATION_MAX_TEXT_LENGTH, type AssistantCitation } from "@t3tools/contracts";
13
import { Button } from "../../components/ui/Button";
24
import * as Dialog from "../../components/ui/Dialog";
35
import { useOpenPullRequest } from "../../native/useOpenPullRequest";
@@ -373,6 +375,7 @@ export interface ThreadFeedProps {
373375
readonly onEndFollowEnabledChange?: (enabled: boolean) => void;
374376
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
375377
readonly onUseArtifactTemplate?: (template: CodexArtifactTemplate) => void;
378+
readonly onCiteAssistantText?: (citation: AssistantCitation) => void;
376379
}
377380

378381
async function waitForThreadShell(
@@ -1179,6 +1182,7 @@ function ArtifactTemplateCard(props: {
11791182

11801183
const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: {
11811184
readonly markdown: string;
1185+
readonly onCiteSelection?: SelectableMarkdownTextProps["onCiteSelection"];
11821186
readonly environmentId: EnvironmentId;
11831187
readonly markdownStyles: MarkdownStyleSet;
11841188
readonly linkHandlers: MarkdownLinkHandlers;
@@ -1197,6 +1201,7 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: {
11971201
return (
11981202
<AssistantMarkdownBlocks
11991203
markdown={liveMarkdown}
1204+
onCiteSelection={props.onCiteSelection}
12001205
markdownStyles={props.markdownStyles}
12011206
linkHandlers={linkHandlers}
12021207
onUseArtifactTemplate={props.onUseArtifactTemplate}
@@ -1209,6 +1214,7 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: {
12091214
// Folds split first, so an artifact card inside a fold stays inside it.
12101215
function AssistantMarkdownBlocks(props: {
12111216
readonly markdown: string;
1217+
readonly onCiteSelection?: SelectableMarkdownTextProps["onCiteSelection"];
12121218
readonly markdownStyles: MarkdownStyleSet;
12131219
readonly linkHandlers: MarkdownLinkHandlers;
12141220
readonly onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined;
@@ -1252,6 +1258,7 @@ function AssistantMarkdownBlocks(props: {
12521258
<SelectableMarkdownText
12531259
key={`markdown:${offset}`}
12541260
markdown={renderCodexInlineDirectivesAsMarkdown(segment.markdown)}
1261+
onCiteSelection={props.onCiteSelection}
12551262
skills={props.skills}
12561263
textStyle={props.markdownStyles.nativeTextStyle}
12571264
{...props.linkHandlers}
@@ -1656,6 +1663,7 @@ function renderFeedEntry(
16561663
ThreadFeedProps,
16571664
| "environmentId"
16581665
| "onUseArtifactTemplate"
1666+
| "onCiteAssistantText"
16591667
| "skills"
16601668
| "dispatchingMessageId"
16611669
| "onEditPendingMessage"
@@ -2254,6 +2262,31 @@ function renderFeedEntry(
22542262
<MarkdownImageAvailableWidthContext value={props.markdownContentWidth}>
22552263
<AssistantMarkdownContent
22562264
markdown={renderedText}
2265+
onCiteSelection={
2266+
props.onCiteAssistantText
2267+
? ({ text, selection }) => {
2268+
if (!text.trim()) return;
2269+
if (text.length > ASSISTANT_CITATION_MAX_TEXT_LENGTH) {
2270+
Dialog.alert(
2271+
"Select a shorter quote",
2272+
`Quotes can contain up to ${ASSISTANT_CITATION_MAX_TEXT_LENGTH.toLocaleString()} characters.`,
2273+
);
2274+
return;
2275+
}
2276+
props.onCiteAssistantText?.({
2277+
version: 1,
2278+
environmentId: props.environmentId,
2279+
threadId: props.threadId,
2280+
messageId: message.id,
2281+
text,
2282+
start: selection.start,
2283+
end: Math.max(selection.end, selection.start + 1),
2284+
prefix: "",
2285+
suffix: "",
2286+
});
2287+
}
2288+
: undefined
2289+
}
22572290
environmentId={props.environmentId}
22582291
markdownStyles={styles}
22592292
linkHandlers={props.markdownLinkHandlers}
@@ -3596,6 +3629,7 @@ export const ThreadFeed = memo(function ThreadFeed({
35963629
dispatchingMessageId: props.dispatchingMessageId,
35973630
onEditPendingMessage: props.onEditPendingMessage,
35983631
onUseArtifactTemplate: props.onUseArtifactTemplate,
3632+
onCiteAssistantText: props.onCiteAssistantText,
35993633
threadId: props.threadId,
36003634
copiedRowId,
36013635
expandedWorkRows,

‎apps/mobile/src/lib/composerContext.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
1+
import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations";
12
import {
23
ComposerContextId,
4+
EnvironmentId,
5+
ThreadId,
6+
MessageId,
37
type OrchestrationMessageContext,
48
type ServerProviderSkill,
59
} from "@t3tools/contracts";
@@ -156,6 +160,28 @@ describe("mobile composer context", () => {
156160
expect(createComposerContextHistory()(source)?.records).toEqual([]);
157161
});
158162
it("keeps exact source positions and repeated references alongside existing native tokens", () => {
163+
const citation = serializeAssistantCitation({
164+
version: 1,
165+
environmentId: EnvironmentId.make("env"),
166+
threadId: ThreadId.make("thread"),
167+
messageId: MessageId.make("message"),
168+
text: "Use $HOME and @file.ts",
169+
start: 0,
170+
end: 22,
171+
prefix: "",
172+
suffix: "",
173+
});
174+
const quoted = composerContextEditorTokens(`Before ${citation} after`, [], new Set());
175+
expect(quoted).toMatchObject([
176+
{
177+
type: "citation",
178+
source: citation,
179+
value: "Use $HOME and @file.ts",
180+
start: 7,
181+
end: 7 + citation.length,
182+
},
183+
]);
184+
expect(serializeComposerMessageForServer(citation, undefined).text).toBe(citation);
159185
const reference = formatComposerContextReference(terminal);
160186
const text = `Use $babysit with $disabled $agentOnly $HOME $PATH $anything $notaskill $20 $20k and [app.ts](src/app.ts) with ${reference} then ${reference}`;
161187
const babysit: ServerProviderSkill = {

‎apps/mobile/src/lib/composerContext.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
import {
2+
collectAssistantCitations,
3+
assistantCitationLabel,
4+
} from "@t3tools/shared/assistantCitations";
15
import { isProviderSkillUserInvocable } from "@t3tools/client-runtime/providerSkills";
26
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
37
import { filePreviewKind } from "@t3tools/shared/filePreview";
@@ -169,13 +173,20 @@ export function composerContextEditorTokens(
169173
knownSkills: { has(name: string): boolean },
170174
) {
171175
const references = collectComposerContextReferences(text);
176+
const citations = collectAssistantCitations(text);
177+
const referencesAndCitations = [...references, ...citations];
172178
return [
173179
...tokens.filter(
174180
(token) =>
175181
// `$HOME` and other `$name` text that is not one of the provider's skills stays prose.
176182
(token.type !== "skill" || knownSkills.has(token.value)) &&
177-
!references.some((ref) => token.start < ref.end && token.end > ref.start),
183+
!referencesAndCitations.some((ref) => token.start < ref.end && token.end > ref.start),
178184
),
185+
...citations.map((ref) => ({
186+
...ref,
187+
type: "citation" as const,
188+
value: assistantCitationLabel(ref.citation),
189+
})),
179190
...references.map((ref) => ({
180191
type: "context" as const,
181192
value: ref.label,

‎apps/mobile/src/native/EnrichedMarkdownText.tsx‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,11 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
329329
flavor="github"
330330
selectable
331331
selectionClipboard={selectionClipboard}
332+
contextMenuItems={
333+
props.onCiteSelection
334+
? [{ text: "Cite", icon: "quote.bubble", onPress: props.onCiteSelection }]
335+
: undefined
336+
}
332337
selectionColor={props.textStyle.selectionColor}
333338
selectionHandleColor={props.textStyle.selectionHandleColor}
334339
md4cFlags={{

‎apps/mobile/src/native/SelectableMarkdownText.types.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,10 @@ export interface MarkdownLinkCustomization {
6464

6565
export interface SelectableMarkdownTextProps {
6666
readonly markdown: string;
67+
readonly onCiteSelection?: (selection: {
68+
text: string;
69+
selection: { start: number; end: number };
70+
}) => void;
6771
readonly textStyle: NativeMarkdownTextStyle;
6872
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
6973
readonly preserveSoftBreaks?: boolean;

‎apps/mobile/src/native/T3ComposerEditor.ios.tsx‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ export function ComposerEditor({
184184
? props.context?.records.find((record) => record.contextId === token.contextId)
185185
: undefined;
186186
const presentation = contextChipPresentation(
187-
token.type === "context" ? token.kind : token.type,
187+
token.type === "context" ? token.kind : token.type === "citation" ? "thread" : token.type,
188188
record,
189189
);
190190
const icon = contextChipIcon(
@@ -198,11 +198,13 @@ export function ComposerEditor({
198198
end: token.end,
199199
accent: contextChipAccent(presentation.accent, theme, chipTextColor),
200200
label:
201-
token.type === "skill"
202-
? (skillLabels.get(token.value) ?? token.value)
203-
: token.type === "context"
204-
? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
205-
: basename(token.value),
201+
token.type === "citation"
202+
? token.value
203+
: token.type === "skill"
204+
? (skillLabels.get(token.value) ?? token.value)
205+
: token.type === "context"
206+
? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
207+
: basename(token.value),
206208
detail: token.type === "context" ? composerChipSizeSuffix(record) : "",
207209
iconUri: contextChipIconUri(icon),
208210
tintsIcon: icon.kind === "chip",

‎apps/mobile/src/native/T3ComposerEditor.native.tsx‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ export function ComposerEditor({
181181
? props.context?.records.find((record) => record.contextId === token.contextId)
182182
: undefined;
183183
const presentation = contextChipPresentation(
184-
token.type === "context" ? token.kind : token.type,
184+
token.type === "context" ? token.kind : token.type === "citation" ? "thread" : token.type,
185185
record,
186186
);
187187
const icon = contextChipIcon(
@@ -195,11 +195,13 @@ export function ComposerEditor({
195195
end: token.end,
196196
accent: contextChipAccent(presentation.accent, theme, chipTextColor),
197197
label:
198-
token.type === "skill"
199-
? (skillLabels.get(token.value) ?? token.value)
200-
: token.type === "context"
201-
? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
202-
: basename(token.value),
198+
token.type === "citation"
199+
? token.value
200+
: token.type === "skill"
201+
? (skillLabels.get(token.value) ?? token.value)
202+
: token.type === "context"
203+
? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
204+
: basename(token.value),
203205
detail: token.type === "context" ? composerChipSizeSuffix(record) : "",
204206
iconUri: contextChipIconUri(icon),
205207
tintsIcon: icon.kind === "chip",

‎docs/user/composer.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,8 +132,11 @@ delete it like other inline context. Copying, reloading, and restoring a
132132
with its quote, and sending tells the agent which words were quoted and which comment you wrote.
133133
The quoted text and comment count toward the message limit.
134134

135-
Mobile displays saved quotes and comments, but does not create citations or
136-
navigate to their sources.
135+
On iPad and other native mobile clients, select text in an assistant response and
136+
choose **Cite** to insert it at the cursor in your draft. Tap the quote to read it
137+
or remove it, then add your instructions and send. Mobile displays saved quotes
138+
and comments, but does not navigate to their sources. Code blocks retain their
139+
Copy menu; citing selections inside code blocks is not supported yet.
137140

138141
## Recall a sent prompt
139142

0 commit comments

Comments
 (0)