Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions apps/mobile/src/components/AssistantCitationSheet.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { ASSISTANT_CITATION_MAX_COMMENT_LENGTH, type AssistantCitation } from "@t3tools/contracts";
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
import { useState } from "react";
import { Platform, ScrollView, TextInput, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useOpenLinkedThread } from "../features/threads/useOpenLinkedThread";
import { requestThreadMessageJump } from "../features/threads/threadMessageJump";
import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
import { AppText as Text } from "./ui/AppText";
import { ListActionRow } from "./ui/ListActionRow";
import { ListSection } from "./ui/ListSection";
import { Sheet } from "./ui/Sheet";

const CONTEXT_CHARS = 80;

function contextBefore(prefix: string) {
const flat = prefix.replace(/\s+/g, " ");
if (flat.length <= CONTEXT_CHARS) return flat.trimStart();
const cut = flat.slice(-CONTEXT_CHARS);
return `…${cut.slice(cut.indexOf(" ") + 1)}`;
}

function contextAfter(suffix: string) {
const flat = suffix.replace(/\s+/g, " ");
if (flat.length <= CONTEXT_CHARS) return flat.trimEnd();
const cut = flat.slice(0, CONTEXT_CHARS);
return `${cut.slice(0, cut.lastIndexOf(" "))}…`;
}

export function AssistantCitationSheet(props: {
readonly citation: AssistantCitation;
readonly onClose: () => void;
readonly onRemove?: () => void;
readonly onCommentChange?: (comment: string) => void;
}) {
const openLinkedThread = useOpenLinkedThread();
const insets = useSafeAreaInsets();
const citation = props.citation;
const [comment, setComment] = useState(citation.comment ?? "");
const close = () => {
if (props.onCommentChange && comment.trim() !== (citation.comment ?? "")) {
props.onCommentChange(comment);
}
props.onClose();
};
return (
<Sheet title="Quote" onClose={close}>
<ScrollView
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
contentContainerStyle={{
paddingHorizontal: 20,
paddingTop: 12,
gap: 24,
paddingBottom: Math.max(20, insets.bottom),
}}
>
<View className="flex-row gap-3 rounded-2xl bg-grouped-card p-4">
<View className="w-1 rounded-full bg-primary" />
<Text selectable textRole="body" className="min-w-0 flex-1 text-foreground-muted">
{contextBefore(citation.prefix)}
<Text className="font-t3-medium text-foreground">{citation.text}</Text>
{contextAfter(citation.suffix)}
</Text>
</View>
{props.onCommentChange ? (
<ListSection title="Comment">
<TextInput
accessibilityLabel="Comment on quote"
placeholder="Add an optional comment…"
placeholderTextColorClassName="accent-foreground-muted"
multiline
maxLength={ASSISTANT_CITATION_MAX_COMMENT_LENGTH}
value={comment}
onChangeText={setComment}
className="min-h-24 px-4 py-3 text-base text-foreground"
style={{ textAlignVertical: "top" }}
/>
</ListSection>
) : citation.comment ? (
<ListSection title="Comment">
<Text selectable textRole="body" className="px-4 py-3 text-foreground">
{citation.comment}
</Text>
</ListSection>
) : null}
<ListSection>
<ListActionRow
icon="arrow.up.right"
label="Go to message"
onPress={() => {
close();
requestThreadMessageJump(scopedThreadKey(citation), citation.messageId);
openLinkedThread(citation);
}}
/>
<ListActionRow
icon="doc.on.doc"
label="Copy quote"
onPress={() => copyTextWithHaptic(citation.text)}
/>
{props.onRemove ? (
<ListActionRow
icon="trash"
label="Remove from draft"
tone="danger"
onPress={props.onRemove}
/>
) : null}
</ListSection>
</ScrollView>
</Sheet>
);
}
57 changes: 44 additions & 13 deletions apps/mobile/src/components/ComposerEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ import { useEffect, useState } from "react";
import type { EnvironmentId } from "@t3tools/contracts";
import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences";
import {
collectAssistantCitations,
serializeAssistantCitation,
withAssistantCitationComment,
} from "@t3tools/shared/assistantCitations";
import { AssistantCitationSheet } from "./AssistantCitationSheet";
import { ComposerEditor as NativeComposerEditor } from "../native/T3ComposerEditor";
import type { ComposerEditorProps as NativeComposerEditorProps } from "../native/T3ComposerEditor";
import {
Expand Down Expand Up @@ -164,13 +170,42 @@ export function ComposerEditor({
const selectedReference = selected
? collectComposerContextReferences(selected.source)[0]
: undefined;
const selectedCitation = selected
? collectAssistantCitations(selected.source)[0]?.citation
: undefined;
const selectedSkillName = selected?.source.match(/^\p{Sc}(.+)$/u)?.[1];
const selectedSkill = selectedSkillName
? props.skills?.find((skill) => skill.name === selectedSkillName)
: undefined;
const record = draft.context?.records.find(
(entry) => entry.contextId === selectedReference?.contextId,
);
const removeSelected =
props.readOnly || props.editable === false
? undefined
: () => {
if (!selected) return;
if (props.value.slice(selected.start, selected.end) === selected.source) {
changeText(props.value.slice(0, selected.start) + props.value.slice(selected.end));
props.onSelectionChange?.({ start: selected.start, end: selected.start });
}
setSelected(null);
};
const commentSelectedCitation =
props.readOnly || props.editable === false || !selected || !selectedCitation
? undefined
: (comment: string) => {
if (props.value.slice(selected.start, selected.end) !== selected.source) return;
const next = serializeAssistantCitation(
withAssistantCitationComment(selectedCitation, comment),
);
const text =
props.value.slice(0, selected.start) + next + props.value.slice(selected.end);
const cursor = selected.start + next.length;
if (draftKey)
rememberComposerDraftSelection(draftKey, text, { start: cursor, end: cursor });
changeText(text);
};
return (
<>
{/* Reset revision history with the recreated iOS view without aborting context imports. */}
Expand Down Expand Up @@ -214,6 +249,14 @@ export function ComposerEditor({
{importing ? (
<Text className="py-2 text-xs text-foreground-muted">Copying context…</Text>
) : null}
{selectedCitation ? (
<AssistantCitationSheet
citation={selectedCitation}
onClose={() => setSelected(null)}
onRemove={removeSelected}
onCommentChange={commentSelectedCitation}
/>
) : null}
{selected && (selectedReference || selectedSkill) ? (
<ComposerContextSheet
label={
Expand Down Expand Up @@ -252,19 +295,7 @@ export function ComposerEditor({
records={draft.context?.records}
attachments={draft.attachments}
onClose={() => setSelected(null)}
onRemove={
props.readOnly || props.editable === false
? undefined
: () => {
if (props.value.slice(selected.start, selected.end) === selected.source) {
changeText(
props.value.slice(0, selected.start) + props.value.slice(selected.end),
);
props.onSelectionChange?.({ start: selected.start, end: selected.start });
}
setSelected(null);
}
}
onRemove={removeSelected}
/>
) : null}
</>
Expand Down
27 changes: 26 additions & 1 deletion apps/mobile/src/features/threads/ThreadDetailScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,13 @@ import { useAppearancePreferences } from "../settings/appearance/AppearancePrefe
import { collectProviderUsageLimits } from "@t3tools/shared/usageLimits";
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
import type { StatusTone } from "../../components/StatusPill";
import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
import {
captureComposerDraftInsertion,
getComposerDraftSnapshot,
insertComposerDraftText,
} from "../../state/use-composer-drafts";
import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations";
import type { AssistantCitation } from "@t3tools/contracts";
import { RenderErrorBoundary, RenderFailureView } from "../../components/RenderErrorBoundary";
import {
ANDROID_READING_MAX_WIDTH,
Expand Down Expand Up @@ -1196,6 +1202,24 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {
composerEditorRef.current?.blur();
};

const canCiteAssistantText =
props.composerDraftKey !== null &&
!isProviderSubagent &&
!composerSlotHidden &&
!props.isSavingQueuedEdit &&
!props.draftMode?.interactionLocked;
const handleCiteAssistantText = (citation: AssistantCitation) => {
if (!canCiteAssistantText || props.composerDraftKey === null) return;
const target = captureComposerDraftInsertion(props.composerDraftKey);
const prefix = target.start > 0 && !/\s/.test(target.text[target.start - 1]!) ? " " : "";
insertComposerDraftText(
props.composerDraftKey,
`${prefix}${serializeAssistantCitation(citation)} `,
target,
);
composerEditorRef.current?.focus();
};

const handleUseArtifactTemplate = (template: CodexArtifactTemplate) => {
const draftMessage =
props.composerDraftKey === null ? "" : getComposerDraftSnapshot(props.composerDraftKey).text;
Expand Down Expand Up @@ -1332,6 +1356,7 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {
onEndFollowEnabledChange={handleEndFollowEnabledChange}
skills={selectedProviderSkills}
onUseArtifactTemplate={handleUseArtifactTemplate}
onCiteAssistantText={canCiteAssistantText ? handleCiteAssistantText : undefined}
/>
</RenderErrorBoundary>
</View>
Expand Down
40 changes: 37 additions & 3 deletions apps/mobile/src/features/threads/ThreadFeed.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Button } from "../../components/ui/Button";
import * as Dialog from "../../components/ui/Dialog";
import { ASSISTANT_CITATION_MAX_TEXT_LENGTH, type AssistantCitation } from "@t3tools/contracts";
import { useOpenPullRequest } from "../../native/useOpenPullRequest";
import { useWorkspaceSettledContentWidth } from "../layout/workspace-content-width";
import { ThreadMarkdownVideo, ThreadMediaVisibleContext } from "./ThreadMarkdownVideo";
Expand Down Expand Up @@ -54,7 +55,6 @@ import {
type ScheduledTaskId,
type ScopedThreadRef,
} from "@t3tools/contracts";
import { renderAssistantCitationsAsText } from "@t3tools/shared/assistantCitations";
import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
import { parseThreadLinkHref } from "@t3tools/shared/threadLinks";
import { PROMPT_LINK_MAX_PROMPT_LENGTH } from "@t3tools/shared/promptLinks";
Expand Down Expand Up @@ -365,6 +365,7 @@ export interface ThreadFeedProps {
readonly onEndFollowEnabledChange?: (enabled: boolean) => void;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
readonly onUseArtifactTemplate?: (template: CodexArtifactTemplate) => void;
readonly onCiteAssistantText?: (citation: AssistantCitation) => void;
}

async function waitForThreadShell(
Expand Down Expand Up @@ -900,6 +901,8 @@ function ArtifactTemplateCard(props: {
const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: {
readonly markdown: string;
readonly environmentId: EnvironmentId;
readonly citationSource?: Pick<AssistantCitation, "threadId" | "messageId">;
readonly onCiteAssistantText?: (citation: AssistantCitation) => void;
readonly markdownStyles: MarkdownStyleSet;
readonly linkHandlers: MarkdownLinkHandlers;
readonly onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined;
Expand Down Expand Up @@ -934,6 +937,32 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: {
markdown={markdown}
skills={props.skills}
textStyle={props.markdownStyles.nativeTextStyle}
onCiteText={
props.onCiteAssistantText && props.citationSource
? (text) => {
if (!text.trim()) return;
if (text.length > ASSISTANT_CITATION_MAX_TEXT_LENGTH) {
Dialog.alert(
"Quote is too long",
`Select up to ${ASSISTANT_CITATION_MAX_TEXT_LENGTH.toLocaleString()} characters to cite.`,
);
return;
}
// Native offsets are local to Markdown blocks; navigation resolves the quote in its message.
if (!props.citationSource) return;
props.onCiteAssistantText?.({
version: 1,
environmentId: props.environmentId,
...props.citationSource,
text,
start: 0,
end: text.replace(/\s+/g, " ").length,
prefix: "",
suffix: "",
});
}
: undefined
}
{...linkHandlers}
renderImage={props.renderImage}
/>
Expand Down Expand Up @@ -1161,7 +1190,7 @@ function ThreadAutomationMessageRow(props: {
<View className="px-3.5 pb-2.5">
<MarkdownImageAvailableWidthContext value={props.contentMaxWidth}>
<UserMessageContent
text={renderAssistantCitationsAsText(props.text)}
text={props.text}
environmentId={props.environmentId}
context={props.context}
markdownStyles={props.markdownStyles}
Expand Down Expand Up @@ -1300,6 +1329,7 @@ function renderFeedEntry(
ThreadFeedProps,
| "environmentId"
| "onUseArtifactTemplate"
| "onCiteAssistantText"
| "skills"
| "dispatchingMessageId"
| "onEditPendingMessage"
Expand Down Expand Up @@ -1509,7 +1539,7 @@ function renderFeedEntry(
const { message } = entry;
const isUser = message.role === "user";
const presentation = resolveUserMessagePresentation(message);
const renderedText = renderAssistantCitationsAsText(presentation.text);
const renderedText = presentation.text;
const styles = isUser ? markdownStyles.user : markdownStyles.assistant;
const timestampLabel = formatMessageTime(isUser ? message.createdAt : message.updatedAt);
const attachments = message.attachments ?? [];
Expand Down Expand Up @@ -1820,6 +1850,8 @@ function renderFeedEntry(
<AssistantMarkdownContent
markdown={renderedText}
environmentId={props.environmentId}
citationSource={{ threadId: props.threadId, messageId: message.id }}
onCiteAssistantText={props.onCiteAssistantText}
markdownStyles={styles}
linkHandlers={props.markdownLinkHandlers}
onUseArtifactTemplate={props.onUseArtifactTemplate}
Expand Down Expand Up @@ -2694,6 +2726,7 @@ export const ThreadFeed = memo(function ThreadFeed({
// Include turn completion so unchanged message rows reveal their footer and spacing
// even when the final message update arrives before the turn settles.
const listAppearanceData = {
onCiteAssistantText: props.onCiteAssistantText,
worktreeSetup: props.worktreeSetup,
setupWorkingStartedAt: props.setupWorkingStartedAt,
dispatchingMessageId: props.dispatchingMessageId,
Expand Down Expand Up @@ -3143,6 +3176,7 @@ export const ThreadFeed = memo(function ThreadFeed({
dispatchingMessageId: props.dispatchingMessageId,
onEditPendingMessage: props.onEditPendingMessage,
onUseArtifactTemplate: props.onUseArtifactTemplate,
onCiteAssistantText: props.onCiteAssistantText,
threadId: props.threadId,
copiedRowId,
expandedWorkRows,
Expand Down
1 change: 1 addition & 0 deletions apps/mobile/src/lib/composerChipPresentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ const CONTEXT_CHIP_PRESENTATIONS = {
icon: "mouse-pointer-click",
},
"review-comment": { accent: "#8a70dd", icon: "message-circle" },
citation: { accent: "#8a70dd", icon: "message-circle" },
"pull-request": {
accent: "#7079e4",
icon: "git-pull-request-arrow",
Expand Down
Loading
Loading