From dab5c0945dbdb3cbf27e924a27a5e246165ecd4c Mon Sep 17 00:00:00 2001 From: Jake Leventhal Date: Wed, 28 Oct 2026 15:26:31 -0400 Subject: [PATCH 01/16] feat(mobile): select, cite, and comment on assistant text Long-press an assistant response, adjust the selection, and choose Cite to insert a quote into the composer. Tap a draft quote to add or edit its comment, copy it, jump to the source message, or remove it. Sent quotes open the same sheet read-only. Co-Authored-By: Claude Opus 5.5 --- .../src/components/AssistantCitationSheet.tsx | 113 ++++++++++++++++++ apps/mobile/src/components/ComposerEditor.tsx | 57 +++++++-- .../features/threads/ThreadDetailScreen.tsx | 28 ++++- .../src/features/threads/ThreadFeed.tsx | 42 ++++++- .../src/lib/composerChipPresentation.ts | 1 + apps/mobile/src/lib/composerContext.test.ts | 21 +++- apps/mobile/src/lib/composerContext.ts | 15 ++- .../src/native/EnrichedMarkdownText.tsx | 11 ++ .../src/native/SelectableMarkdownText.tsx | 53 +++++++- .../native/SelectableMarkdownText.types.ts | 1 + .../src/native/T3ComposerEditor.ios.tsx | 4 +- .../src/native/T3ComposerEditor.native.tsx | 5 +- .../src/native/useEnrichedLinkVariants.ts | 11 ++ docs/user/composer.md | 6 +- 14 files changed, 341 insertions(+), 27 deletions(-) create mode 100644 apps/mobile/src/components/AssistantCitationSheet.tsx diff --git a/apps/mobile/src/components/AssistantCitationSheet.tsx b/apps/mobile/src/components/AssistantCitationSheet.tsx new file mode 100644 index 0000000000000..8aa8d00edf1ac --- /dev/null +++ b/apps/mobile/src/components/AssistantCitationSheet.tsx @@ -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 ( + + + + + + {contextBefore(citation.prefix)} + {citation.text} + {contextAfter(citation.suffix)} + + + {props.onCommentChange ? ( + + + + ) : citation.comment ? ( + + + {citation.comment} + + + ) : null} + + { + close(); + requestThreadMessageJump(scopedThreadKey(citation), citation.messageId); + openLinkedThread(citation); + }} + /> + copyTextWithHaptic(citation.text)} + /> + {props.onRemove ? ( + + ) : null} + + + + ); +} diff --git a/apps/mobile/src/components/ComposerEditor.tsx b/apps/mobile/src/components/ComposerEditor.tsx index f7118b95b425f..a8f31bf1f9316 100644 --- a/apps/mobile/src/components/ComposerEditor.tsx +++ b/apps/mobile/src/components/ComposerEditor.tsx @@ -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 { @@ -169,6 +175,9 @@ 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) @@ -176,6 +185,32 @@ export function ComposerEditor({ 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. */} @@ -226,6 +261,14 @@ export function ComposerEditor({ {importing ? ( Copying context… ) : null} + {selectedCitation ? ( + setSelected(null)} + onRemove={removeSelected} + onCommentChange={commentSelectedCitation} + /> + ) : null} {selected && (selectedReference || selectedSkill) ? ( 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} diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 3e7eec1449e26..61e7236e03e4f 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -130,7 +130,14 @@ 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, setFreshSessionPending } from "../../state/use-composer-drafts"; +import { + captureComposerDraftInsertion, + getComposerDraftSnapshot, + setFreshSessionPending, + 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, @@ -1381,6 +1388,24 @@ function ThreadDetailBody( 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; @@ -1518,6 +1543,7 @@ function ThreadDetailBody( onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange} onIsAtEndChange={setIsAtEnd} skills={selectedProviderSkills} + onCiteAssistantText={handleCiteAssistantText} onUseArtifactTemplate={handleUseArtifactTemplate} /> diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index dbbcaa1fd9cff..fe0e914718d8f 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -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"; @@ -60,7 +61,6 @@ import { type ScopedThreadRef, } from "@t3tools/contracts"; import type { ToolCallVisibility } from "@t3tools/contracts/settings"; -import { renderAssistantCitationsAsText } from "@t3tools/shared/assistantCitations"; import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard"; import { hostedThreadLink, parseThreadLinkHref } from "@t3tools/shared/threadLinks"; import { PROMPT_LINK_MAX_PROMPT_LENGTH } from "@t3tools/shared/promptLinks"; @@ -347,6 +347,7 @@ export interface ThreadFeedProps { readonly onIsAtEndChange?: (isAtEnd: boolean) => void; readonly skills?: ReadonlyArray; readonly onUseArtifactTemplate?: (template: CodexArtifactTemplate) => void; + readonly onCiteAssistantText?: (citation: AssistantCitation) => void; } const USER_MESSAGE_COPY_MENU_ACTIONS = [ @@ -1138,6 +1139,8 @@ function ArtifactTemplateCard(props: { const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { readonly markdown: string; readonly environmentId: EnvironmentId; + readonly citationSource?: Pick; + readonly onCiteAssistantText?: (citation: AssistantCitation) => void; readonly markdownStyles: MarkdownStyleSet; readonly linkHandlers: MarkdownLinkHandlers; readonly onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined; @@ -1156,6 +1159,32 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { return ( { + 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 + } markdownStyles={props.markdownStyles} linkHandlers={linkHandlers} onUseArtifactTemplate={props.onUseArtifactTemplate} @@ -1169,6 +1198,7 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { // Folds split first, so an artifact card inside a fold stays inside it. function AssistantMarkdownBlocks(props: { readonly markdown: string; + readonly onCiteText?: (text: string) => void; readonly markdownStyles: MarkdownStyleSet; readonly linkHandlers: MarkdownLinkHandlers; readonly onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined; @@ -1216,6 +1246,7 @@ function AssistantMarkdownBlocks(props: { skills={props.skills} models={props.models} textStyle={props.markdownStyles.nativeTextStyle} + onCiteText={props.onCiteText} {...props.linkHandlers} renderImage={props.renderImage} /> @@ -1485,7 +1516,7 @@ function ThreadAutomationMessageRow(props: { { it("keeps exact source positions and repeated references alongside existing native tokens", () => { const reference = formatComposerContextReference(terminal); - const text = `Use $babysit with $disabled $agentOnly $HOME $PATH $anything $notaskill $20 $20k and [app.ts](src/app.ts) with ${reference} then ${reference}`; + const citation = serializeAssistantCitation({ + version: 1, + environmentId: EnvironmentId.make("remote"), + threadId: ThreadId.make("thread"), + messageId: MessageId.make("message"), + text: "日本語 🚀 with @file.ts and $HOME", + start: 0, + end: 33, + prefix: "", + suffix: "", + }); + const text = `Use $babysit with $disabled $agentOnly $HOME $PATH $anything $notaskill $20 $20k and [app.ts](src/app.ts) with ${reference} then ${reference} (${citation}),${citation}!`; const babysit: ServerProviderSkill = { name: "babysit", path: "/skills/babysit", @@ -222,6 +237,8 @@ describe("mobile composer context", () => { "[app.ts](src/app.ts)", reference, reference, + citation, + citation, ]); for (const token of tokens) expect(text.slice(token.start, token.end)).toBe(token.source); expect( @@ -230,7 +247,7 @@ describe("mobile composer context", () => { collectComposerInlineTokens(text), composerSkillLabels([]), ).map((token) => token.type), - ).toEqual(["mention", "context", "context"]); + ).toEqual(["mention", "context", "context", "citation", "citation"]); expect( composerContextEditorTokens( text, diff --git a/apps/mobile/src/lib/composerContext.ts b/apps/mobile/src/lib/composerContext.ts index 53494209362af..644e8ddeb7a2f 100644 --- a/apps/mobile/src/lib/composerContext.ts +++ b/apps/mobile/src/lib/composerContext.ts @@ -6,6 +6,10 @@ import { isProviderSkillUserInvocable } from "@t3tools/client-runtime/providerSk import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { filePreviewKind } from "@t3tools/shared/filePreview"; import { videoMimeType } from "@t3tools/shared/video"; +import { + assistantCitationLabel, + collectAssistantCitations, +} from "@t3tools/shared/assistantCitations"; import { COMPOSER_CONTEXT_MAX_RECORDS, COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS, @@ -194,13 +198,15 @@ export function composerContextEditorTokens( modelTokens: ReadonlyArray = [], ) { const references = collectComposerContextReferences(text); + const citations = collectAssistantCitations(text); const inlineTokens = tokens.filter( (token) => // `$HOME` and other `$name` text that is not one of the provider's skills stays prose. (token.type !== "skill" || knownSkills.has(token.value)) && - !references.some((ref) => token.start < ref.end && token.end > ref.start), + !references.some((ref) => token.start < ref.end && token.end > ref.start) && + !citations.some((ref) => token.start < ref.end && token.end > ref.start), ); - const taken = [...inlineTokens, ...references, ...composerMathRanges(text)]; + const taken = [...inlineTokens, ...references, ...citations, ...composerMathRanges(text)]; const models = modelTokens.filter( (mention) => !taken.some((range) => mention.start < range.end && mention.end > range.start), ); @@ -216,6 +222,11 @@ export function composerContextEditorTokens( value: mention.model, ...mention, })), + ...citations.map((ref) => ({ + type: "citation" as const, + value: assistantCitationLabel(ref.citation), + ...ref, + })), ].sort((a, b) => a.start - b.start); } diff --git a/apps/mobile/src/native/EnrichedMarkdownText.tsx b/apps/mobile/src/native/EnrichedMarkdownText.tsx index 86bf8021bdd0f..a9a4570c22b6d 100644 --- a/apps/mobile/src/native/EnrichedMarkdownText.tsx +++ b/apps/mobile/src/native/EnrichedMarkdownText.tsx @@ -420,6 +420,17 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) { containerStyle={{ flexShrink: 1, minWidth: 0 }} flavor="github" selectable + contextMenuItems={ + props.onCiteText + ? [ + { + text: "Cite", + icon: "quote.bubble", + onPress: ({ text }) => props.onCiteText?.(text), + }, + ] + : undefined + } selectionClipboard={selectionClipboard} selectionColor={props.textStyle.selectionColor} selectionHandleColor={props.textStyle.selectionHandleColor} diff --git a/apps/mobile/src/native/SelectableMarkdownText.tsx b/apps/mobile/src/native/SelectableMarkdownText.tsx index e49405af4dd4f..d05e91304bf94 100644 --- a/apps/mobile/src/native/SelectableMarkdownText.tsx +++ b/apps/mobile/src/native/SelectableMarkdownText.tsx @@ -1,4 +1,9 @@ import { Platform } from "react-native"; +import { useState } from "react"; +import type { AssistantCitation } from "@t3tools/contracts"; +import { parseAssistantCitationHref } from "@t3tools/shared/assistantCitations"; +import { AssistantCitationSheet } from "../components/AssistantCitationSheet"; +import { copyTextWithHaptic } from "../lib/copyTextWithHaptic"; import type { SelectableMarkdownTextProps } from "./SelectableMarkdownText.types"; import { MobileEnrichedMarkdownText } from "./EnrichedMarkdownText"; @@ -17,6 +22,8 @@ export type { } from "./SelectableMarkdownText.types"; export function SelectableMarkdownText(props: SelectableMarkdownTextProps) { + const [citation, setCitation] = useState(null); + const hasCitations = props.markdown.includes("t3-citation:"); const theme = useUniwindTheme(); const selectionColor = themeColorWithAlpha(theme["--color-focus"], 0.32); const selectionHandleColor = theme["--color-focus"]; @@ -24,5 +31,49 @@ export function SelectableMarkdownText(props: SelectableMarkdownTextProps) { Platform.OS === "android" ? { selectionColor, selectionHandleColor, ...props.textStyle } : props.textStyle; - return ; + return ( + <> + { + const quote = parseAssistantCitationHref(href); + if (quote) setCitation(quote); + else props.onLinkPress?.(href); + } + : props.onLinkPress + } + fileContextMenu={ + hasCitations + ? (href) => + parseAssistantCitationHref(href) + ? { + title: "Assistant quote", + actions: [ + { id: "open-quote", title: "Open quote" }, + { id: "copy-quote", title: "Copy quote" }, + ], + } + : props.fileContextMenu?.(href) + : props.fileContextMenu + } + onFileContextMenuAction={ + hasCitations + ? (href, actionId) => { + const quote = parseAssistantCitationHref(href); + if (quote) { + if (actionId === "open-quote") setCitation(quote); + else if (actionId === "copy-quote") copyTextWithHaptic(quote.text); + } else props.onFileContextMenuAction?.(href, actionId); + } + : props.onFileContextMenuAction + } + /> + {citation ? ( + setCitation(null)} /> + ) : null} + + ); } diff --git a/apps/mobile/src/native/SelectableMarkdownText.types.ts b/apps/mobile/src/native/SelectableMarkdownText.types.ts index 63f8429c386fd..95b9545122b97 100644 --- a/apps/mobile/src/native/SelectableMarkdownText.types.ts +++ b/apps/mobile/src/native/SelectableMarkdownText.types.ts @@ -77,6 +77,7 @@ export interface SelectableMarkdownTextProps { readonly models?: ReadonlyArray; readonly preserveSoftBreaks?: boolean; readonly onLinkPress?: (href: string) => void; + readonly onCiteText?: (text: string) => void; readonly fileContextMenu?: (href: string) => MarkdownFileContextMenu | undefined; readonly onFileContextMenuAction?: (href: string, actionId: string) => void; readonly linkCustomization?: (href: string) => MarkdownLinkCustomization | undefined; diff --git a/apps/mobile/src/native/T3ComposerEditor.ios.tsx b/apps/mobile/src/native/T3ComposerEditor.ios.tsx index 437bcda4d012d..26cc26fd6b3c4 100644 --- a/apps/mobile/src/native/T3ComposerEditor.ios.tsx +++ b/apps/mobile/src/native/T3ComposerEditor.ios.tsx @@ -200,7 +200,7 @@ export function ComposerEditor({ token.type === "mention" ? token.value : contextRecordFileName(record), ); return { - type: token.type, + type: token.type === "citation" ? "context" : token.type, source: token.source, start: token.start, end: token.end, @@ -216,6 +216,8 @@ export function ComposerEditor({ ? model.label : token.type === "context" ? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}` + : token.type === "citation" + ? token.value : basename(token.value), detail: token.type === "context" ? composerChipSizeSuffix(record) : "", iconUri: model ? modelChipIconUri(model) : contextChipIconUri(icon), diff --git a/apps/mobile/src/native/T3ComposerEditor.native.tsx b/apps/mobile/src/native/T3ComposerEditor.native.tsx index 5aabd8e0d6071..15ab04f93a2b2 100644 --- a/apps/mobile/src/native/T3ComposerEditor.native.tsx +++ b/apps/mobile/src/native/T3ComposerEditor.native.tsx @@ -200,8 +200,7 @@ export function ComposerEditor({ token.type === "mention" ? token.value : contextRecordFileName(record), ); return { - // Android taps only known token types; a model chip opens like a skill chip. - type: token.type === "model" ? "skill" : token.type, + type: token.type === "model" ? "skill" : token.type === "citation" ? "context" : token.type, source: token.source, start: token.start, end: token.end, @@ -217,6 +216,8 @@ export function ComposerEditor({ ? model.label : token.type === "context" ? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}` + : token.type === "citation" + ? token.value : basename(token.value), detail: token.type === "context" ? composerChipSizeSuffix(record) : "", iconUri: model ? modelChipIconUri(model) : contextChipIconUri(icon), diff --git a/apps/mobile/src/native/useEnrichedLinkVariants.ts b/apps/mobile/src/native/useEnrichedLinkVariants.ts index 2d4cf85cb7db1..f05f66aec6f28 100644 --- a/apps/mobile/src/native/useEnrichedLinkVariants.ts +++ b/apps/mobile/src/native/useEnrichedLinkVariants.ts @@ -1,5 +1,9 @@ import { modelChipIcon } from "../lib/contextChipIconSource"; import { useMemo } from "react"; +import { + assistantCitationLabel, + parseAssistantCitationHref, +} from "@t3tools/shared/assistantCitations"; import { Image } from "react-native"; import type { LinkPillContent, MarkdownStyle } from "react-native-enriched-markdown"; import type { ComposerContextRecord } from "@t3tools/contracts"; @@ -65,6 +69,13 @@ function presentation( ): MarkdownLinkCustomization | undefined { const custom = props.linkCustomization?.(url); if (custom) return custom; + const citation = parseAssistantCitationHref(url); + if (citation) + return { + label: assistantCitationLabel(citation), + icon: CONTEXT_CHIP_ICON_SOURCES["message-circle"], + chip: { accent: contextChipPresentation("citation").accent, tintsIcon: true }, + }; const context = enrichedContextLinkCustomization(url); if (context) return context; const skill = enrichedSkillReference(url, props.skills); diff --git a/docs/user/composer.md b/docs/user/composer.md index df880e49c6ca5..862d48792eba1 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -142,8 +142,10 @@ delete it like other inline context. Copying, reloading, and restoring a with its quote, and sending tells the agent which words were quoted and which comment you wrote. The quoted text and comment count toward the message limit. -Mobile displays saved quotes and comments, but does not create citations or -navigate to their sources. +On mobile, long-press an assistant response, adjust the text selection, and choose +**Cite** to insert a quote at the composer cursor. Tap a quote in a draft to add +or edit its comment, or to remove it. Tap a quote in a draft or sent message to +open its source message. ## Recall a sent prompt From 8cb16439f38428105eee32694323f936e4ccf059 Mon Sep 17 00:00:00 2001 From: Jake Leventhal Date: Wed, 28 Oct 2026 15:44:06 -0400 Subject: [PATCH 02/16] docs(mobile): name Go to message for opening a quote's source Co-Authored-By: Claude Opus 5.5 --- docs/user/composer.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/user/composer.md b/docs/user/composer.md index 862d48792eba1..7bff24f0dab48 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -144,8 +144,8 @@ The quoted text and comment count toward the message limit. On mobile, long-press an assistant response, adjust the text selection, and choose **Cite** to insert a quote at the composer cursor. Tap a quote in a draft to add -or edit its comment, or to remove it. Tap a quote in a draft or sent message to -open its source message. +or edit its comment, or to remove it. To open the source message, tap a quote in +a draft or sent message, then choose **Go to message**. ## Recall a sent prompt From ab7ac87f5e56a451bb268b2535444019fff9348c Mon Sep 17 00:00:00 2001 From: Jake Leventhal Date: Mon, 2 Nov 2026 10:10:55 -0500 Subject: [PATCH 03/16] fix(mobile): keep voice drafts locked when citing text --- .../features/threads/ThreadDetailScreen.tsx | 9 +++- .../src/features/threads/ThreadFeed.tsx | 50 +++++++++---------- 2 files changed, 33 insertions(+), 26 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 61e7236e03e4f..8f4ffab6f7879 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -218,6 +218,7 @@ import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-scroll-position import { useOpenLinkedThread } from "./useOpenLinkedThread"; import { useGlobalVoiceInput } from "../voice-input/VoiceInputProvider"; import type { OrchestrationV2ProviderSession } from "@t3tools/contracts"; +import { voiceInputBlocksSubmission } from "@t3tools/client-runtime/voice-input"; export interface ThreadDetailScreenProps { readonly header?: React.ReactNode; @@ -1395,7 +1396,13 @@ function ThreadDetailBody( !props.isSavingQueuedEdit && !props.draftMode?.interactionLocked; const handleCiteAssistantText = (citation: AssistantCitation) => { - if (!canCiteAssistantText || props.composerDraftKey === null) return; + if ( + !canCiteAssistantText || + props.composerDraftKey === null || + (voiceInputSession.ownerKey === props.composerDraftKey && + voiceInputBlocksSubmission(voiceInputSession.controller.currentState)) + ) + return; const target = captureComposerDraftInsertion(props.composerDraftKey); const prefix = target.start > 0 && !/\s/.test(target.text[target.start - 1]!) ? " " : ""; insertComposerDraftText( diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index fe0e914718d8f..ad8f9cd3281a3 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -1159,32 +1159,32 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { return ( { - 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: "", - }); + 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; } - : undefined - } + // 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 + } markdownStyles={props.markdownStyles} linkHandlers={linkHandlers} onUseArtifactTemplate={props.onUseArtifactTemplate} From 45896dc572598d0bb49e2a5f024fe68f48f072ed Mon Sep 17 00:00:00 2001 From: maria-rcks Date: Mon, 2 Nov 2026 21:49:00 +0000 Subject: [PATCH 04/16] fix(mobile): hide cite while voice input blocks drafts --- apps/mobile/src/features/threads/ThreadDetailScreen.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 8f4ffab6f7879..6cc78df8dec21 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -1394,7 +1394,11 @@ function ThreadDetailBody( !isProviderSubagent && !composerSlotHidden && !props.isSavingQueuedEdit && - !props.draftMode?.interactionLocked; + !props.draftMode?.interactionLocked && + !( + voiceInputSession.ownerKey === props.composerDraftKey && + voiceInputBlocksSubmission(voiceInputSession.controller.currentState) + ); const handleCiteAssistantText = (citation: AssistantCitation) => { if ( !canCiteAssistantText || From be3d5f31a11fcf43cc13a6760df7d9495a008d7b Mon Sep 17 00:00:00 2001 From: Jake Leventhal Date: Thu, 12 Nov 2026 09:29:31 -0500 Subject: [PATCH 05/16] fix(mobile): keep citation drafts within input limits --- .../src/components/AssistantCitationSheet.tsx | 14 ++++++++-- .../components/ComposerEditor.ios.test.tsx | 1 + apps/mobile/src/components/ComposerEditor.tsx | 20 ++++++++++++++ .../features/threads/ThreadDetailScreen.tsx | 18 ++++++++----- apps/mobile/src/lib/composerContext.test.ts | 27 +++++++++++++++++++ apps/mobile/src/lib/composerContext.ts | 9 +++++++ .../src/native/T3ComposerEditor.ios.tsx | 2 +- .../src/native/T3ComposerEditor.native.tsx | 5 ++-- 8 files changed, 85 insertions(+), 11 deletions(-) diff --git a/apps/mobile/src/components/AssistantCitationSheet.tsx b/apps/mobile/src/components/AssistantCitationSheet.tsx index 8aa8d00edf1ac..62185cc3b9f89 100644 --- a/apps/mobile/src/components/AssistantCitationSheet.tsx +++ b/apps/mobile/src/components/AssistantCitationSheet.tsx @@ -32,19 +32,23 @@ export function AssistantCitationSheet(props: { readonly onClose: () => void; readonly onRemove?: () => void; readonly onCommentChange?: (comment: string) => void; + readonly canChangeComment?: (comment: string) => boolean; }) { const openLinkedThread = useOpenLinkedThread(); const insets = useSafeAreaInsets(); const citation = props.citation; const [comment, setComment] = useState(citation.comment ?? ""); + const commentChanged = comment.trim() !== (citation.comment ?? ""); + const commentTooLong = commentChanged && props.canChangeComment?.(comment) === false; const close = () => { - if (props.onCommentChange && comment.trim() !== (citation.comment ?? "")) { + if (commentTooLong) return; + if (props.onCommentChange && commentChanged) { props.onCommentChange(comment); } props.onClose(); }; return ( - + + {commentTooLong ? ( + + This comment makes the message too long to send. Shorten it to save and close. + + ) : null} ) : citation.comment ? ( @@ -88,6 +97,7 @@ export function AssistantCitationSheet(props: { icon="arrow.up.right" label="Go to message" onPress={() => { + if (commentTooLong) return; close(); requestThreadMessageJump(scopedThreadKey(citation), citation.messageId); openLinkedThread(citation); diff --git a/apps/mobile/src/components/ComposerEditor.ios.test.tsx b/apps/mobile/src/components/ComposerEditor.ios.test.tsx index f7ce1f9918d85..60f37716b84bb 100644 --- a/apps/mobile/src/components/ComposerEditor.ios.test.tsx +++ b/apps/mobile/src/components/ComposerEditor.ios.test.tsx @@ -116,6 +116,7 @@ vi.mock("expo-file-system", () => ({ vi.mock("./ui/Dialog", () => ({ alert: vi.fn() })); vi.mock("./ui/AppText", () => ({ AppText: ({ children }: { children?: ReactNode }) => children })); vi.mock("./ComposerContextSheet", () => ({ ComposerContextSheet: () => null })); +vi.mock("./AssistantCitationSheet", () => ({ AssistantCitationSheet: () => null })); vi.mock("../features/threads/useOpenLinkedThread", () => ({ useOpenLinkedThread: () => vi.fn() })); vi.mock("../state/peerLinks", () => ({ useLinkedEnvironments: () => [] })); vi.mock("../state/model-mentions", () => ({ useModelMentions: () => [] })); diff --git a/apps/mobile/src/components/ComposerEditor.tsx b/apps/mobile/src/components/ComposerEditor.tsx index a8f31bf1f9316..ea527efdb8e94 100644 --- a/apps/mobile/src/components/ComposerEditor.tsx +++ b/apps/mobile/src/components/ComposerEditor.tsx @@ -40,6 +40,7 @@ import { useLinkedEnvironments } from "../state/peerLinks"; import { ComposerContextSheet } from "./ComposerContextSheet"; import { AppText as Text } from "./ui/AppText"; import { + assistantCitationDraftWithinLimit, composerDocumentAttachment, composerMentionPath, type ComposerDocumentAttachment, @@ -206,6 +207,13 @@ export function ComposerEditor({ ); const text = props.value.slice(0, selected.start) + next + props.value.slice(selected.end); + if (!assistantCitationDraftWithinLimit(text)) { + Dialog.alert( + "Could not update quote", + "This comment would make the message too long to send. Shorten the comment or draft.", + ); + return; + } const cursor = selected.start + next.length; if (draftKey) rememberComposerDraftSelection(draftKey, text, { start: cursor, end: cursor }); @@ -267,6 +275,18 @@ export function ComposerEditor({ onClose={() => setSelected(null)} onRemove={removeSelected} onCommentChange={commentSelectedCitation} + canChangeComment={ + selected && commentSelectedCitation + ? (comment) => + assistantCitationDraftWithinLimit( + props.value.slice(0, selected.start) + + serializeAssistantCitation( + withAssistantCitationComment(selectedCitation, comment), + ) + + props.value.slice(selected.end), + ) + : undefined + } /> ) : null} {selected && (selectedReference || selectedSkill) ? ( diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 6cc78df8dec21..c6c987f8838da 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -136,6 +136,7 @@ import { setFreshSessionPending, insertComposerDraftText, } from "../../state/use-composer-drafts"; +import { assistantCitationDraftWithinLimit } from "../../lib/composerContext"; import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations"; import type { AssistantCitation } from "@t3tools/contracts"; import { RenderErrorBoundary, RenderFailureView } from "../../components/RenderErrorBoundary"; @@ -1409,11 +1410,16 @@ function ThreadDetailBody( 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, - ); + const value = `${prefix}${serializeAssistantCitation(citation)} `; + const text = target.text.slice(0, target.start) + value + target.text.slice(target.end); + if (!assistantCitationDraftWithinLimit(text)) { + Dialog.alert( + "Could not add quote", + "This quote would make the message too long to send. Shorten the draft or select less text.", + ); + return; + } + insertComposerDraftText(props.composerDraftKey, value, target); composerEditorRef.current?.focus(); }; @@ -1554,7 +1560,7 @@ function ThreadDetailBody( onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange} onIsAtEndChange={setIsAtEnd} skills={selectedProviderSkills} - onCiteAssistantText={handleCiteAssistantText} + onCiteAssistantText={canCiteAssistantText ? handleCiteAssistantText : undefined} onUseArtifactTemplate={handleUseArtifactTemplate} /> diff --git a/apps/mobile/src/lib/composerContext.test.ts b/apps/mobile/src/lib/composerContext.test.ts index 3366846439c6d..657970c28a999 100644 --- a/apps/mobile/src/lib/composerContext.test.ts +++ b/apps/mobile/src/lib/composerContext.test.ts @@ -1,4 +1,5 @@ import { + PROVIDER_SEND_TURN_MAX_INPUT_CHARS, ComposerContextId, EnvironmentId, MessageId, @@ -16,6 +17,7 @@ import { } from "@t3tools/shared/composerContextReferences"; import { describe, expect, it } from "vite-plus/test"; import { + assistantCitationDraftWithinLimit, collectComposerModelTokens, composerContextEditorTokens, composerSkillLabels, @@ -205,6 +207,31 @@ describe("mobile composer context", () => { expect(collectComposerModelTokens("model:codex/gpt-6.1", known, kept)).toEqual([]); }); + it("rejects citation drafts exceeding either encoded or expanded input limits", () => { + const quote = (text: string) => + serializeAssistantCitation({ + version: 1, + environmentId: EnvironmentId.make("remote"), + threadId: ThreadId.make("thread"), + messageId: MessageId.make("message"), + text, + start: 0, + end: text.length, + prefix: "", + suffix: "", + }); + expect(assistantCitationDraftWithinLimit(`Explain ${quote("short quote")}`)).toBe(true); + expect( + assistantCitationDraftWithinLimit( + `${quote("日".repeat(8_000))} ${quote("語".repeat(8_000))}`, + ), + ).toBe(false); + const short = quote("x"); + const expandedOverflow = "a".repeat(PROVIDER_SEND_TURN_MAX_INPUT_CHARS - short.length) + short; + expect(expandedOverflow.length).toBe(PROVIDER_SEND_TURN_MAX_INPUT_CHARS); + expect(assistantCitationDraftWithinLimit(expandedOverflow)).toBe(false); + }); + it("keeps exact source positions and repeated references alongside existing native tokens", () => { const reference = formatComposerContextReference(terminal); const citation = serializeAssistantCitation({ diff --git a/apps/mobile/src/lib/composerContext.ts b/apps/mobile/src/lib/composerContext.ts index 644e8ddeb7a2f..403e01da6efd2 100644 --- a/apps/mobile/src/lib/composerContext.ts +++ b/apps/mobile/src/lib/composerContext.ts @@ -9,8 +9,10 @@ import { videoMimeType } from "@t3tools/shared/video"; import { assistantCitationLabel, collectAssistantCitations, + expandAssistantCitationsForProvider, } from "@t3tools/shared/assistantCitations"; import { + PROVIDER_SEND_TURN_MAX_INPUT_CHARS, COMPOSER_CONTEXT_MAX_RECORDS, COMPOSER_CONTEXT_REVIEW_TEXT_MAX_CHARS, ComposerContextId, @@ -40,6 +42,13 @@ import { const isMessageContext = Schema.is(OrchestrationMessageContext); const decodeMessageContext = Schema.decodeUnknownOption(OrchestrationMessageContext); +export function assistantCitationDraftWithinLimit(text: string): boolean { + return ( + text.length <= PROVIDER_SEND_TURN_MAX_INPUT_CHARS && + expandAssistantCitationsForProvider(text).length <= PROVIDER_SEND_TURN_MAX_INPUT_CHARS + ); +} + export function composerContextSendBlockReason( context?: OrchestrationMessageContext, ): string | null { diff --git a/apps/mobile/src/native/T3ComposerEditor.ios.tsx b/apps/mobile/src/native/T3ComposerEditor.ios.tsx index 26cc26fd6b3c4..efd7ba0e9a94f 100644 --- a/apps/mobile/src/native/T3ComposerEditor.ios.tsx +++ b/apps/mobile/src/native/T3ComposerEditor.ios.tsx @@ -218,7 +218,7 @@ export function ComposerEditor({ ? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}` : token.type === "citation" ? token.value - : basename(token.value), + : basename(token.value), detail: token.type === "context" ? composerChipSizeSuffix(record) : "", iconUri: model ? modelChipIconUri(model) : contextChipIconUri(icon), tintsIcon: model ? modelChipIcon(model).tintsIcon : icon.kind === "chip", diff --git a/apps/mobile/src/native/T3ComposerEditor.native.tsx b/apps/mobile/src/native/T3ComposerEditor.native.tsx index 15ab04f93a2b2..e369e5257d8fc 100644 --- a/apps/mobile/src/native/T3ComposerEditor.native.tsx +++ b/apps/mobile/src/native/T3ComposerEditor.native.tsx @@ -200,7 +200,8 @@ export function ComposerEditor({ token.type === "mention" ? token.value : contextRecordFileName(record), ); return { - type: token.type === "model" ? "skill" : token.type === "citation" ? "context" : token.type, + type: + token.type === "model" ? "skill" : token.type === "citation" ? "context" : token.type, source: token.source, start: token.start, end: token.end, @@ -218,7 +219,7 @@ export function ComposerEditor({ ? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}` : token.type === "citation" ? token.value - : basename(token.value), + : basename(token.value), detail: token.type === "context" ? composerChipSizeSuffix(record) : "", iconUri: model ? modelChipIconUri(model) : contextChipIconUri(icon), tintsIcon: model ? modelChipIcon(model).tintsIcon : icon.kind === "chip", From e34f76a628478a7c46c80fa105cc406d33152dcc Mon Sep 17 00:00:00 2001 From: Jake Leventhal Date: Thu, 12 Nov 2026 10:42:41 -0500 Subject: [PATCH 06/16] fix(citations): preserve mobile quote sources and bound expansion --- .../src/features/threads/ThreadFeed.tsx | 128 ++++++++++++------ .../lib/assistantCitationSelection.test.ts | 70 ++++++++++ .../src/lib/assistantCitationSelection.ts | 102 ++++++++++++++ .../ProviderTurnControlService.ts | 18 ++- .../ProviderTurnStartService.test.ts | 39 ++++++ .../ProviderTurnStartService.ts | 32 +++-- .../src/lib/assistantTextSelection.test.ts | 17 +++ apps/web/src/lib/assistantTextSelection.ts | 101 ++------------ docs/internals/assistant-citations.md | 6 +- docs/user/composer.md | 4 +- packages/contracts/src/assistantCitations.ts | 9 ++ .../shared/src/assistantCitations.test.ts | 16 +++ packages/shared/src/assistantCitations.ts | 112 ++++++++++++++- 13 files changed, 510 insertions(+), 144 deletions(-) create mode 100644 apps/mobile/src/lib/assistantCitationSelection.test.ts create mode 100644 apps/mobile/src/lib/assistantCitationSelection.ts diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index ad8f9cd3281a3..3e4748f723af0 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -1,3 +1,7 @@ +import { Sheet } from "../../components/ui/Sheet"; +import { ListActionRow } from "../../components/ui/ListActionRow"; +import { ListSection } from "../../components/ui/ListSection"; +import { collectMobileAssistantTextSelectors } from "../../lib/assistantCitationSelection"; import { Button } from "../../components/ui/Button"; import * as Dialog from "../../components/ui/Dialog"; import { ASSISTANT_CITATION_MAX_TEXT_LENGTH, type AssistantCitation } from "@t3tools/contracts"; @@ -117,6 +121,7 @@ import { } from "react"; import { Image, + ScrollView, Platform, type LayoutChangeEvent, type NativeScrollEvent, @@ -1147,6 +1152,19 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { readonly renderImage: MarkdownImageRenderer; readonly skills?: ReadonlyArray | undefined; }) { + const [quoteChoices, setQuoteChoices] = useState< + ReturnType + >([]); + const cite = (selector: (typeof quoteChoices)[number]) => { + if (!props.citationSource || !props.onCiteAssistantText) return; + setQuoteChoices([]); + props.onCiteAssistantText({ + version: 1, + environmentId: props.environmentId, + ...props.citationSource, + ...selector, + }); + }; const models = useModelMentions(props.environmentId, props.markdown); const liveMarkdown = useLiveThreadLinkLabels(props.markdown, props.environmentId); const threadIcons = useThreadChipIcons(props.environmentId, liveMarkdown); @@ -1157,48 +1175,68 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { }; return ( - { - 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; + <> + { + 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; + } + const selectors = collectMobileAssistantTextSelectors(liveMarkdown, path, text); + if (selectors.length === 0) { + Dialog.alert( + "Unable to locate quote", + "Select more surrounding text to cite its source accurately.", + ); + return; + } + if (selectors.length === 1) cite(selectors[0]!); + else setQuoteChoices(selectors); } - // 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 - } - markdownStyles={props.markdownStyles} - linkHandlers={linkHandlers} - onUseArtifactTemplate={props.onUseArtifactTemplate} - renderImage={props.renderImage} - skills={props.skills} - models={models} - /> + : undefined + } + markdownStyles={props.markdownStyles} + linkHandlers={linkHandlers} + onUseArtifactTemplate={props.onUseArtifactTemplate} + renderImage={props.renderImage} + skills={props.skills} + models={models} + /> + {quoteChoices.length > 0 && props.onCiteAssistantText ? ( + setQuoteChoices([])}> + + + {quoteChoices.map((selector) => ( + cite(selector)} + /> + ))} + + + + ) : null} + ); }); // Folds split first, so an artifact card inside a fold stays inside it. function AssistantMarkdownBlocks(props: { readonly markdown: string; - readonly onCiteText?: (text: string) => void; + readonly citationPath?: string; + readonly onCiteText?: (text: string, path: string) => void; readonly markdownStyles: MarkdownStyleSet; readonly linkHandlers: MarkdownLinkHandlers; readonly onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined; @@ -1215,7 +1253,7 @@ function AssistantMarkdownBlocks(props: { ), [props.markdown], ); - return blocks.map((block) => { + return blocks.map((block, blockIndex) => { if (block.kind === "details") { return ( - + ); } - return block.segments.map((segment) => { + return block.segments.map((segment, segmentIndex) => { const offset = block.sourceOffset + segment.sourceOffset; if (segment.kind === "artifact-template") { return ( @@ -1246,7 +1288,15 @@ function AssistantMarkdownBlocks(props: { skills={props.skills} models={props.models} textStyle={props.markdownStyles.nativeTextStyle} - onCiteText={props.onCiteText} + onCiteText={ + props.onCiteText + ? (text) => + props.onCiteText?.( + text, + `${props.citationPath ?? ""}${blockIndex}:${segmentIndex}`, + ) + : undefined + } {...props.linkHandlers} renderImage={props.renderImage} /> diff --git a/apps/mobile/src/lib/assistantCitationSelection.test.ts b/apps/mobile/src/lib/assistantCitationSelection.test.ts new file mode 100644 index 0000000000000..6b2739394040f --- /dev/null +++ b/apps/mobile/src/lib/assistantCitationSelection.test.ts @@ -0,0 +1,70 @@ +import { expect, it } from "vite-plus/test"; +import { collectMobileAssistantTextSelectors } from "./assistantCitationSelection"; +import { + findAssistantCitationText, + serializeAssistantCitation, + expandAssistantCitationsForProvider, +} from "@t3tools/shared/assistantCitations"; +import { EnvironmentId, ThreadId, MessageId } from "@t3tools/contracts"; + +it("offers distinct source choices within a block and maps recursive folds without merging occurrences", () => { + const paragraph = `${"x".repeat(40)}**quote**${"x".repeat(40)}`; + const markdown = `${paragraph}\n\n
Outer\n\n
Inner\n\n${paragraph}\n\n
\n\n
`; + const first = collectMobileAssistantTextSelectors(markdown, "0:0", "quote")[0]; + const second = collectMobileAssistantTextSelectors(markdown, "1/1/0:0", "quote")[0]; + expect(first?.occurrence).toEqual({ index: 0, count: 2 }); + expect(second?.occurrence).toEqual({ index: 1, count: 2 }); + const rendered = `${"x".repeat(40)}quote${"x".repeat(40)} ${"x".repeat(40)}quote${"x".repeat(40)}`; + expect(findAssistantCitationText(rendered, second!)).toEqual({ + start: rendered.lastIndexOf("quote"), + end: rendered.lastIndexOf("quote") + 5, + }); + const markers = [first!, second!].map((selector) => + serializeAssistantCitation({ + version: 1, + environmentId: EnvironmentId.make("env"), + threadId: ThreadId.make("thread"), + messageId: MessageId.make("assistant"), + ...selector, + }), + ); + expect(markers[0]).not.toBe(markers[1]); + expect(expandAssistantCitationsForProvider(markers.join(" "))).toContain( + '"id": "assistant-quote-2"', + ); + const sameBlock = collectMobileAssistantTextSelectors( + "first **quote** then **quote** last", + "0:0", + "quote", + ); + expect(sameBlock[1]?.start).toBe(17); + expect(sameBlock[1]?.prefix).toBe("first quote then "); +}); + +it("rejects unmappable or blank selections instead of inventing a source", () => { + expect(collectMobileAssistantTextSelectors("quote quote", "0:0", " ")).toEqual([]); + expect(collectMobileAssistantTextSelectors("quote ".repeat(21), "0:0", "quote")).toEqual([]); + expect(collectMobileAssistantTextSelectors("quote quote", "0:0", "other")).toEqual([]); + expect(collectMobileAssistantTextSelectors("quote quote", "missing", "quote")).toEqual([]); +}); + +it("uses the web math representation around a selected passage", () => { + for (const formula of ["$x$", "\\(x\\)"]) { + const [selector] = collectMobileAssistantTextSelectors( + `Before ${formula} after`, + "0:0", + "after", + ); + expect(selector?.prefix).toBe("Before \\(x\\) "); + expect(findAssistantCitationText("Before \\(x\\) after", selector!)).toEqual({ + start: 13, + end: 18, + }); + } + const [display] = collectMobileAssistantTextSelectors( + "Before\n\n$$\nx\n$$\n\nafter", + "0:0", + "after", + ); + expect(display?.prefix).toBe("Before \\[ x \\] "); +}); diff --git a/apps/mobile/src/lib/assistantCitationSelection.ts b/apps/mobile/src/lib/assistantCitationSelection.ts new file mode 100644 index 0000000000000..350b5e4d8fc44 --- /dev/null +++ b/apps/mobile/src/lib/assistantCitationSelection.ts @@ -0,0 +1,102 @@ +import { markdownMathRanges } from "@t3tools/shared/markdownMath"; +import { createAssistantTextSelector } from "@t3tools/shared/assistantCitations"; +import { + splitCodexArtifactTemplateMarkdown, + renderCodexInlineDirectivesAsMarkdown, +} from "@t3tools/shared/codexMarkdownDirectives"; +import { splitMarkdownDetails } from "./markdownDetails"; +import { parseMarkdownDocument, type MarkdownNode } from "./markdownDocument"; + +function renderedText(node: MarkdownNode, restoreMath: (value: string) => string): string { + if ( + node.type === "definition" || + node.type === "image" || + node.type === "imageReference" || + node.type === "html" + ) + return ""; + if ("value" in node) return restoreMath(node.value); + if ("children" in node) { + const inline = + node.type === "paragraph" || + node.type === "heading" || + node.type === "link" || + node.type === "linkReference" || + node.type === "emphasis" || + node.type === "strong" || + node.type === "delete" || + node.type === "tableCell"; + return node.children.map((child) => renderedText(child, restoreMath)).join(inline ? "" : "\n"); + } + return node.type === "break" ? "\n" : ""; +} + +function citationText(markdown: string): string { + const formulas = markdownMathRanges(markdown); + let marker = "\ue000t3math"; + while (markdown.includes(marker)) marker += "_"; + const tokens = formulas.map((_, index) => `${marker}${index}\ue001`); + let cursor = 0; + let prose = ""; + for (const [index, formula] of formulas.entries()) { + prose += markdown.slice(cursor, formula.start) + tokens[index]; + cursor = formula.end; + } + prose += markdown.slice(cursor); + return renderedText(parseMarkdownDocument(prose), (value) => + value.replace(new RegExp(`${marker}(\\d+)\ue001`, "g"), (_, index: string) => { + const formula = formulas[Number(index)]!; + const tex = formula.tex.trim(); + return formula.display ? `\\[\n${tex}\n\\]` : `\\(${tex}\\)`; + }), + ); +} + +function citationSegments(markdown: string, path = ""): Array<{ path: string; text: string }> { + return splitMarkdownDetails(markdown).flatMap((block, index) => { + if (block.kind === "details") return citationSegments(block.body, `${path}${index}/`); + return splitCodexArtifactTemplateMarkdown(block.markdown).flatMap((segment, segmentIndex) => + segment.kind === "markdown" + ? [ + { + path: `${path}${index}:${segmentIndex}`, + text: citationText(renderCodexInlineDirectivesAsMarkdown(segment.markdown)), + }, + ] + : [], + ); + }); +} + +function occurrences(text: string, quote: string): number[] { + const result: number[] = []; + for (let index = text.indexOf(quote); index !== -1; index = text.indexOf(quote, index + 1)) + result.push(index); + return result; +} + +export function collectMobileAssistantTextSelectors(markdown: string, path: string, text: string) { + if (!text.trim()) return []; + const normalize = (value: string) => value.replace(/\s+/g, " "); + const quote = normalize(text); + const segments = citationSegments(markdown); + const segmentIndex = segments.findIndex((segment) => segment.path === path); + const segment = segments[segmentIndex]; + if (!segment) return []; + const leading = segments + .slice(0, segmentIndex) + .map((entry) => entry.text) + .join("\n"); + const fullText = normalize(segments.map((entry) => entry.text).join("\n")); + const offset = normalize(leading + (segmentIndex > 0 ? "\n" : "")).length; + const matches = occurrences(fullText, quote); + const localMatches = occurrences(normalize(segment.text), quote); + if (localMatches.length > 20) return []; + return localMatches.flatMap((localStart) => { + const start = offset + localStart; + const index = matches.indexOf(start); + if (index === -1) return []; + const selector = createAssistantTextSelector(fullText, start, start + quote.length); + return selector ? [{ ...selector, text, occurrence: { index, count: matches.length } }] : []; + }); +} diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts index 0973be037e39a..7b1c34405e063 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts @@ -1,6 +1,7 @@ import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences"; import { MessageId, + PROVIDER_SEND_TURN_MAX_INPUT_CHARS, type ModelSelection, type NodeId, ProviderSessionId, @@ -401,6 +402,18 @@ export const layer: Layer.Layer< cause: "The persisted steering message or target run is missing.", }); } + const text = projectComposerContextForProvider({ + text: message.text, + records: message.context?.records ?? [], + }); + if (text.length > PROVIDER_SEND_TURN_MAX_INPUT_CHARS) { + return yield* new ProviderTurnControlError({ + threadId: input.threadId, + operation: "steer", + providerTurnId: input.providerTurnId, + cause: `Message exceeds ${PROVIDER_SEND_TURN_MAX_INPUT_CHARS.toLocaleString("en-US")} characters after expanding context and quotes. Shorten it and try again.`, + }); + } yield* loaded.session.value .steerTurn({ threadId: input.threadId, @@ -412,10 +425,7 @@ export const layer: Layer.Layer< : { modelSelection: input.modelSelection }), message: { messageId: message.id, - text: projectComposerContextForProvider({ - text: message.text, - records: message.context?.records ?? [], - }), + text, attachments: message.attachments, createdBy: message.createdBy, creationSource: message.creationSource, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index ac2692907cbbc..9960d9ad45084 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -1,3 +1,7 @@ +import { + serializeAssistantCitation, + expandAssistantCitationsForProvider, +} from "@t3tools/shared/assistantCitations"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it, vi } from "vite-plus/test"; @@ -19,6 +23,8 @@ import { RunId, ThreadId, ProjectId, + EnvironmentId, + PROVIDER_SEND_TURN_MAX_INPUT_CHARS, type OrchestrationV2ThreadProjection, OrchestrationV2DomainEvent, } from "@t3tools/contracts"; @@ -1936,3 +1942,36 @@ for (const previousMessages of [[], ["/compact", " /COMPACT "]]) { }), ); } + +effectIt.effect("rejects citation expansion before opening a provider session", () => + Effect.gen(function* () { + const marker = serializeAssistantCitation({ + version: 1, + environmentId: EnvironmentId.make("env"), + threadId: ThreadId.make("thread"), + messageId: MessageId.make("assistant"), + text: "\u0001".repeat(8_000), + start: 0, + end: 8_000, + prefix: "", + suffix: "", + }); + const text = "x".repeat(80_000) + marker; + expect(text.length).toBeLessThan(PROVIDER_SEND_TURN_MAX_INPUT_CHARS); + expect(expandAssistantCitationsForProvider(text).length).toBeGreaterThan( + PROVIDER_SEND_TURN_MAX_INPUT_CHARS, + ); + const harness = makeLocalCommandHarness({ text }); + yield* harness.start; + expect(harness.open).not.toHaveBeenCalled(); + expect(harness.startTurn).not.toHaveBeenCalled(); + expect(harness.projection().runs.at(-1)?.status).toBe("failed"); + expect(harness.projection().turnItems).toMatchObject([ + { + type: "error", + failure: { class: "validation_error", message: expect.stringContaining("120,000") }, + }, + ]); + expect(harness.projection().messages[0]?.text).toBe(text); + }), +); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 2de9fcbc70d9d..ed452aee07f30 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -2,6 +2,7 @@ import { modelSelectionsEqual } from "@t3tools/shared/model"; import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences"; import { CommandId, + PROVIDER_SEND_TURN_MAX_INPUT_CHARS, latestProviderTurnForAttempt, type OrchestrationV2DomainEvent, type OrchestrationV2ContextHandoff, @@ -565,6 +566,28 @@ export const layer: Layer.Layer< }); }, ); + const userText = projectComposerContextForProvider({ + text: message.text, + records: message.context?.records ?? [], + }); + if (userText.length > PROVIDER_SEND_TURN_MAX_INPUT_CHARS) { + yield* settleRunBeforeStart({ + signal: "expanded-input-too-long", + status: "failed", + now: yield* DateTime.now, + providerInstanceId: run.providerInstanceId, + itemProviderThreadId: providerThread.id, + item: { + type: "error", + title: "Message is too long", + failure: makeProviderFailure({ + class: "validation_error", + message: `Message exceeds ${PROVIDER_SEND_TURN_MAX_INPUT_CHARS.toLocaleString("en-US")} characters after expanding context and quotes. Shorten it and try again.`, + }), + }, + }); + return; + } if (message.attachments.length === 0 && message.text.trimStart().startsWith("/")) { const isEmptyCompaction = message.text.trim().toLowerCase() === "/compact" && !projection.hasConversation; @@ -597,10 +620,7 @@ export const layer: Layer.Layer< : yield* Effect.result( providerAuth.tryHandlePromptCommand({ instanceId: authInstanceId, - text: projectComposerContextForProvider({ - text: message.text, - records: message.context?.records ?? [], - }), + text: userText, hasAttachments: false, }), ); @@ -865,10 +885,6 @@ export const layer: Layer.Layer< }); let effectiveHandoffs = handoffs; let resumeFellBack = false; - const userText = projectComposerContextForProvider({ - text: message.text, - records: message.context?.records ?? [], - }); // Native goal commands go verbatim; handoff history waits a turn. const goalDriver = session.driver === "codex" || diff --git a/apps/web/src/lib/assistantTextSelection.test.ts b/apps/web/src/lib/assistantTextSelection.test.ts index d06261cb856aa..a25972be7700a 100644 --- a/apps/web/src/lib/assistantTextSelection.test.ts +++ b/apps/web/src/lib/assistantTextSelection.test.ts @@ -507,3 +507,20 @@ describe("findAssistantCitationText", () => { }); }); }); + +it("resolves a repeated native quote only while its occurrence count is unchanged", () => { + const repeated = "x".repeat(40) + "quote" + "x".repeat(40); + const text = `${repeated} / ${repeated}`; + const second = text.lastIndexOf("quote"); + const citation = { + ...createAssistantTextSelector(text, second, second + 5)!, + occurrence: { index: 1, count: 2 }, + }; + expect(findAssistantCitationText(text, citation)).toEqual({ start: second, end: second + 5 }); + expect(findAssistantCitationText(`${text} / ${repeated}`, citation)).toBeNull(); + const unique = { + ...createAssistantTextSelector("old quote", 4, 9)!, + occurrence: { index: 0, count: 1 }, + }; + expect(findAssistantCitationText("new quote", unique)).toEqual({ start: 4, end: 9 }); +}); diff --git a/apps/web/src/lib/assistantTextSelection.ts b/apps/web/src/lib/assistantTextSelection.ts index 9f83cd829eed0..b81d3de6135b5 100644 --- a/apps/web/src/lib/assistantTextSelection.ts +++ b/apps/web/src/lib/assistantTextSelection.ts @@ -1,14 +1,18 @@ -import { ASSISTANT_CITATION_CONTEXT_LENGTH, type AssistantCitation } from "@t3tools/contracts"; +import { type AssistantCitation } from "@t3tools/contracts"; import { mathWrapperOf } from "../markdown-clipboard"; -export type AssistantTextSelector = { - readonly text: string; - readonly start: number; - readonly end: number; - readonly prefix: string; - readonly suffix: string; -}; +export { + createAssistantTextSelector, + findAssistantCitationText, +} from "@t3tools/shared/assistantCitations"; +import { + createAssistantTextSelector, + findAssistantCitationText, + splitsSurrogatePair, + type AssistantTextSelector, +} from "@t3tools/shared/assistantCitations"; +export type { AssistantTextSelector } from "@t3tools/shared/assistantCitations"; export type AssistantCitationSourceAnchor = { source: HTMLElement; @@ -39,87 +43,6 @@ const EXCLUDED_SELECTOR = `${CONTROL_SELECTOR}, [hidden], [aria-hidden=true], sc const BLOCK_SELECTOR = "address, article, aside, blockquote, dd, div, dl, dt, figcaption, figure, footer, h1, h2, h3, h4, h5, h6, header, hr, li, main, nav, ol, p, pre, section, table, td, th, tr, ul"; -function normalizeWhitespace(text: string): string { - return text.replace(/\s+/g, " "); -} - -function splitsSurrogatePair(text: string, offset: number): boolean { - const before = text.charCodeAt(offset - 1); - const after = text.charCodeAt(offset); - return before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff; -} - -export function createAssistantTextSelector( - text: string, - rawStart: number, - rawEnd: number, -): AssistantTextSelector | null { - const quote = text.slice(rawStart, rawEnd); - if (quote.trim().length === 0) return null; - - const normalized = normalizeWhitespace(text); - let start = normalizeWhitespace(text.slice(0, rawStart)).length; - if (rawStart > 0 && /\s/.test(text[rawStart - 1]!) && /\s/.test(text[rawStart]!)) { - start -= 1; - } - const end = normalizeWhitespace(text.slice(0, rawEnd)).length; - let prefixStart = Math.max(0, start - ASSISTANT_CITATION_CONTEXT_LENGTH); - let suffixEnd = Math.min(normalized.length, end + ASSISTANT_CITATION_CONTEXT_LENGTH); - // A split pair becomes a replacement character when the context enters a URL. - if (splitsSurrogatePair(normalized, prefixStart)) prefixStart += 1; - if (splitsSurrogatePair(normalized, suffixEnd)) suffixEnd -= 1; - return { - text: quote, - start, - end, - prefix: normalized.slice(prefixStart, start), - suffix: normalized.slice(end, suffixEnd), - }; -} - -/** Offsets use normalized UTF-16 units. Saved offsets may drift, so they cannot break context ties. */ -export function findAssistantCitationText( - text: string, - selector: AssistantTextSelector, -): { start: number; end: number } | null { - const normalized = normalizeWhitespace(text); - const quote = normalizeWhitespace(selector.text); - if (quote.trim().length === 0) return null; - - const prefix = normalizeWhitespace(selector.prefix); - const suffix = normalizeWhitespace(selector.suffix); - const matchesContext = (start: number, end: number) => - normalized.slice(Math.max(0, start - prefix.length), start) === prefix && - normalized.slice(end, end + suffix.length) === suffix; - - let match = - Number.isSafeInteger(selector.start) && - Number.isSafeInteger(selector.end) && - selector.start >= 0 && - selector.end - selector.start === quote.length && - normalized.slice(selector.start, selector.end) === quote && - matchesContext(selector.start, selector.end) - ? { start: selector.start, end: selector.end } - : null; - let onlyQuote: { start: number; end: number } | null = null; - let quoteCount = 0; - - for ( - let start = normalized.indexOf(quote); - start !== -1; - start = normalized.indexOf(quote, start + 1) - ) { - const end = start + quote.length; - quoteCount += 1; - onlyQuote = { start, end }; - if (!matchesContext(start, end)) continue; - if (match !== null && match.start !== start) return null; - match = { start, end }; - } - - return match ?? (quoteCount === 1 ? onlyQuote : null); -} - /** A text node, or a whole rendered formula standing for its TeX. */ type TextChunk = { node: Text | Element; start: number; end: number }; diff --git a/docs/internals/assistant-citations.md b/docs/internals/assistant-citations.md index ec830f75bc031..7b440875a50c2 100644 --- a/docs/internals/assistant-citations.md +++ b/docs/internals/assistant-citations.md @@ -11,8 +11,10 @@ Source navigation is best effort. [Text selectors](../../apps/web/src/lib/assist refer to rendered text after whitespace normalization, measured in UTF-16 units. They cannot be applied to raw Markdown. The original excerpt keeps its whitespace; normalization is only for locating it. Repeated text needs an unambiguous context -match, even if one occurrence still sits at the saved offsets. Guessing could -highlight the wrong claim. +match, even if one occurrence still sits at the saved offsets. Mobile records an +explicit occurrence choice when the native renderer cannot identify its block; +that choice resolves only while the rendered occurrence count and context still +match. Guessing could highlight the wrong claim. Navigation owns the highlight's lifetime across virtual-row remounts. The source row must be fetched, unfolded, mounted, and measured before quote positioning diff --git a/docs/user/composer.md b/docs/user/composer.md index 7bff24f0dab48..db1975450bdc1 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -143,7 +143,9 @@ with its quote, and sending tells the agent which words were quoted and which co The quoted text and comment count toward the message limit. On mobile, long-press an assistant response, adjust the text selection, and choose -**Cite** to insert a quote at the composer cursor. Tap a quote in a draft to add +**Cite** to insert a quote at the composer cursor. If the passage appears more than +once in that section, choose its source occurrence. Select more surrounding text +if a short passage appears too often. Tap a quote in a draft to add or edit its comment, or to remove it. To open the source message, tap a quote in a draft or sent message, then choose **Go to message**. diff --git a/packages/contracts/src/assistantCitations.ts b/packages/contracts/src/assistantCitations.ts index 96572a4bfa656..ee16537fc5b71 100644 --- a/packages/contracts/src/assistantCitations.ts +++ b/packages/contracts/src/assistantCitations.ts @@ -22,6 +22,15 @@ export const AssistantCitation = Schema.Struct({ ), start: NonNegativeInt.check(Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER)), end: NonNegativeInt.check(Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER)), + occurrence: Schema.optional( + Schema.Struct({ + index: NonNegativeInt.check(Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER)), + count: NonNegativeInt.check( + Schema.isGreaterThan(0), + Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER), + ), + }).check(Schema.makeFilter((value) => value.index < value.count)), + ), prefix: Schema.String.check(Schema.isMaxLength(ASSISTANT_CITATION_CONTEXT_LENGTH)), suffix: Schema.String.check(Schema.isMaxLength(ASSISTANT_CITATION_CONTEXT_LENGTH)), }).check( diff --git a/packages/shared/src/assistantCitations.test.ts b/packages/shared/src/assistantCitations.test.ts index 7dbaaf9d8bdeb..a698e482ee4f1 100644 --- a/packages/shared/src/assistantCitations.test.ts +++ b/packages/shared/src/assistantCitations.test.ts @@ -95,6 +95,10 @@ describe("assistant citation references", () => { "t3-citation://v1/a/b/c?text=quote&start=5&end=0&prefix=&suffix=", "t3-citation://v1/a/b/c?text=quote&start=0&end=5&prefix=&suffix=&text=other", "t3-citation://v1/a/b/c?text=quote&start=0&end=5&prefix=&suffix=&unknown=value", + "t3-citation://v1/a/b/c?text=quote&start=0&end=5&prefix=&suffix=&occurrence=0", + "t3-citation://v1/a/b/c?text=quote&start=0&end=5&prefix=&suffix=&occurrence=1&occurrences=1", + "t3-citation://v1/a/b/c?text=quote&start=0&end=5&prefix=&suffix=&occurrence=0&occurrences=0", + "t3-citation://v1/a/b/c?text=quote&start=0&end=5&prefix=&suffix=&occurrence=0&occurrences=9007199254740992", "t3-citation://v1/a/b/c?text=quote&start=0&end=5&prefix=&suffix=&comment=one&comment=two", ])("leaves invalid or unsupported references unchanged: %s", (href) => { expect(parseAssistantCitationHref(href)).toBeNull(); @@ -282,3 +286,15 @@ describe("assistant citation references", () => { ); }); }); + +it("retains distinct repeated occurrences through serialization and provider expansion", () => { + const first = { ...citation, occurrence: { index: 0, count: 2 } }; + const second = { ...citation, occurrence: { index: 1, count: 2 } }; + expect(parseAssistantCitationHref(formatAssistantCitationHref(second))).toEqual(second); + const expanded = readProviderContext( + expandAssistantCitationsForProvider( + `${serializeAssistantCitation(first)} ${serializeAssistantCitation(second)}`, + ), + ); + expect(expanded).toHaveLength(2); +}); diff --git a/packages/shared/src/assistantCitations.ts b/packages/shared/src/assistantCitations.ts index bb072e462a45e..d776af320a059 100644 --- a/packages/shared/src/assistantCitations.ts +++ b/packages/shared/src/assistantCitations.ts @@ -51,6 +51,10 @@ export function formatAssistantCitationHref(citation: AssistantCitation): string prefix: citation.prefix, suffix: citation.suffix, }); + if (citation.occurrence !== undefined) { + query.set("occurrence", String(citation.occurrence.index)); + query.set("occurrences", String(citation.occurrence.count)); + } if (citation.comment !== undefined) query.set("comment", citation.comment); return `${CITATION_HREF_PREFIX}${path}?${query}`; } @@ -75,8 +79,14 @@ export function parseAssistantCitationHref(href: string): AssistantCitation | nu } const requiredKeys = ["text", "start", "end", "prefix", "suffix"]; const comment = url.searchParams.get("comment"); + const occurrence = url.searchParams.get("occurrence"); + const occurrences = url.searchParams.get("occurrences"); + if ((occurrence === null) !== (occurrences === null)) return null; + if (occurrence !== null && (!/^\d{1,16}$/.test(occurrence) || !/^\d{1,16}$/.test(occurrences!))) + return null; if ( - url.searchParams.size !== requiredKeys.length + (comment === null ? 0 : 1) || + url.searchParams.size !== + requiredKeys.length + (comment === null ? 0 : 1) + (occurrence === null ? 0 : 2) || requiredKeys.some((key) => url.searchParams.getAll(key).length !== 1) ) { return null; @@ -96,6 +106,9 @@ export function parseAssistantCitationHref(href: string): AssistantCitation | nu prefix: url.searchParams.get("prefix"), suffix: url.searchParams.get("suffix"), ...(comment === null ? {} : { comment }), + ...(occurrence === null + ? {} + : { occurrence: { index: Number(occurrence), count: Number(occurrences) } }), }), ); } catch { @@ -198,3 +211,100 @@ export function renderAssistantCitationsAsText(prompt: string): string { } return text + prompt.slice(cursor); } + +export type AssistantTextSelector = { + readonly text: string; + readonly start: number; + readonly end: number; + readonly prefix: string; + readonly suffix: string; + readonly occurrence?: AssistantCitation["occurrence"]; +}; + +function normalizeWhitespace(text: string): string { + return text.replace(/\s+/g, " "); +} + +export function splitsSurrogatePair(text: string, offset: number): boolean { + const before = text.charCodeAt(offset - 1); + const after = text.charCodeAt(offset); + return before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff; +} + +export function createAssistantTextSelector( + text: string, + rawStart: number, + rawEnd: number, +): AssistantTextSelector | null { + const quote = text.slice(rawStart, rawEnd); + if (quote.trim().length === 0) return null; + + const normalized = normalizeWhitespace(text); + let start = normalizeWhitespace(text.slice(0, rawStart)).length; + if (rawStart > 0 && /\s/.test(text[rawStart - 1]!) && /\s/.test(text[rawStart]!)) { + start -= 1; + } + const end = normalizeWhitespace(text.slice(0, rawEnd)).length; + let prefixStart = Math.max(0, start - ASSISTANT_CITATION_CONTEXT_LENGTH); + let suffixEnd = Math.min(normalized.length, end + ASSISTANT_CITATION_CONTEXT_LENGTH); + // A split pair becomes a replacement character when the context enters a URL. + if (splitsSurrogatePair(normalized, prefixStart)) prefixStart += 1; + if (splitsSurrogatePair(normalized, suffixEnd)) suffixEnd -= 1; + return { + text: quote, + start, + end, + prefix: normalized.slice(prefixStart, start), + suffix: normalized.slice(end, suffixEnd), + }; +} + +/** Offsets use normalized UTF-16 units. Saved offsets may drift, so they cannot break context ties. */ +export function findAssistantCitationText( + text: string, + selector: AssistantTextSelector, +): { start: number; end: number } | null { + const normalized = normalizeWhitespace(text); + const quote = normalizeWhitespace(selector.text); + if (quote.trim().length === 0) return null; + + const prefix = normalizeWhitespace(selector.prefix); + const suffix = normalizeWhitespace(selector.suffix); + const matchesContext = (start: number, end: number) => + normalized.slice(Math.max(0, start - prefix.length), start) === prefix && + normalized.slice(end, end + suffix.length) === suffix; + + let match = + Number.isSafeInteger(selector.start) && + Number.isSafeInteger(selector.end) && + selector.start >= 0 && + selector.end - selector.start === quote.length && + normalized.slice(selector.start, selector.end) === quote && + matchesContext(selector.start, selector.end) + ? { start: selector.start, end: selector.end } + : null; + let onlyQuote: { start: number; end: number } | null = null; + let quoteCount = 0; + let occurrenceMatch: { start: number; end: number } | null = null; + + for ( + let start = normalized.indexOf(quote); + start !== -1; + start = normalized.indexOf(quote, start + 1) + ) { + const end = start + quote.length; + if (selector.occurrence?.index === quoteCount) occurrenceMatch = { start, end }; + quoteCount += 1; + onlyQuote = { start, end }; + if (!matchesContext(start, end)) continue; + if (match !== null && match.start !== start && selector.occurrence === undefined) return null; + match = { start, end }; + } + + if (selector.occurrence !== undefined) { + if (quoteCount !== selector.occurrence.count || occurrenceMatch === null) return null; + if (quoteCount === 1) return occurrenceMatch; + return matchesContext(occurrenceMatch.start, occurrenceMatch.end) ? occurrenceMatch : null; + } + return match ?? (quoteCount === 1 ? onlyQuote : null); +} From 75e6ac4c9411b4ef4f12ce5794eaf313d563c091 Mon Sep 17 00:00:00 2001 From: Jake Leventhal Date: Thu, 12 Nov 2026 10:50:27 -0500 Subject: [PATCH 07/16] test(mobile): isolate citation picker presentation in previews --- apps/mobile/src/lib/filePreview.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/mobile/src/lib/filePreview.test.ts b/apps/mobile/src/lib/filePreview.test.ts index 47f00f0e2f1fb..d25b8ffe7d0fb 100644 --- a/apps/mobile/src/lib/filePreview.test.ts +++ b/apps/mobile/src/lib/filePreview.test.ts @@ -232,6 +232,8 @@ vi.mock("expo-haptics", () => ({ selectionAsync: async () => {} })); vi.mock("expo-image", () => ({})); vi.mock("uniwind", () => ({})); vi.mock("../components/ui/Dialog", () => ({})); +vi.mock("../components/ui/Sheet", () => ({ Sheet: () => null })); +vi.mock("../components/ui/ListActionRow", () => ({ ListActionRow: () => null })); vi.mock("../components/ui/NativePresentation", () => ({ PresentationSource: ({ children }: { children?: ReactNode }) => children, })); From e372cac1fc3f88a1f15f0017f27e4e2dd1c370a4 Mon Sep 17 00:00:00 2001 From: Jake Leventhal Date: Thu, 12 Nov 2026 11:42:16 -0500 Subject: [PATCH 08/16] fix(mobile): keep quote choices aligned with live text --- .../src/features/threads/ThreadFeed.tsx | 17 ++-- .../lib/assistantCitationSelection.test.ts | 7 ++ .../src/lib/assistantCitationSelection.ts | 8 +- apps/mobile/src/lib/filePreview.test.ts | 82 ++++++++++++++++++- 4 files changed, 101 insertions(+), 13 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 3e4748f723af0..a1413f83b75cc 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -1152,12 +1152,16 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { readonly renderImage: MarkdownImageRenderer; readonly skills?: ReadonlyArray | undefined; }) { - const [quoteChoices, setQuoteChoices] = useState< - ReturnType - >([]); + const liveMarkdown = useLiveThreadLinkLabels(props.markdown, props.environmentId); + const [quoteSelection, setQuoteSelection] = useState<{ + markdown: string; + selectors: ReturnType; + } | null>(null); + if (quoteSelection !== null && quoteSelection.markdown !== liveMarkdown) setQuoteSelection(null); + const quoteChoices = quoteSelection?.selectors ?? []; const cite = (selector: (typeof quoteChoices)[number]) => { if (!props.citationSource || !props.onCiteAssistantText) return; - setQuoteChoices([]); + setQuoteSelection(null); props.onCiteAssistantText({ version: 1, environmentId: props.environmentId, @@ -1166,7 +1170,6 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { }); }; const models = useModelMentions(props.environmentId, props.markdown); - const liveMarkdown = useLiveThreadLinkLabels(props.markdown, props.environmentId); const threadIcons = useThreadChipIcons(props.environmentId, liveMarkdown); const linkHandlers: MarkdownLinkHandlers = { ...props.linkHandlers, @@ -1198,7 +1201,7 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { return; } if (selectors.length === 1) cite(selectors[0]!); - else setQuoteChoices(selectors); + else setQuoteSelection({ markdown: liveMarkdown, selectors }); } : undefined } @@ -1210,7 +1213,7 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { models={models} /> {quoteChoices.length > 0 && props.onCiteAssistantText ? ( - setQuoteChoices([])}> + setQuoteSelection(null)}> More\n\n` quote`\n\n", + "1/0:0", + "quote", + ); + expect(leadingSpace?.start).toBe(2); + expect(leadingSpace?.occurrence).toEqual({ index: 0, count: 1 }); }); it("rejects unmappable or blank selections instead of inventing a source", () => { diff --git a/apps/mobile/src/lib/assistantCitationSelection.ts b/apps/mobile/src/lib/assistantCitationSelection.ts index 350b5e4d8fc44..5851cfa41b492 100644 --- a/apps/mobile/src/lib/assistantCitationSelection.ts +++ b/apps/mobile/src/lib/assistantCitationSelection.ts @@ -83,12 +83,12 @@ export function collectMobileAssistantTextSelectors(markdown: string, path: stri const segmentIndex = segments.findIndex((segment) => segment.path === path); const segment = segments[segmentIndex]; if (!segment) return []; - const leading = segments - .slice(0, segmentIndex) + const fullText = normalize(segments.map((entry) => entry.text).join("\n")); + const throughSegment = segments + .slice(0, segmentIndex + 1) .map((entry) => entry.text) .join("\n"); - const fullText = normalize(segments.map((entry) => entry.text).join("\n")); - const offset = normalize(leading + (segmentIndex > 0 ? "\n" : "")).length; + const offset = normalize(throughSegment).length - normalize(segment.text).length; const matches = occurrences(fullText, quote); const localMatches = occurrences(normalize(segment.text), quote); if (localMatches.length > 20) return []; diff --git a/apps/mobile/src/lib/filePreview.test.ts b/apps/mobile/src/lib/filePreview.test.ts index d25b8ffe7d0fb..e0e2f12da19a6 100644 --- a/apps/mobile/src/lib/filePreview.test.ts +++ b/apps/mobile/src/lib/filePreview.test.ts @@ -85,6 +85,7 @@ vi.mock("react-native", () => ({ addEventListener: () => ({ remove() {} }), }, View: ({ children }: { children?: ReactNode }) => createElement("div", null, children), + ScrollView: ({ children }: { children?: ReactNode }) => createElement("div", null, children), Pressable: (props: { children?: ReactNode; onPress: () => void; @@ -193,12 +194,15 @@ vi.mock("../native/SelectableMarkdownText", () => ({ markdown: string; onLinkPress(href: string): void; renderImage?: MarkdownImageRenderer; + onCiteText?: (text: string) => void; }) => { const embed = props.markdown.match(/!\[([^\]]*)\]\(([^)]+)\)/); return createElement( "div", null, createElement("button", { onClick: () => props.onLinkPress("target.ts") }, props.markdown), + props.onCiteText && + createElement("button", { onClick: () => props.onCiteText?.("quote") }, "Cite quote"), embed && props.renderImage?.({ href: embed[2]!, alt: embed[1]!, title: null }), ); }, @@ -232,8 +236,13 @@ vi.mock("expo-haptics", () => ({ selectionAsync: async () => {} })); vi.mock("expo-image", () => ({})); vi.mock("uniwind", () => ({})); vi.mock("../components/ui/Dialog", () => ({})); -vi.mock("../components/ui/Sheet", () => ({ Sheet: () => null })); -vi.mock("../components/ui/ListActionRow", () => ({ ListActionRow: () => null })); +vi.mock("../components/ui/Sheet", () => ({ + Sheet: ({ children }: { children?: ReactNode }) => children, +})); +vi.mock("../components/ui/ListActionRow", () => ({ + ListActionRow: ({ label, onPress }: { label: string; onPress(): void }) => + createElement("button", { onClick: onPress }, label), +})); vi.mock("../components/ui/NativePresentation", () => ({ PresentationSource: ({ children }: { children?: ReactNode }) => children, })); @@ -1333,6 +1342,75 @@ describe("inline file previews", () => { }); describe("ThreadFeed previews", () => { + it("drops stale quote choices when the streaming source changes", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const environmentId = EnvironmentId.make("environment-1"); + const threadId = ThreadId.make("thread-1"); + const messageId = MessageId.make("message-1"); + const timestamp = "2026-10-20T00:00:00.000Z"; + const cited = vi.fn(); + const element = (text: string) => + createElement(ThreadFeed, { + environmentId, + threadId, + detailRef: null, + threadTitle: "quotes", + workspaceRoot: "/repo", + feed: [ + { + type: "message", + id: messageId, + createdAt: timestamp, + message: { + id: messageId, + role: "assistant", + text, + attachments: [], + createdAt: timestamp, + updatedAt: timestamp, + runId: null, + streaming: true, + visibility: "local", + sourceThreadId: threadId, + }, + }, + ], + queuedMessages: [], + dispatchingMessageId: null, + onEditPendingMessage: null, + contentPresentation: { kind: "ready" }, + latestRun: null, + activeWorkStartedAt: null, + listRef: { current: null }, + freeze: { value: false } as Parameters[0]["freeze"], + contentInsetEndAdjustment: { value: 0 } as Parameters< + typeof ThreadFeed + >[0]["contentInsetEndAdjustment"], + anchorMessageId: null, + keyboardOffset: 0, + onCiteAssistantText: cited, + }); + const container = document.createElement("div"); + const root = createRoot(container); + const button = (text: string) => + [...container.querySelectorAll("button")].find((e) => e.textContent === text); + try { + await act(async () => root.render(element("first quote then quote"))); + await act(async () => button("Cite quote")!.click()); + expect(button("Occurrence 2 of 2")).toBeDefined(); + await act(async () => root.render(element("first quote then quote and quote"))); + expect(button("Occurrence 2 of 2")).toBeUndefined(); + expect(cited).not.toHaveBeenCalled(); + await act(async () => button("Cite quote")!.click()); + await act(async () => button("Occurrence 2 of 3")!.click()); + expect(cited).toHaveBeenCalledWith( + expect.objectContaining({ occurrence: { index: 1, count: 3 } }), + ); + } finally { + await act(async () => root.unmount()); + } + }); + it("does not commit an open preview over a different thread", async () => { (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; const environmentId = EnvironmentId.make("environment-1"); From 209ae250363e674da5e1277aebc5c316b141d7a9 Mon Sep 17 00:00:00 2001 From: Jake Leventhal Date: Thu, 12 Nov 2026 11:45:07 -0500 Subject: [PATCH 09/16] fix(server): reject oversized steering input before delivery --- .../src/orchestration-v2/Orchestrator.ts | 13 ++ .../SteeringCompletion.integration.test.ts | 133 ++++++++++++++++++ 2 files changed, 146 insertions(+) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index c186c40f9e73a..c0c0fd7f881d3 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -65,6 +65,7 @@ import { parseGoalCommand, orchestrationV2RunWorkStartedAt, ProviderInstanceId, + PROVIDER_SEND_TURN_MAX_INPUT_CHARS, ProviderInteractionMode, isRuntimeModeAbove, resolveProviderInstanceEnabled, @@ -80,6 +81,7 @@ import { } from "@t3tools/contracts"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { modelSelectionsEqual } from "@t3tools/shared/model"; +import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences"; import { modelSwitchSince } from "./modelSwitch.ts"; import { combinePullRequestWatchWakes, type PullRequestWatchWake } from "./pullRequestWatch.ts"; import { recordThreadOpen } from "@t3tools/shared/paletteSearch"; @@ -5543,6 +5545,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio >, message: Pick, ) { + const text = projectComposerContextForProvider({ + text: message.text, + records: message.context?.records ?? [], + }); + if (text.length > PROVIDER_SEND_TURN_MAX_INPUT_CHARS) { + return yield* new OrchestratorCommandRejectedError({ + commandId: command.commandId, + commandType: command.type, + cause: `Message exceeds ${PROVIDER_SEND_TURN_MAX_INPUT_CHARS.toLocaleString("en-US")} characters after expanding context and quotes. Shorten it and try again.`, + }); + } if (isNativeMaintenanceCommand(message)) { return yield* new OrchestratorDispatchError({ commandId: command.commandId, diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index ad0c179d783fe..10e062efc4902 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1,6 +1,7 @@ import { assert, it } from "@effect/vitest"; import { ChatAttachmentId, + ComposerContextId, CommandId, EnvironmentId, MessageId, @@ -11,11 +12,14 @@ import { ProviderInstanceId, ProviderThreadId, ProviderTurnId, + PROVIDER_SEND_TURN_MAX_INPUT_CHARS, ThreadId, TurnItemId, type ModelSelection, type OrchestrationV2DomainEvent, } from "@t3tools/contracts"; +import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations"; +import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; @@ -34,6 +38,7 @@ import * as ThreadManagementService from "./ThreadManagementService.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as CommandReceiptStore from "./CommandReceiptStore.ts"; +import { userFacingDispatchErrorMessage } from "./UserFacingErrors.ts"; import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; @@ -2123,6 +2128,134 @@ it.effect("keeps a held commentary draft before the steer when turn end flushes ), ); +it.effect.each(["auto", "restart", "deferred", "promote-edited"] as const)( + "rejects expanded steering input before commit: %s", + (delivery) => + Effect.scoped( + Effect.gen(function* () { + const { started, steered, interrupted, layer, startFirstTurn } = + yield* nextTurnSelectionHarness(`oversized-steer-${delivery}`, true); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const outbox = yield* EffectOutbox.EffectOutboxV2; + const sink = yield* EventSink.EventSinkV2; + const threadId = yield* startFirstTurn; + const first = started[0]!; + const citation = serializeAssistantCitation({ + version: 1, + environmentId: EnvironmentId.make("env"), + threadId, + messageId: MessageId.make("assistant"), + text: "\u0001".repeat(5_000), + start: 0, + end: 5_000, + prefix: "", + suffix: "", + }); + const text = `${"x".repeat(80_000)}${citation}[log](t3-context://v1/terminal/log)`; + const context = { + version: 1 as const, + records: [ + { + version: 1 as const, + kind: "terminal" as const, + contextId: ComposerContextId.make("log"), + label: "log", + terminalId: "terminal", + terminalLabel: "Terminal", + lineStart: 1, + lineEnd: 1, + text: "y".repeat(20_000), + }, + ], + }; + assert.isBelow(text.length, PROVIDER_SEND_TURN_MAX_INPUT_CHARS); + assert.isBelow( + projectComposerContextForProvider({ text, records: [] }).length, + PROVIDER_SEND_TURN_MAX_INPUT_CHARS, + ); + assert.isAbove( + projectComposerContextForProvider({ text, records: context.records }).length, + PROVIDER_SEND_TURN_MAX_INPUT_CHARS, + ); + if (delivery === "deferred") { + const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!; + yield* sink.write({ + events: [ + { + id: EventId.make("turn-not-ready"), + type: "provider-turn.updated", + threadId, + occurredAt: yield* DateTime.now, + payload: { ...turn, status: "pending" }, + }, + ], + }); + } + const commandId = CommandId.make("oversized-steer"); + let command: Parameters[0] = { + type: "message.dispatch", + commandId, + threadId, + messageId: MessageId.make("oversized"), + text, + context, + attachments: [], + dispatchMode: { type: "start_immediately" }, + deliveryIntent: + delivery === "restart" ? "restart" : delivery === "deferred" ? "steer" : "auto", + createdBy: "user", + creationSource: "mobile", + }; + if (delivery === "promote-edited") { + yield* orchestrator.dispatch({ + ...command, + commandId: CommandId.make("queue"), + text: "Initially valid queued message", + dispatchMode: { type: "queue_after_active" }, + deliveryIntent: undefined, + }); + const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.status === "queued", + )!; + yield* orchestrator.dispatch({ + type: "queued-run.edit", + commandId: CommandId.make("edit"), + threadId, + runId: queued.id, + text, + context, + }); + command = { + type: "queued-message.promote-to-steer", + commandId, + threadId, + queuedRunId: queued.id, + targetRunId: first.runId, + }; + } + const before = yield* orchestrator.getThreadProjection(threadId); + const sequence = yield* orchestrator.getThreadEventSequence(threadId); + const error = yield* orchestrator.dispatch(command).pipe(Effect.flip); + assert.instanceOf(error, Orchestrator.OrchestratorCommandRejectedError); + assert.equal( + userFacingDispatchErrorMessage(error), + "Message exceeds 120,000 characters after expanding context and quotes. Shorten it and try again.", + ); + assert.deepEqual(yield* outbox.listByCommandId(commandId), []); + assert.deepEqual(yield* sink.readByCommandId({ commandId }).pipe(Stream.runCollect), []); + yield* worker.drain(); + assert.equal(yield* orchestrator.getThreadEventSequence(threadId), sequence); + assert.deepEqual(yield* orchestrator.getThreadProjection(threadId), before); + assert.deepEqual(steered, []); + assert.deepEqual(interrupted, []); + assert.lengthOf(started, 1); + }).pipe(Effect.provide(layer)); + }), + ), +); + it.effect("steers a promoted queued message with the selection it was queued with", () => Effect.scoped( Effect.gen(function* () { From 4b6e9e7fbe7af3043ae0948af57283b6293ad357 Mon Sep 17 00:00:00 2001 From: Jake Leventhal Date: Thu, 12 Nov 2026 12:13:38 -0500 Subject: [PATCH 10/16] fix(mobile): ignore empty blocks in citation context --- .../src/lib/assistantCitationSelection.test.ts | 17 +++++++++++++++++ .../src/lib/assistantCitationSelection.ts | 7 +++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/apps/mobile/src/lib/assistantCitationSelection.test.ts b/apps/mobile/src/lib/assistantCitationSelection.test.ts index 0abe6b723e780..6e7e5a9f1410d 100644 --- a/apps/mobile/src/lib/assistantCitationSelection.test.ts +++ b/apps/mobile/src/lib/assistantCitationSelection.test.ts @@ -46,6 +46,23 @@ it("offers distinct source choices within a block and maps recursive folds witho ); expect(leadingSpace?.start).toBe(2); expect(leadingSpace?.occurrence).toEqual({ index: 0, count: 1 }); + for (const { source, path } of [ + { source: "![before](image.png)\n\nquote quote\n\n![after](image.png)", path: "0:0" }, + { + source: + "![before](image.png)\n\n
More\n\nquote quote\n\n
\n\n![after](image.png)", + path: "1/0:0", + }, + ]) { + const selectors = collectMobileAssistantTextSelectors(source, path, "quote"); + expect(selectors).toHaveLength(2); + for (const [index, selector] of selectors.entries()) { + expect(findAssistantCitationText("quote quote", selector)).toEqual({ + start: index * 6, + end: index * 6 + 5, + }); + } + } }); it("rejects unmappable or blank selections instead of inventing a source", () => { diff --git a/apps/mobile/src/lib/assistantCitationSelection.ts b/apps/mobile/src/lib/assistantCitationSelection.ts index 5851cfa41b492..bdc157926ebb8 100644 --- a/apps/mobile/src/lib/assistantCitationSelection.ts +++ b/apps/mobile/src/lib/assistantCitationSelection.ts @@ -26,7 +26,10 @@ function renderedText(node: MarkdownNode, restoreMath: (value: string) => string node.type === "strong" || node.type === "delete" || node.type === "tableCell"; - return node.children.map((child) => renderedText(child, restoreMath)).join(inline ? "" : "\n"); + return node.children + .map((child) => renderedText(child, restoreMath)) + .filter((text) => text.length > 0) + .join(inline ? "" : "\n"); } return node.type === "break" ? "\n" : ""; } @@ -79,7 +82,7 @@ export function collectMobileAssistantTextSelectors(markdown: string, path: stri if (!text.trim()) return []; const normalize = (value: string) => value.replace(/\s+/g, " "); const quote = normalize(text); - const segments = citationSegments(markdown); + const segments = citationSegments(markdown).filter((segment) => segment.text.trim().length > 0); const segmentIndex = segments.findIndex((segment) => segment.path === path); const segment = segments[segmentIndex]; if (!segment) return []; From 305f7fd2c1dcda6ac113519e4c147ae26006612e Mon Sep 17 00:00:00 2001 From: Jake Leventhal Date: Thu, 12 Nov 2026 12:35:31 -0500 Subject: [PATCH 11/16] fix(mobile): exclude diagram source from citation occurrences --- .../src/lib/assistantCitationSelection.test.ts | 14 ++++++++++++++ apps/mobile/src/lib/assistantCitationSelection.ts | 3 ++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/apps/mobile/src/lib/assistantCitationSelection.test.ts b/apps/mobile/src/lib/assistantCitationSelection.test.ts index 6e7e5a9f1410d..971739c082eec 100644 --- a/apps/mobile/src/lib/assistantCitationSelection.test.ts +++ b/apps/mobile/src/lib/assistantCitationSelection.test.ts @@ -46,8 +46,22 @@ it("offers distinct source choices within a block and maps recursive folds witho ); expect(leadingSpace?.start).toBe(2); expect(leadingSpace?.occurrence).toEqual({ index: 0, count: 1 }); + const codeChoices = collectMobileAssistantTextSelectors( + "quote\n\n```text\nquote\n```\n\nquote", + "0:0", + "quote", + ); + expect(codeChoices.map((choice) => choice.occurrence)).toEqual([ + { index: 0, count: 3 }, + { index: 1, count: 3 }, + { index: 2, count: 3 }, + ]); for (const { source, path } of [ { source: "![before](image.png)\n\nquote quote\n\n![after](image.png)", path: "0:0" }, + { + source: 'quote\n\n```mermaid\nflowchart TD\nA["quote"]\n```\n\nquote', + path: "0:0", + }, { source: "![before](image.png)\n\n
More\n\nquote quote\n\n
\n\n![after](image.png)", diff --git a/apps/mobile/src/lib/assistantCitationSelection.ts b/apps/mobile/src/lib/assistantCitationSelection.ts index bdc157926ebb8..4915f213be08f 100644 --- a/apps/mobile/src/lib/assistantCitationSelection.ts +++ b/apps/mobile/src/lib/assistantCitationSelection.ts @@ -12,7 +12,8 @@ function renderedText(node: MarkdownNode, restoreMath: (value: string) => string node.type === "definition" || node.type === "image" || node.type === "imageReference" || - node.type === "html" + node.type === "html" || + (node.type === "code" && node.lang === "mermaid") ) return ""; if ("value" in node) return restoreMath(node.value); From 81f59c3e179efa2c7374d7e5a4a13b220a10b5bc Mon Sep 17 00:00:00 2001 From: maria-rcks Date: Sun, 15 Nov 2026 02:58:19 +0000 Subject: [PATCH 12/16] fix(citations): preserve legacy links for unique quotes --- packages/shared/src/assistantCitations.test.ts | 3 +++ packages/shared/src/assistantCitations.ts | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/shared/src/assistantCitations.test.ts b/packages/shared/src/assistantCitations.test.ts index a698e482ee4f1..cc15cc1da703c 100644 --- a/packages/shared/src/assistantCitations.test.ts +++ b/packages/shared/src/assistantCitations.test.ts @@ -57,6 +57,9 @@ describe("assistant citation references", () => { it("preserves legacy v1 link bytes without adding a comment", () => { expect(parseAssistantCitationHref(legacyHref)).toStrictEqual(legacyCitation); expect(formatAssistantCitationHref(legacyCitation)).toBe(legacyHref); + expect( + formatAssistantCitationHref({ ...legacyCitation, occurrence: { index: 0, count: 1 } }), + ).toBe(legacyHref); expect(formatAssistantCitationHref({ ...legacyCitation, comment: undefined })).toBe(legacyHref); expect(serializeAssistantCitation(legacyCitation)).toBe(`[Assistant quote](${legacyHref})`); }); diff --git a/packages/shared/src/assistantCitations.ts b/packages/shared/src/assistantCitations.ts index d776af320a059..ecf50c1e4e008 100644 --- a/packages/shared/src/assistantCitations.ts +++ b/packages/shared/src/assistantCitations.ts @@ -51,7 +51,7 @@ export function formatAssistantCitationHref(citation: AssistantCitation): string prefix: citation.prefix, suffix: citation.suffix, }); - if (citation.occurrence !== undefined) { + if (citation.occurrence !== undefined && citation.occurrence.count > 1) { query.set("occurrence", String(citation.occurrence.index)); query.set("occurrences", String(citation.occurrence.count)); } From c4de196c6488a2a9186a328c28648ac33ef57c36 Mon Sep 17 00:00:00 2001 From: maria-rcks Date: Sun, 15 Nov 2026 03:08:59 +0000 Subject: [PATCH 13/16] fix(citations): preserve merged validation and reference handling --- .../lib/assistantCitationSelection.test.ts | 6 +++++ .../src/lib/assistantCitationSelection.ts | 22 +++++++++++++++---- .../ProviderTurnStartService.ts | 4 ++++ 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/apps/mobile/src/lib/assistantCitationSelection.test.ts b/apps/mobile/src/lib/assistantCitationSelection.test.ts index 971739c082eec..46c30a0bb131c 100644 --- a/apps/mobile/src/lib/assistantCitationSelection.test.ts +++ b/apps/mobile/src/lib/assistantCitationSelection.test.ts @@ -32,6 +32,12 @@ it("offers distinct source choices within a block and maps recursive folds witho expect(expandAssistantCitationsForProvider(markers.join(" "))).toContain( '"id": "assistant-quote-2"', ); + const [reference] = collectMobileAssistantTextSelectors( + "before [label][id] after\n\n
More\n\n[id]: https://example.com\n\n
", + "0:0", + "before label after", + ); + expect(reference?.text).toBe("before label after"); const sameBlock = collectMobileAssistantTextSelectors( "first **quote** then **quote** last", "0:0", diff --git a/apps/mobile/src/lib/assistantCitationSelection.ts b/apps/mobile/src/lib/assistantCitationSelection.ts index 4915f213be08f..294cd7f091ddb 100644 --- a/apps/mobile/src/lib/assistantCitationSelection.ts +++ b/apps/mobile/src/lib/assistantCitationSelection.ts @@ -5,7 +5,12 @@ import { renderCodexInlineDirectivesAsMarkdown, } from "@t3tools/shared/codexMarkdownDirectives"; import { splitMarkdownDetails } from "./markdownDetails"; -import { parseMarkdownDocument, type MarkdownNode } from "./markdownDocument"; +import { + markdownReferenceDefinitions, + parseMarkdownDocument, + withReferenceDefinitions, + type MarkdownNode, +} from "./markdownDocument"; function renderedText(node: MarkdownNode, restoreMath: (value: string) => string): string { if ( @@ -56,15 +61,24 @@ function citationText(markdown: string): string { ); } -function citationSegments(markdown: string, path = ""): Array<{ path: string; text: string }> { +function citationSegments( + markdown: string, + path = "", + definitions = markdownReferenceDefinitions(markdown), +): Array<{ path: string; text: string }> { return splitMarkdownDetails(markdown).flatMap((block, index) => { - if (block.kind === "details") return citationSegments(block.body, `${path}${index}/`); + if (block.kind === "details") + return citationSegments(block.body, `${path}${index}/`, definitions); return splitCodexArtifactTemplateMarkdown(block.markdown).flatMap((segment, segmentIndex) => segment.kind === "markdown" ? [ { path: `${path}${index}:${segmentIndex}`, - text: citationText(renderCodexInlineDirectivesAsMarkdown(segment.markdown)), + text: citationText( + renderCodexInlineDirectivesAsMarkdown( + withReferenceDefinitions(segment.markdown, definitions), + ), + ), }, ] : [], diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 3f302a9d83c58..b7561ce5e39ab 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -546,6 +546,10 @@ export const layer: Layer.Layer< }); if (userText.length > PROVIDER_SEND_TURN_MAX_INPUT_CHARS) { yield* settleRunBeforeStart({ + run, + rootNode, + attempt, + turnItems: projection.turnItems, signal: "expanded-input-too-long", status: "failed", now: yield* DateTime.now, From f43e86c0416768d415bb005ac08828c4a3dcfccd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 04:58:55 +0000 Subject: [PATCH 14/16] fix(citations): keep citation links readable by released servers Every released server and client rejects a citation link with an unknown query key, so the occurrence/occurrences fields made an older server send the raw link to the provider without the citations block, and older clients could not render or open the quote. The mobile chooser still picks the occurrence; its selector carries that occurrence's own offsets and context, which web already resolves by context. Drop the unreachable steer-time length check: the orchestrator rejects oversized steering before commit on every path, and a failure there would only be retried by the durable worker. Trim tests that only covered the removed fields. Co-Authored-By: Claude Opus 5.5 --- .../features/threads/ThreadDetailScreen.tsx | 8 +-- .../src/features/threads/ThreadFeed.tsx | 12 ++-- .../lib/assistantCitationSelection.test.ts | 46 ++++++------ .../src/lib/assistantCitationSelection.ts | 2 +- apps/mobile/src/lib/filePreview.test.ts | 72 ------------------- .../src/native/T3ComposerEditor.native.tsx | 1 + .../ProviderTurnControlService.ts | 18 ++--- .../SteeringCompletion.integration.test.ts | 5 +- .../src/lib/assistantTextSelection.test.ts | 17 ----- docs/internals/assistant-citations.md | 11 +-- packages/contracts/src/assistantCitations.ts | 9 --- .../shared/src/assistantCitations.test.ts | 16 ----- packages/shared/src/assistantCitations.ts | 25 +------ 13 files changed, 44 insertions(+), 198 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 9a1e0443928b3..27d88e94714da 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -1374,13 +1374,7 @@ function ThreadDetailBody( voiceInputBlocksSubmission(voiceInputSession.controller.currentState) ); const handleCiteAssistantText = (citation: AssistantCitation) => { - if ( - !canCiteAssistantText || - props.composerDraftKey === null || - (voiceInputSession.ownerKey === props.composerDraftKey && - voiceInputBlocksSubmission(voiceInputSession.controller.currentState)) - ) - return; + if (!canCiteAssistantText || props.composerDraftKey === null) return; const target = captureComposerDraftInsertion(props.composerDraftKey); const prefix = target.start > 0 && !/\s/.test(target.text[target.start - 1]!) ? " " : ""; const value = `${prefix}${serializeAssistantCitation(citation)} `; diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 7450a25664241..ec23ed4e7dab7 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -1310,7 +1310,7 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { } | null>(null); if (quoteSelection !== null && quoteSelection.markdown !== liveMarkdown) setQuoteSelection(null); const quoteChoices = quoteSelection?.selectors ?? []; - const cite = (selector: (typeof quoteChoices)[number]) => { + const cite = ({ selector }: (typeof quoteChoices)[number]) => { if (!props.citationSource || !props.onCiteAssistantText) return; setQuoteSelection(null); props.onCiteAssistantText({ @@ -1376,12 +1376,12 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { contentContainerStyle={{ padding: 20 }} > - {quoteChoices.map((selector) => ( + {quoteChoices.map((choice) => ( cite(selector)} + key={choice.selector.start} + label={`Occurrence ${choice.index + 1} of ${choice.count}`} + description={`${choice.selector.prefix}${choice.selector.text}${choice.selector.suffix}`} + onPress={() => cite(choice)} /> ))} diff --git a/apps/mobile/src/lib/assistantCitationSelection.test.ts b/apps/mobile/src/lib/assistantCitationSelection.test.ts index 971739c082eec..a1942741eccb2 100644 --- a/apps/mobile/src/lib/assistantCitationSelection.test.ts +++ b/apps/mobile/src/lib/assistantCitationSelection.test.ts @@ -10,16 +10,14 @@ import { EnvironmentId, ThreadId, MessageId } from "@t3tools/contracts"; it("offers distinct source choices within a block and maps recursive folds without merging occurrences", () => { const paragraph = `${"x".repeat(40)}**quote**${"x".repeat(40)}`; const markdown = `${paragraph}\n\n
Outer\n\n
Inner\n\n${paragraph}\n\n
\n\n
`; - const first = collectMobileAssistantTextSelectors(markdown, "0:0", "quote")[0]; - const second = collectMobileAssistantTextSelectors(markdown, "1/1/0:0", "quote")[0]; - expect(first?.occurrence).toEqual({ index: 0, count: 2 }); - expect(second?.occurrence).toEqual({ index: 1, count: 2 }); + const [first] = collectMobileAssistantTextSelectors(markdown, "0:0", "quote"); + const [second] = collectMobileAssistantTextSelectors(markdown, "1/1/0:0", "quote"); + expect([first?.index, first?.count, second?.index, second?.count]).toEqual([0, 2, 1, 2]); const rendered = `${"x".repeat(40)}quote${"x".repeat(40)} ${"x".repeat(40)}quote${"x".repeat(40)}`; - expect(findAssistantCitationText(rendered, second!)).toEqual({ - start: rendered.lastIndexOf("quote"), - end: rendered.lastIndexOf("quote") + 5, - }); - const markers = [first!, second!].map((selector) => + expect(second?.selector.start).toBe(rendered.lastIndexOf("quote")); + // Identical context on both sides stays ambiguous rather than guessing. + expect(findAssistantCitationText(rendered, second!.selector)).toBeNull(); + const markers = [first!, second!].map(({ selector }) => serializeAssistantCitation({ version: 1, environmentId: EnvironmentId.make("env"), @@ -37,24 +35,24 @@ it("offers distinct source choices within a block and maps recursive folds witho "0:0", "quote", ); - expect(sameBlock[1]?.start).toBe(17); - expect(sameBlock[1]?.prefix).toBe("first quote then "); + expect(sameBlock[1]?.selector.start).toBe(17); + expect(sameBlock[1]?.selector.prefix).toBe("first quote then "); const [leadingSpace] = collectMobileAssistantTextSelectors( "x\n\n
More\n\n` quote`\n\n
", "1/0:0", "quote", ); - expect(leadingSpace?.start).toBe(2); - expect(leadingSpace?.occurrence).toEqual({ index: 0, count: 1 }); + expect(leadingSpace?.selector.start).toBe(2); + expect(leadingSpace?.count).toBe(1); const codeChoices = collectMobileAssistantTextSelectors( "quote\n\n```text\nquote\n```\n\nquote", "0:0", "quote", ); - expect(codeChoices.map((choice) => choice.occurrence)).toEqual([ - { index: 0, count: 3 }, - { index: 1, count: 3 }, - { index: 2, count: 3 }, + expect(codeChoices.map((choice) => [choice.index, choice.count])).toEqual([ + [0, 3], + [1, 3], + [2, 3], ]); for (const { source, path } of [ { source: "![before](image.png)\n\nquote quote\n\n![after](image.png)", path: "0:0" }, @@ -70,7 +68,7 @@ it("offers distinct source choices within a block and maps recursive folds witho ]) { const selectors = collectMobileAssistantTextSelectors(source, path, "quote"); expect(selectors).toHaveLength(2); - for (const [index, selector] of selectors.entries()) { + for (const [index, { selector }] of selectors.entries()) { expect(findAssistantCitationText("quote quote", selector)).toEqual({ start: index * 6, end: index * 6 + 5, @@ -88,13 +86,9 @@ it("rejects unmappable or blank selections instead of inventing a source", () => it("uses the web math representation around a selected passage", () => { for (const formula of ["$x$", "\\(x\\)"]) { - const [selector] = collectMobileAssistantTextSelectors( - `Before ${formula} after`, - "0:0", - "after", - ); - expect(selector?.prefix).toBe("Before \\(x\\) "); - expect(findAssistantCitationText("Before \\(x\\) after", selector!)).toEqual({ + const [choice] = collectMobileAssistantTextSelectors(`Before ${formula} after`, "0:0", "after"); + expect(choice?.selector.prefix).toBe("Before \\(x\\) "); + expect(findAssistantCitationText("Before \\(x\\) after", choice!.selector)).toEqual({ start: 13, end: 18, }); @@ -104,5 +98,5 @@ it("uses the web math representation around a selected passage", () => { "0:0", "after", ); - expect(display?.prefix).toBe("Before \\[ x \\] "); + expect(display?.selector.prefix).toBe("Before \\[ x \\] "); }); diff --git a/apps/mobile/src/lib/assistantCitationSelection.ts b/apps/mobile/src/lib/assistantCitationSelection.ts index 4915f213be08f..7f9fa068b594f 100644 --- a/apps/mobile/src/lib/assistantCitationSelection.ts +++ b/apps/mobile/src/lib/assistantCitationSelection.ts @@ -101,6 +101,6 @@ export function collectMobileAssistantTextSelectors(markdown: string, path: stri const index = matches.indexOf(start); if (index === -1) return []; const selector = createAssistantTextSelector(fullText, start, start + quote.length); - return selector ? [{ ...selector, text, occurrence: { index, count: matches.length } }] : []; + return selector ? [{ selector: { ...selector, text }, index, count: matches.length }] : []; }); } diff --git a/apps/mobile/src/lib/filePreview.test.ts b/apps/mobile/src/lib/filePreview.test.ts index 2abcbdd94b234..43322f8ad148e 100644 --- a/apps/mobile/src/lib/filePreview.test.ts +++ b/apps/mobile/src/lib/filePreview.test.ts @@ -199,15 +199,12 @@ vi.mock("../native/SelectableMarkdownText", () => ({ markdown: string; onLinkPress(href: string): void; renderImage?: MarkdownImageRenderer; - onCiteText?: (text: string) => void; }) => { const embed = props.markdown.match(/!\[([^\]]*)\]\(([^)]+)\)/); return createElement( "div", null, createElement("button", { onClick: () => props.onLinkPress("target.ts") }, props.markdown), - props.onCiteText && - createElement("button", { onClick: () => props.onCiteText?.("quote") }, "Cite quote"), embed && props.renderImage?.({ href: embed[2]!, alt: embed[1]!, title: null }), ); }, @@ -1405,75 +1402,6 @@ describe("inline file previews", () => { }); describe("ThreadFeed previews", () => { - it("drops stale quote choices when the streaming source changes", async () => { - (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - const environmentId = EnvironmentId.make("environment-1"); - const threadId = ThreadId.make("thread-1"); - const messageId = MessageId.make("message-1"); - const timestamp = "2026-10-20T00:00:00.000Z"; - const cited = vi.fn(); - const element = (text: string) => - createElement(ThreadFeed, { - environmentId, - threadId, - detailRef: null, - threadTitle: "quotes", - workspaceRoot: "/repo", - feed: [ - { - type: "message", - id: messageId, - createdAt: timestamp, - message: { - id: messageId, - role: "assistant", - text, - attachments: [], - createdAt: timestamp, - updatedAt: timestamp, - runId: null, - streaming: true, - visibility: "local", - sourceThreadId: threadId, - }, - }, - ], - queuedMessages: [], - dispatchingMessageId: null, - onEditPendingMessage: null, - contentPresentation: { kind: "ready" }, - latestRun: null, - activeWorkStartedAt: null, - listRef: { current: null }, - freeze: { value: false } as Parameters[0]["freeze"], - contentInsetEndAdjustment: { value: 0 } as Parameters< - typeof ThreadFeed - >[0]["contentInsetEndAdjustment"], - anchorMessageId: null, - keyboardOffset: 0, - onCiteAssistantText: cited, - }); - const container = document.createElement("div"); - const root = createRoot(container); - const button = (text: string) => - [...container.querySelectorAll("button")].find((e) => e.textContent === text); - try { - await act(async () => root.render(element("first quote then quote"))); - await act(async () => button("Cite quote")!.click()); - expect(button("Occurrence 2 of 2")).toBeDefined(); - await act(async () => root.render(element("first quote then quote and quote"))); - expect(button("Occurrence 2 of 2")).toBeUndefined(); - expect(cited).not.toHaveBeenCalled(); - await act(async () => button("Cite quote")!.click()); - await act(async () => button("Occurrence 2 of 3")!.click()); - expect(cited).toHaveBeenCalledWith( - expect.objectContaining({ occurrence: { index: 1, count: 3 } }), - ); - } finally { - await act(async () => root.unmount()); - } - }); - it("does not commit an open preview over a different thread", async () => { (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; const environmentId = EnvironmentId.make("environment-1"); diff --git a/apps/mobile/src/native/T3ComposerEditor.native.tsx b/apps/mobile/src/native/T3ComposerEditor.native.tsx index e369e5257d8fc..af52387d408a3 100644 --- a/apps/mobile/src/native/T3ComposerEditor.native.tsx +++ b/apps/mobile/src/native/T3ComposerEditor.native.tsx @@ -200,6 +200,7 @@ export function ComposerEditor({ token.type === "mention" ? token.value : contextRecordFileName(record), ); return { + // Android taps only known token types; a model chip opens like a skill chip. type: token.type === "model" ? "skill" : token.type === "citation" ? "context" : token.type, source: token.source, diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts index 2ab5840df528d..f9727734bf870 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts @@ -1,7 +1,6 @@ import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences"; import { MessageId, - PROVIDER_SEND_TURN_MAX_INPUT_CHARS, type ModelSelection, type NodeId, ProviderSessionId, @@ -445,18 +444,6 @@ export const layer: Layer.Layer< cause: "The persisted steering message or target run is missing.", }); } - const text = projectComposerContextForProvider({ - text: message.text, - records: message.context?.records ?? [], - }); - if (text.length > PROVIDER_SEND_TURN_MAX_INPUT_CHARS) { - return yield* new ProviderTurnControlError({ - threadId: input.threadId, - operation: "steer", - providerTurnId: input.providerTurnId, - cause: `Message exceeds ${PROVIDER_SEND_TURN_MAX_INPUT_CHARS.toLocaleString("en-US")} characters after expanding context and quotes. Shorten it and try again.`, - }); - } yield* loaded.session.value .steerTurn({ threadId: input.threadId, @@ -468,7 +455,10 @@ export const layer: Layer.Layer< : { modelSelection: input.modelSelection }), message: { messageId: message.id, - text, + text: projectComposerContextForProvider({ + text: message.text, + records: message.context?.records ?? [], + }), attachments: message.attachments, createdBy: message.createdBy, creationSource: message.creationSource, diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 3e5721d070c0c..0f6ce6229be25 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -2194,7 +2194,7 @@ it.effect("keeps a held commentary draft before the steer when turn end flushes }), ); -it.effect.each(["auto", "restart", "deferred", "promote-edited"] as const)( +it.effect.each(["auto", "deferred", "promote-edited"] as const)( "rejects expanded steering input before commit: %s", (delivery) => Effect.scoped( @@ -2269,8 +2269,7 @@ it.effect.each(["auto", "restart", "deferred", "promote-edited"] as const)( context, attachments: [], dispatchMode: { type: "start_immediately" }, - deliveryIntent: - delivery === "restart" ? "restart" : delivery === "deferred" ? "steer" : "auto", + deliveryIntent: delivery === "deferred" ? "steer" : "auto", createdBy: "user", creationSource: "mobile", }; diff --git a/apps/web/src/lib/assistantTextSelection.test.ts b/apps/web/src/lib/assistantTextSelection.test.ts index a25972be7700a..d06261cb856aa 100644 --- a/apps/web/src/lib/assistantTextSelection.test.ts +++ b/apps/web/src/lib/assistantTextSelection.test.ts @@ -507,20 +507,3 @@ describe("findAssistantCitationText", () => { }); }); }); - -it("resolves a repeated native quote only while its occurrence count is unchanged", () => { - const repeated = "x".repeat(40) + "quote" + "x".repeat(40); - const text = `${repeated} / ${repeated}`; - const second = text.lastIndexOf("quote"); - const citation = { - ...createAssistantTextSelector(text, second, second + 5)!, - occurrence: { index: 1, count: 2 }, - }; - expect(findAssistantCitationText(text, citation)).toEqual({ start: second, end: second + 5 }); - expect(findAssistantCitationText(`${text} / ${repeated}`, citation)).toBeNull(); - const unique = { - ...createAssistantTextSelector("old quote", 4, 9)!, - occurrence: { index: 0, count: 1 }, - }; - expect(findAssistantCitationText("new quote", unique)).toEqual({ start: 4, end: 9 }); -}); diff --git a/docs/internals/assistant-citations.md b/docs/internals/assistant-citations.md index 7b440875a50c2..c5313488b4a06 100644 --- a/docs/internals/assistant-citations.md +++ b/docs/internals/assistant-citations.md @@ -11,10 +11,13 @@ Source navigation is best effort. [Text selectors](../../apps/web/src/lib/assist refer to rendered text after whitespace normalization, measured in UTF-16 units. They cannot be applied to raw Markdown. The original excerpt keeps its whitespace; normalization is only for locating it. Repeated text needs an unambiguous context -match, even if one occurrence still sits at the saved offsets. Mobile records an -explicit occurrence choice when the native renderer cannot identify its block; -that choice resolves only while the rendered occurrence count and context still -match. Guessing could highlight the wrong claim. +match, even if one occurrence still sits at the saved offsets. Guessing could +highlight the wrong claim. Mobile's native selection reports only text, so when a +passage repeats within its block the user picks the occurrence, and mobile saves +that occurrence's offsets and context like any other selector. + +Released servers and clients reject a citation link with an unknown query key and +send or show it unexpanded. Adding a field to the link needs a new link version. Navigation owns the highlight's lifetime across virtual-row remounts. The source row must be fetched, unfolded, mounted, and measured before quote positioning diff --git a/packages/contracts/src/assistantCitations.ts b/packages/contracts/src/assistantCitations.ts index ee16537fc5b71..96572a4bfa656 100644 --- a/packages/contracts/src/assistantCitations.ts +++ b/packages/contracts/src/assistantCitations.ts @@ -22,15 +22,6 @@ export const AssistantCitation = Schema.Struct({ ), start: NonNegativeInt.check(Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER)), end: NonNegativeInt.check(Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER)), - occurrence: Schema.optional( - Schema.Struct({ - index: NonNegativeInt.check(Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER)), - count: NonNegativeInt.check( - Schema.isGreaterThan(0), - Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER), - ), - }).check(Schema.makeFilter((value) => value.index < value.count)), - ), prefix: Schema.String.check(Schema.isMaxLength(ASSISTANT_CITATION_CONTEXT_LENGTH)), suffix: Schema.String.check(Schema.isMaxLength(ASSISTANT_CITATION_CONTEXT_LENGTH)), }).check( diff --git a/packages/shared/src/assistantCitations.test.ts b/packages/shared/src/assistantCitations.test.ts index a698e482ee4f1..7dbaaf9d8bdeb 100644 --- a/packages/shared/src/assistantCitations.test.ts +++ b/packages/shared/src/assistantCitations.test.ts @@ -95,10 +95,6 @@ describe("assistant citation references", () => { "t3-citation://v1/a/b/c?text=quote&start=5&end=0&prefix=&suffix=", "t3-citation://v1/a/b/c?text=quote&start=0&end=5&prefix=&suffix=&text=other", "t3-citation://v1/a/b/c?text=quote&start=0&end=5&prefix=&suffix=&unknown=value", - "t3-citation://v1/a/b/c?text=quote&start=0&end=5&prefix=&suffix=&occurrence=0", - "t3-citation://v1/a/b/c?text=quote&start=0&end=5&prefix=&suffix=&occurrence=1&occurrences=1", - "t3-citation://v1/a/b/c?text=quote&start=0&end=5&prefix=&suffix=&occurrence=0&occurrences=0", - "t3-citation://v1/a/b/c?text=quote&start=0&end=5&prefix=&suffix=&occurrence=0&occurrences=9007199254740992", "t3-citation://v1/a/b/c?text=quote&start=0&end=5&prefix=&suffix=&comment=one&comment=two", ])("leaves invalid or unsupported references unchanged: %s", (href) => { expect(parseAssistantCitationHref(href)).toBeNull(); @@ -286,15 +282,3 @@ describe("assistant citation references", () => { ); }); }); - -it("retains distinct repeated occurrences through serialization and provider expansion", () => { - const first = { ...citation, occurrence: { index: 0, count: 2 } }; - const second = { ...citation, occurrence: { index: 1, count: 2 } }; - expect(parseAssistantCitationHref(formatAssistantCitationHref(second))).toEqual(second); - const expanded = readProviderContext( - expandAssistantCitationsForProvider( - `${serializeAssistantCitation(first)} ${serializeAssistantCitation(second)}`, - ), - ); - expect(expanded).toHaveLength(2); -}); diff --git a/packages/shared/src/assistantCitations.ts b/packages/shared/src/assistantCitations.ts index d776af320a059..fef486ba6831b 100644 --- a/packages/shared/src/assistantCitations.ts +++ b/packages/shared/src/assistantCitations.ts @@ -51,10 +51,6 @@ export function formatAssistantCitationHref(citation: AssistantCitation): string prefix: citation.prefix, suffix: citation.suffix, }); - if (citation.occurrence !== undefined) { - query.set("occurrence", String(citation.occurrence.index)); - query.set("occurrences", String(citation.occurrence.count)); - } if (citation.comment !== undefined) query.set("comment", citation.comment); return `${CITATION_HREF_PREFIX}${path}?${query}`; } @@ -79,14 +75,8 @@ export function parseAssistantCitationHref(href: string): AssistantCitation | nu } const requiredKeys = ["text", "start", "end", "prefix", "suffix"]; const comment = url.searchParams.get("comment"); - const occurrence = url.searchParams.get("occurrence"); - const occurrences = url.searchParams.get("occurrences"); - if ((occurrence === null) !== (occurrences === null)) return null; - if (occurrence !== null && (!/^\d{1,16}$/.test(occurrence) || !/^\d{1,16}$/.test(occurrences!))) - return null; if ( - url.searchParams.size !== - requiredKeys.length + (comment === null ? 0 : 1) + (occurrence === null ? 0 : 2) || + url.searchParams.size !== requiredKeys.length + (comment === null ? 0 : 1) || requiredKeys.some((key) => url.searchParams.getAll(key).length !== 1) ) { return null; @@ -106,9 +96,6 @@ export function parseAssistantCitationHref(href: string): AssistantCitation | nu prefix: url.searchParams.get("prefix"), suffix: url.searchParams.get("suffix"), ...(comment === null ? {} : { comment }), - ...(occurrence === null - ? {} - : { occurrence: { index: Number(occurrence), count: Number(occurrences) } }), }), ); } catch { @@ -218,7 +205,6 @@ export type AssistantTextSelector = { readonly end: number; readonly prefix: string; readonly suffix: string; - readonly occurrence?: AssistantCitation["occurrence"]; }; function normalizeWhitespace(text: string): string { @@ -285,7 +271,6 @@ export function findAssistantCitationText( : null; let onlyQuote: { start: number; end: number } | null = null; let quoteCount = 0; - let occurrenceMatch: { start: number; end: number } | null = null; for ( let start = normalized.indexOf(quote); @@ -293,18 +278,12 @@ export function findAssistantCitationText( start = normalized.indexOf(quote, start + 1) ) { const end = start + quote.length; - if (selector.occurrence?.index === quoteCount) occurrenceMatch = { start, end }; quoteCount += 1; onlyQuote = { start, end }; if (!matchesContext(start, end)) continue; - if (match !== null && match.start !== start && selector.occurrence === undefined) return null; + if (match !== null && match.start !== start) return null; match = { start, end }; } - if (selector.occurrence !== undefined) { - if (quoteCount !== selector.occurrence.count || occurrenceMatch === null) return null; - if (quoteCount === 1) return occurrenceMatch; - return matchesContext(occurrenceMatch.start, occurrenceMatch.end) ? occurrenceMatch : null; - } return match ?? (quoteCount === 1 ? onlyQuote : null); } From 40b876a873ab5a2319285e447092b8c24c14d810 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 05:18:47 +0000 Subject: [PATCH 15/16] fix(server): limit only quote expansion to the provider input cap The new 120,000-character check measured the full provider projection, including terminal excerpts, review diffs and preview annotations. Web's composer counts only the citation-expanded prompt and main enforces no server limit, so a short prompt with large context passed the composer and then failed after send. Measure expandAssistantCitationsForProvider output instead, at turn start and before a steer commits, matching the web composer and the mobile citation guard. Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/Orchestrator.ts | 12 ++-- .../ProviderTurnStartService.ts | 21 ++++-- .../SteeringCompletion.integration.test.ts | 69 ++++++++++++------- 3 files changed, 65 insertions(+), 37 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index fde35f89bdb53..53d18578f58ef 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -82,7 +82,7 @@ import { } from "@t3tools/contracts"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { modelSelectionsEqual } from "@t3tools/shared/model"; -import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences"; +import { expandAssistantCitationsForProvider } from "@t3tools/shared/assistantCitations"; import { modelSwitchSince } from "./modelSwitch.ts"; import { contextBoundaryOrdinal, isScheduledFreshRun } from "./contextBoundary.ts"; import { isPlaceholderThreadTitle } from "./placeholderThreadTitle.ts"; @@ -5918,15 +5918,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio >, message: Pick, ) { - const text = projectComposerContextForProvider({ - text: message.text, - records: message.context?.records ?? [], - }); - if (text.length > PROVIDER_SEND_TURN_MAX_INPUT_CHARS) { + if ( + expandAssistantCitationsForProvider(message.text).length > PROVIDER_SEND_TURN_MAX_INPUT_CHARS + ) { return yield* new OrchestratorCommandRejectedError({ commandId: command.commandId, commandType: command.type, - cause: `Message exceeds ${PROVIDER_SEND_TURN_MAX_INPUT_CHARS.toLocaleString("en-US")} characters after expanding context and quotes. Shorten it and try again.`, + cause: `Message exceeds ${PROVIDER_SEND_TURN_MAX_INPUT_CHARS.toLocaleString("en-US")} characters after expanding quotes. Shorten it and try again.`, }); } if (isNativeMaintenanceCommand(message)) { diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 2e4c9a96c0696..b029e3824c718 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1,5 +1,6 @@ import { modelSelectionsEqual } from "@t3tools/shared/model"; import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences"; +import { expandAssistantCitationsForProvider } from "@t3tools/shared/assistantCitations"; import { CommandId, PROVIDER_SEND_TURN_MAX_INPUT_CHARS, @@ -602,11 +603,10 @@ export const layer: Layer.Layer< }); }, ); - const userText = projectComposerContextForProvider({ - text: providerMessage.text, - records: providerMessage.context?.records ?? [], - }); - if (userText.length > PROVIDER_SEND_TURN_MAX_INPUT_CHARS) { + if ( + expandAssistantCitationsForProvider(providerMessage.text).length > + PROVIDER_SEND_TURN_MAX_INPUT_CHARS + ) { yield* settleRunBeforeStart({ run, rootNode, @@ -622,7 +622,7 @@ export const layer: Layer.Layer< title: "Message is too long", failure: makeProviderFailure({ class: "validation_error", - message: `Message exceeds ${PROVIDER_SEND_TURN_MAX_INPUT_CHARS.toLocaleString("en-US")} characters after expanding context and quotes. Shorten it and try again.`, + message: `Message exceeds ${PROVIDER_SEND_TURN_MAX_INPUT_CHARS.toLocaleString("en-US")} characters after expanding quotes. Shorten it and try again.`, }), }, }); @@ -663,7 +663,10 @@ export const layer: Layer.Layer< : yield* Effect.result( providerAuth.tryHandlePromptCommand({ instanceId: authInstanceId, - text: userText, + text: projectComposerContextForProvider({ + text: providerMessage.text, + records: providerMessage.context?.records ?? [], + }), hasAttachments: false, }), ); @@ -917,6 +920,10 @@ export const layer: Layer.Layer< }); let effectiveHandoffs = handoffs; let resumeFellBack = false; + const userText = projectComposerContextForProvider({ + text: providerMessage.text, + records: providerMessage.context?.records ?? [], + }); // Native goal commands go verbatim; handoff history waits a turn. const goalDriver = session.driver === "codex" || diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 0f6ce6229be25..062a86f6f7b2a 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -2,6 +2,7 @@ import { assert, it } from "@effect/vitest"; import * as TestClock from "effect/testing/TestClock"; import { ChatAttachmentId, + COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS, ComposerContextId, CommandId, EnvironmentId, @@ -20,7 +21,10 @@ import { type ModelSelection, type OrchestrationV2DomainEvent, } from "@t3tools/contracts"; -import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations"; +import { + expandAssistantCitationsForProvider, + serializeAssistantCitation, +} from "@t3tools/shared/assistantCitations"; import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; @@ -2213,36 +2217,40 @@ it.effect.each(["auto", "deferred", "promote-edited"] as const)( environmentId: EnvironmentId.make("env"), threadId, messageId: MessageId.make("assistant"), - text: "\u0001".repeat(5_000), + text: "\u0001".repeat(8_000), start: 0, - end: 5_000, + end: 8_000, prefix: "", suffix: "", }); - const text = `${"x".repeat(80_000)}${citation}[log](t3-context://v1/terminal/log)`; + const text = `${"x".repeat(80_000)}${citation}`; + // Context excerpts are not part of the limit, matching the web composer's check. + const largeContextText = + "Read [one](t3-context://v1/terminal/one) and [two](t3-context://v1/terminal/two)"; const context = { version: 1 as const, - records: [ - { - version: 1 as const, - kind: "terminal" as const, - contextId: ComposerContextId.make("log"), - label: "log", - terminalId: "terminal", - terminalLabel: "Terminal", - lineStart: 1, - lineEnd: 1, - text: "y".repeat(20_000), - }, - ], + records: (["one", "two"] as const).map((id) => ({ + version: 1 as const, + kind: "terminal" as const, + contextId: ComposerContextId.make(id), + label: id, + terminalId: "terminal", + terminalLabel: "Terminal", + lineStart: 1, + lineEnd: 1, + text: "y".repeat(COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS), + })), }; assert.isBelow(text.length, PROVIDER_SEND_TURN_MAX_INPUT_CHARS); - assert.isBelow( - projectComposerContextForProvider({ text, records: [] }).length, + assert.isAbove( + expandAssistantCitationsForProvider(text).length, PROVIDER_SEND_TURN_MAX_INPUT_CHARS, ); assert.isAbove( - projectComposerContextForProvider({ text, records: context.records }).length, + projectComposerContextForProvider({ + text: largeContextText, + records: context.records, + }).length, PROVIDER_SEND_TURN_MAX_INPUT_CHARS, ); if (delivery === "deferred") { @@ -2266,7 +2274,6 @@ it.effect.each(["auto", "deferred", "promote-edited"] as const)( threadId, messageId: MessageId.make("oversized"), text, - context, attachments: [], dispatchMode: { type: "start_immediately" }, deliveryIntent: delivery === "deferred" ? "steer" : "auto", @@ -2290,7 +2297,6 @@ it.effect.each(["auto", "deferred", "promote-edited"] as const)( threadId, runId: queued.id, text, - context, }); command = { type: "queued-message.promote-to-steer", @@ -2306,7 +2312,7 @@ it.effect.each(["auto", "deferred", "promote-edited"] as const)( assert.instanceOf(error, Orchestrator.OrchestratorCommandRejectedError); assert.equal( userFacingDispatchErrorMessage(error), - "Message exceeds 120,000 characters after expanding context and quotes. Shorten it and try again.", + "Message exceeds 120,000 characters after expanding quotes. Shorten it and try again.", ); assert.deepEqual(yield* outbox.listByCommandId(commandId), []); assert.deepEqual(yield* sink.readByCommandId({ commandId }).pipe(Stream.runCollect), []); @@ -2316,6 +2322,23 @@ it.effect.each(["auto", "deferred", "promote-edited"] as const)( assert.deepEqual(steered, []); assert.deepEqual(interrupted, []); assert.lengthOf(started, 1); + if (delivery === "auto") { + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("large-context-steer"), + threadId, + messageId: MessageId.make("large-context"), + text: largeContextText, + context, + attachments: [], + dispatchMode: { type: "start_immediately" }, + deliveryIntent: "auto", + createdBy: "user", + creationSource: "mobile", + }); + yield* worker.drain(); + assert.lengthOf(steered, 1); + } }).pipe(Effect.provide(layer)); }), ), From 2cdf11cc229d947d162127481ab35d328d628d1c Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:47:06 -0800 Subject: [PATCH 16/16] fix(mobile): translate quote citation copy after main added i18n Co-Authored-By: Claude Opus 5.5 --- .../src/components/AssistantCitationSheet.tsx | 26 ++++++++++++------- apps/mobile/src/components/ComposerEditor.tsx | 6 +++-- .../features/threads/ThreadDetailScreen.tsx | 6 +++-- .../src/features/threads/ThreadFeed.tsx | 22 +++++++++++----- apps/mobile/src/i18n/translations/de.json | 24 +++++++++++++++-- apps/mobile/src/i18n/translations/en.json | 24 +++++++++++++++-- apps/mobile/src/i18n/translations/es.json | 24 +++++++++++++++-- apps/mobile/src/i18n/translations/fr.json | 24 +++++++++++++++-- apps/mobile/src/i18n/translations/ja.json | 24 +++++++++++++++-- apps/mobile/src/i18n/translations/ko.json | 24 +++++++++++++++-- apps/mobile/src/i18n/translations/pt-BR.json | 24 +++++++++++++++-- apps/mobile/src/i18n/translations/ru.json | 24 +++++++++++++++-- apps/mobile/src/i18n/translations/sv.json | 24 +++++++++++++++-- apps/mobile/src/i18n/translations/zh.json | 24 +++++++++++++++-- .../src/native/EnrichedMarkdownText.tsx | 2 +- .../src/native/SelectableMarkdownText.tsx | 8 +++--- 16 files changed, 266 insertions(+), 44 deletions(-) diff --git a/apps/mobile/src/components/AssistantCitationSheet.tsx b/apps/mobile/src/components/AssistantCitationSheet.tsx index 62185cc3b9f89..3af99f8224bea 100644 --- a/apps/mobile/src/components/AssistantCitationSheet.tsx +++ b/apps/mobile/src/components/AssistantCitationSheet.tsx @@ -1,6 +1,7 @@ import { ASSISTANT_CITATION_MAX_COMMENT_LENGTH, type AssistantCitation } from "@t3tools/contracts"; import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { useState } from "react"; +import { T, useGT } from "gt-react-native"; import { Platform, ScrollView, TextInput, View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useOpenLinkedThread } from "../features/threads/useOpenLinkedThread"; @@ -34,6 +35,7 @@ export function AssistantCitationSheet(props: { readonly onCommentChange?: (comment: string) => void; readonly canChangeComment?: (comment: string) => boolean; }) { + const gt = useGT(); const openLinkedThread = useOpenLinkedThread(); const insets = useSafeAreaInsets(); const citation = props.citation; @@ -48,7 +50,11 @@ export function AssistantCitationSheet(props: { props.onClose(); }; return ( - +
{props.onCommentChange ? ( - + {commentTooLong ? ( - This comment makes the message too long to send. Shorten it to save and close. + + This comment makes the message too long to send. Shorten it to save and close. + ) : null} ) : citation.comment ? ( - + {citation.comment} @@ -95,7 +103,7 @@ export function AssistantCitationSheet(props: { { if (commentTooLong) return; close(); @@ -105,13 +113,13 @@ export function AssistantCitationSheet(props: { /> copyTextWithHaptic(citation.text)} /> {props.onRemove ? ( diff --git a/apps/mobile/src/components/ComposerEditor.tsx b/apps/mobile/src/components/ComposerEditor.tsx index f61fe652747fa..8d3805234696b 100644 --- a/apps/mobile/src/components/ComposerEditor.tsx +++ b/apps/mobile/src/components/ComposerEditor.tsx @@ -223,8 +223,10 @@ export function ComposerEditor({ props.value.slice(0, selected.start) + next + props.value.slice(selected.end); if (!assistantCitationDraftWithinLimit(text)) { Dialog.alert( - "Could not update quote", - "This comment would make the message too long to send. Shorten the comment or draft.", + gt("Could not update quote"), + gt( + "This comment would make the message too long to send. Shorten the comment or draft.", + ), ); return; } diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 324c95c8c9b05..cf8adb7ac3581 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -1378,8 +1378,10 @@ function ThreadDetailBody( const text = target.text.slice(0, target.start) + value + target.text.slice(target.end); if (!assistantCitationDraftWithinLimit(text)) { Dialog.alert( - "Could not add quote", - "This quote would make the message too long to send. Shorten the draft or select less text.", + gt("Could not add quote"), + gt( + "This quote would make the message too long to send. Shorten the draft or select less text.", + ), ); return; } diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index aa9f8209516fd..fd78a906e51ae 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -1323,6 +1323,7 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { readonly renderImage: MarkdownImageRenderer; readonly skills?: ReadonlyArray | undefined; }) { + const gt = useGT(); const liveMarkdown = useLiveThreadLinkLabels(props.markdown, props.environmentId); const [quoteSelection, setQuoteSelection] = useState<{ markdown: string; @@ -1364,16 +1365,18 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { 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.`, + gt("Quote is too long"), + gt("Select up to {max} characters to cite.", { + max: ASSISTANT_CITATION_MAX_TEXT_LENGTH.toLocaleString(), + }), ); return; } const selectors = collectMobileAssistantTextSelectors(liveMarkdown, path, text); if (selectors.length === 0) { Dialog.alert( - "Unable to locate quote", - "Select more surrounding text to cite its source accurately.", + gt("Unable to locate quote"), + gt("Select more surrounding text to cite its source accurately."), ); return; } @@ -1390,16 +1393,21 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { models={models} /> {quoteChoices.length > 0 && props.onCiteAssistantText ? ( - setQuoteSelection(null)}> + setQuoteSelection(null)}> - + {quoteChoices.map((choice) => ( cite(choice)} /> diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index c9d43d96b3eb8..2b338c39b0627 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -1237,6 +1237,14 @@ "6df89a3609273ddf": "Zur Startseite", "ca91bde751481f6e": "Route nicht gefunden", "fa7ad42d8043440e": "Zur Startseite", + "67e94b9fb8ee633b": "Quote", + "90b2fa60b4cd0c15": "Kommentar", + "60f8d5f18d14777e": "Comment on quote", + "b9185b31f8d03aaa": "Add an optional comment…", + "c59ddf9a3543013f": "Go to message", + "58d429970e815c66": "Copy quote", + "200acb0e96f98096": "Aus Entwurf entfernen", + "cf063d4a1ffd5c6e": "This comment makes the message too long to send. Shorten it to save and close.", "9d1893839b7b4881": "Dev", "ae2263d9d6e71fd8": "Vorschau", "525f2b92a20a9707": "Beta", @@ -1262,7 +1270,6 @@ "fb28c2c6667398c7": "gemergt", "8c5799964db00630": "Seite", "bf14b3522e13a2c3": "URL", - "90b2fa60b4cd0c15": "Kommentar", "669b9d73d58ea020": "Auswahl", "6345ddd2e293ddd5": "Angeforderte Änderungen", "74e6003622876943": "Element", @@ -1282,7 +1289,6 @@ "eca94e6557931eae": "Versuch es erneut, wenn eine Verbindung besteht.", "be3fcbc1324d5f38": "{term, select, mr {Merge Request öffnen} cr {Änderungsanfrage öffnen} other {Pull Request öffnen}}", "19f953915a468edd": "Anhang öffnen", - "200acb0e96f98096": "Aus Entwurf entfernen", "13559139cab80bd6": [ "Zeilen ", { @@ -1306,6 +1312,8 @@ "8fce5e0d1adf9939": "Ein Teil des Kontexts ist nicht verfügbar", "c80fb12238256d0d": "Diese Referenzen sind als nicht verfügbar markiert.", "d3fdcfa142649a36": "Versuch erneut zu kopieren.", + "71369ce364d8ed08": "Could not update quote", + "5f794b9980f91c26": "This comment would make the message too long to send. Shorten the comment or draft.", "b9cf50b7e7b1bc54": "Kontext wird kopiert…", "bda161176d64ec51": "Modell wählen", "54a5cee284438dd6": "Modell- und Reasoning-Einstellungen", @@ -1465,6 +1473,7 @@ "9f1b29c948772f0f": "Link öffnen", "258d16c1554b734c": "Link kopieren", "d7dc565616d13a5c": "Link teilen", + "51244cd196696a00": "Cite", "6cdca065884f77f2": "Kopieren", "0165ef55eb6c8a99": "Als Markdown kopieren", "7c1923203049d602": "Code kopieren", @@ -1482,6 +1491,8 @@ "v": "v" } ], + "ede9a884a11b7972": "Assistant quote", + "f563a55ee229090e": "Open quote", "7b30d976b8508ddf": "Nachricht senden", "40c503999bce960e": "Neue Aufgabe", "2225f6bda46f4cc6": "Tastatur ausblenden", @@ -4328,6 +4339,8 @@ "cebceafe7ddc7d5d": "Feedback zur Genehmigung", "0830bd81f19bb753": "Sende Feedback zur Genehmigung ohne Anhänge oder zusätzlichen Kontext.", "d15878f290283f53": "Nachricht konnte nicht bearbeitet werden", + "dd426ccfb3da6826": "Could not add quote", + "ba2b33c3082441c4": "This quote would make the message too long to send. Shorten the draft or select less text.", "188db618b91bf237": "Die Unterhaltung konnte nicht angezeigt werden", "86ba20bb0ac0e5d0": "Sende Feedback, um diese Anfrage abzulehnen", "880aa376639f0b04": "Sende eine Nachricht, um abzulehnen und den Agenten umzulenken", @@ -4349,6 +4362,13 @@ "c0e2a25e01e3236f": "{name} herunterladen", "71e7894d52a4dc83": "Vorlage verwenden", "0d2983c2dbaac338": "Vorlage {name} verwenden", + "9c588b380359c9ac": "Quote is too long", + "4867b752740e9a9b": "Select up to {max} characters to cite.", + "ea59a48fb9657a5c": "Unable to locate quote", + "9680ed7cf7c79355": "Select more surrounding text to cite its source accurately.", + "623b6e7bc72d2688": "Choose quote source", + "ae98d7a6f90f56f2": "This text appears more than once. Choose the passage you selected.", + "a047920204bc0ec7": "Occurrence {index} of {count}", "cd03eb1b84271c02": "Agent", "0226edfcba8db105": "{label}: {summary}", "5d2859f3b56ad6cf": "Doppeltippen, um die Nachricht auszublenden.", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 7a89a1cf37c22..ff5335d575fff 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -1237,6 +1237,14 @@ "6df89a3609273ddf": "Return home", "ca91bde751481f6e": "Route not found", "fa7ad42d8043440e": "Return home", + "67e94b9fb8ee633b": "Quote", + "90b2fa60b4cd0c15": "Comment", + "60f8d5f18d14777e": "Comment on quote", + "b9185b31f8d03aaa": "Add an optional comment…", + "c59ddf9a3543013f": "Go to message", + "58d429970e815c66": "Copy quote", + "200acb0e96f98096": "Remove from draft", + "cf063d4a1ffd5c6e": "This comment makes the message too long to send. Shorten it to save and close.", "9d1893839b7b4881": "Dev", "ae2263d9d6e71fd8": "Preview", "525f2b92a20a9707": "Beta", @@ -1262,7 +1270,6 @@ "fb28c2c6667398c7": "merged", "8c5799964db00630": "Page", "bf14b3522e13a2c3": "URL", - "90b2fa60b4cd0c15": "Comment", "669b9d73d58ea020": "Selection", "6345ddd2e293ddd5": "Requested changes", "74e6003622876943": "Element", @@ -1282,7 +1289,6 @@ "eca94e6557931eae": "Try again when connected.", "be3fcbc1324d5f38": "Open {term, select, mr {merge request} cr {change request} other {pull request}}", "19f953915a468edd": "Open attachment", - "200acb0e96f98096": "Remove from draft", "13559139cab80bd6": [ "Lines ", { @@ -1306,6 +1312,8 @@ "8fce5e0d1adf9939": "Some context is unavailable", "c80fb12238256d0d": "Those references are marked unavailable.", "d3fdcfa142649a36": "Try copying again.", + "71369ce364d8ed08": "Could not update quote", + "5f794b9980f91c26": "This comment would make the message too long to send. Shorten the comment or draft.", "b9cf50b7e7b1bc54": "Copying context…", "bda161176d64ec51": "Choose model", "54a5cee284438dd6": "Model and reasoning settings", @@ -1465,6 +1473,7 @@ "9f1b29c948772f0f": "Open link", "258d16c1554b734c": "Copy link", "d7dc565616d13a5c": "Share link", + "51244cd196696a00": "Cite", "6cdca065884f77f2": "Copy", "0165ef55eb6c8a99": "Copy as Markdown", "7c1923203049d602": "Copy code", @@ -1482,6 +1491,8 @@ "v": "v" } ], + "ede9a884a11b7972": "Assistant quote", + "f563a55ee229090e": "Open quote", "7b30d976b8508ddf": "Send Message", "40c503999bce960e": "New task", "2225f6bda46f4cc6": "Dismiss keyboard", @@ -4329,6 +4340,8 @@ "cebceafe7ddc7d5d": "Approval feedback", "0830bd81f19bb753": "Send approval feedback without attachments or added context.", "d15878f290283f53": "Could not edit message", + "dd426ccfb3da6826": "Could not add quote", + "ba2b33c3082441c4": "This quote would make the message too long to send. Shorten the draft or select less text.", "188db618b91bf237": "The conversation couldn't be displayed", "86ba20bb0ac0e5d0": "Send feedback to decline this request", "880aa376639f0b04": "Send a message to decline and redirect the agent", @@ -4350,6 +4363,13 @@ "c0e2a25e01e3236f": "Download {name}", "71e7894d52a4dc83": "Use template", "0d2983c2dbaac338": "Use {name} template", + "9c588b380359c9ac": "Quote is too long", + "4867b752740e9a9b": "Select up to {max} characters to cite.", + "ea59a48fb9657a5c": "Unable to locate quote", + "9680ed7cf7c79355": "Select more surrounding text to cite its source accurately.", + "623b6e7bc72d2688": "Choose quote source", + "ae98d7a6f90f56f2": "This text appears more than once. Choose the passage you selected.", + "a047920204bc0ec7": "Occurrence {index} of {count}", "cd03eb1b84271c02": "Agent", "0226edfcba8db105": "{label}: {summary}", "5d2859f3b56ad6cf": "Double tap to hide the message.", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 288dbfc7da2cf..ae3331c2db59f 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -1237,6 +1237,14 @@ "6df89a3609273ddf": "Volver al inicio", "ca91bde751481f6e": "Ruta no encontrada", "fa7ad42d8043440e": "Volver al inicio", + "67e94b9fb8ee633b": "Quote", + "90b2fa60b4cd0c15": "Comentario", + "60f8d5f18d14777e": "Comment on quote", + "b9185b31f8d03aaa": "Add an optional comment…", + "c59ddf9a3543013f": "Go to message", + "58d429970e815c66": "Copy quote", + "200acb0e96f98096": "Quitar del borrador", + "cf063d4a1ffd5c6e": "This comment makes the message too long to send. Shorten it to save and close.", "9d1893839b7b4881": "Dev", "ae2263d9d6e71fd8": "Vista previa", "525f2b92a20a9707": "Beta", @@ -1262,7 +1270,6 @@ "fb28c2c6667398c7": "fusionada", "8c5799964db00630": "Página", "bf14b3522e13a2c3": "URL", - "90b2fa60b4cd0c15": "Comentario", "669b9d73d58ea020": "Selección", "6345ddd2e293ddd5": "Cambios solicitados", "74e6003622876943": "Elemento", @@ -1282,7 +1289,6 @@ "eca94e6557931eae": "Inténtalo de nuevo cuando haya conexión.", "be3fcbc1324d5f38": "Abrir la {term, select, mr {merge request} cr {solicitud de cambios} other {pull request}}", "19f953915a468edd": "Abrir adjunto", - "200acb0e96f98096": "Quitar del borrador", "13559139cab80bd6": [ "Líneas ", { @@ -1306,6 +1312,8 @@ "8fce5e0d1adf9939": "Parte del contexto no está disponible", "c80fb12238256d0d": "Esas referencias están marcadas como no disponibles.", "d3fdcfa142649a36": "Prueba a copiar de nuevo.", + "71369ce364d8ed08": "Could not update quote", + "5f794b9980f91c26": "This comment would make the message too long to send. Shorten the comment or draft.", "b9cf50b7e7b1bc54": "Copiando contexto…", "bda161176d64ec51": "Elegir modelo", "54a5cee284438dd6": "Ajustes del modelo y del razonamiento", @@ -1465,6 +1473,7 @@ "9f1b29c948772f0f": "Abrir enlace", "258d16c1554b734c": "Copiar enlace", "d7dc565616d13a5c": "Compartir enlace", + "51244cd196696a00": "Cite", "6cdca065884f77f2": "Copiar", "0165ef55eb6c8a99": "Copiar como Markdown", "7c1923203049d602": "Copiar código", @@ -1482,6 +1491,8 @@ "v": "v" } ], + "ede9a884a11b7972": "Assistant quote", + "f563a55ee229090e": "Open quote", "7b30d976b8508ddf": "Enviar mensaje", "40c503999bce960e": "Nueva tarea", "2225f6bda46f4cc6": "Ocultar teclado", @@ -4321,6 +4332,8 @@ "cebceafe7ddc7d5d": "Comentarios de la aprobación", "0830bd81f19bb753": "Envía los comentarios de aprobación sin adjuntos ni contexto añadido.", "d15878f290283f53": "No se pudo editar el mensaje", + "dd426ccfb3da6826": "Could not add quote", + "ba2b33c3082441c4": "This quote would make the message too long to send. Shorten the draft or select less text.", "188db618b91bf237": "No se pudo mostrar la conversación", "86ba20bb0ac0e5d0": "Envía comentarios para rechazar esta solicitud", "880aa376639f0b04": "Envía un mensaje para rechazar y redirigir al agente", @@ -4342,6 +4355,13 @@ "c0e2a25e01e3236f": "Descargar {name}", "71e7894d52a4dc83": "Usar plantilla", "0d2983c2dbaac338": "Usar la plantilla {name}", + "9c588b380359c9ac": "Quote is too long", + "4867b752740e9a9b": "Select up to {max} characters to cite.", + "ea59a48fb9657a5c": "Unable to locate quote", + "9680ed7cf7c79355": "Select more surrounding text to cite its source accurately.", + "623b6e7bc72d2688": "Choose quote source", + "ae98d7a6f90f56f2": "This text appears more than once. Choose the passage you selected.", + "a047920204bc0ec7": "Occurrence {index} of {count}", "cd03eb1b84271c02": "Agente", "0226edfcba8db105": "{label}: {summary}", "5d2859f3b56ad6cf": "Toca dos veces para ocultar el mensaje.", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 28ec2284fca74..4d4feaa6ec8c5 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -1237,6 +1237,14 @@ "6df89a3609273ddf": "Retour à l’accueil", "ca91bde751481f6e": "Route introuvable", "fa7ad42d8043440e": "Retour à l’accueil", + "67e94b9fb8ee633b": "Quote", + "90b2fa60b4cd0c15": "Commentaire", + "60f8d5f18d14777e": "Comment on quote", + "b9185b31f8d03aaa": "Add an optional comment…", + "c59ddf9a3543013f": "Go to message", + "58d429970e815c66": "Copy quote", + "200acb0e96f98096": "Retirer du brouillon", + "cf063d4a1ffd5c6e": "This comment makes the message too long to send. Shorten it to save and close.", "9d1893839b7b4881": "Dev", "ae2263d9d6e71fd8": "Preview", "525f2b92a20a9707": "Bêta", @@ -1262,7 +1270,6 @@ "fb28c2c6667398c7": "fusionnée", "8c5799964db00630": "Page", "bf14b3522e13a2c3": "URL", - "90b2fa60b4cd0c15": "Commentaire", "669b9d73d58ea020": "Sélection", "6345ddd2e293ddd5": "Modifications demandées", "74e6003622876943": "Élément", @@ -1282,7 +1289,6 @@ "eca94e6557931eae": "Réessayez une fois connecté.", "be3fcbc1324d5f38": "Ouvrir la {term, select, mr {merge request} cr {demande de modification} other {pull request}}", "19f953915a468edd": "Ouvrir la pièce jointe", - "200acb0e96f98096": "Retirer du brouillon", "13559139cab80bd6": [ "Lignes ", { @@ -1306,6 +1312,8 @@ "8fce5e0d1adf9939": "Une partie du contexte est indisponible", "c80fb12238256d0d": "Ces références sont marquées comme indisponibles.", "d3fdcfa142649a36": "Essayez de copier à nouveau.", + "71369ce364d8ed08": "Could not update quote", + "5f794b9980f91c26": "This comment would make the message too long to send. Shorten the comment or draft.", "b9cf50b7e7b1bc54": "Copie du contexte…", "bda161176d64ec51": "Choisir un modèle", "54a5cee284438dd6": "Paramètres du modèle et du raisonnement", @@ -1465,6 +1473,7 @@ "9f1b29c948772f0f": "Ouvrir le lien", "258d16c1554b734c": "Copier le lien", "d7dc565616d13a5c": "Partager le lien", + "51244cd196696a00": "Cite", "6cdca065884f77f2": "Copier", "0165ef55eb6c8a99": "Copier en Markdown", "7c1923203049d602": "Copier le code", @@ -1482,6 +1491,8 @@ "v": "v" } ], + "ede9a884a11b7972": "Assistant quote", + "f563a55ee229090e": "Open quote", "7b30d976b8508ddf": "Envoyer le message", "40c503999bce960e": "Nouvelle tâche", "2225f6bda46f4cc6": "Masquer le clavier", @@ -4322,6 +4333,8 @@ "cebceafe7ddc7d5d": "Retour sur l’approbation", "0830bd81f19bb753": "Envoyez votre réponse à l’approbation sans pièces jointes ni contexte ajouté.", "d15878f290283f53": "Impossible de modifier le message", + "dd426ccfb3da6826": "Could not add quote", + "ba2b33c3082441c4": "This quote would make the message too long to send. Shorten the draft or select less text.", "188db618b91bf237": "La conversation n’a pas pu être affichée", "86ba20bb0ac0e5d0": "Envoyez un commentaire pour refuser cette demande", "880aa376639f0b04": "Envoyez un message pour refuser et réorienter l’agent", @@ -4343,6 +4356,13 @@ "c0e2a25e01e3236f": "Télécharger {name}", "71e7894d52a4dc83": "Utiliser le modèle", "0d2983c2dbaac338": "Utiliser le modèle {name}", + "9c588b380359c9ac": "Quote is too long", + "4867b752740e9a9b": "Select up to {max} characters to cite.", + "ea59a48fb9657a5c": "Unable to locate quote", + "9680ed7cf7c79355": "Select more surrounding text to cite its source accurately.", + "623b6e7bc72d2688": "Choose quote source", + "ae98d7a6f90f56f2": "This text appears more than once. Choose the passage you selected.", + "a047920204bc0ec7": "Occurrence {index} of {count}", "cd03eb1b84271c02": "Agent", "0226edfcba8db105": "{label} : {summary}", "5d2859f3b56ad6cf": "Touchez deux fois pour masquer le message.", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index f6741fdb8b775..d27246ad9a062 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -1237,6 +1237,14 @@ "6df89a3609273ddf": "ホームに戻る", "ca91bde751481f6e": "ルートが見つかりません", "fa7ad42d8043440e": "ホームに戻る", + "67e94b9fb8ee633b": "Quote", + "90b2fa60b4cd0c15": "コメント", + "60f8d5f18d14777e": "Comment on quote", + "b9185b31f8d03aaa": "Add an optional comment…", + "c59ddf9a3543013f": "Go to message", + "58d429970e815c66": "Copy quote", + "200acb0e96f98096": "下書きから削除", + "cf063d4a1ffd5c6e": "This comment makes the message too long to send. Shorten it to save and close.", "9d1893839b7b4881": "Dev", "ae2263d9d6e71fd8": "プレビュー", "525f2b92a20a9707": "ベータ", @@ -1262,7 +1270,6 @@ "fb28c2c6667398c7": "マージ済み", "8c5799964db00630": "ページ", "bf14b3522e13a2c3": "URL", - "90b2fa60b4cd0c15": "コメント", "669b9d73d58ea020": "選択範囲", "6345ddd2e293ddd5": "変更をリクエスト済み", "74e6003622876943": "要素", @@ -1282,7 +1289,6 @@ "eca94e6557931eae": "接続されたらもう一度お試しください。", "be3fcbc1324d5f38": "{term, select, mr {マージリクエストを開く} cr {変更リクエストを開く} other {プルリクエストを開く}}", "19f953915a468edd": "添付ファイルを開く", - "200acb0e96f98096": "下書きから削除", "13559139cab80bd6": [ { "i": 1, @@ -1306,6 +1312,8 @@ "8fce5e0d1adf9939": "一部のコンテキストを利用できません", "c80fb12238256d0d": "それらの参照は利用不可として表示されます。", "d3fdcfa142649a36": "もう一度コピーしてください。", + "71369ce364d8ed08": "Could not update quote", + "5f794b9980f91c26": "This comment would make the message too long to send. Shorten the comment or draft.", "b9cf50b7e7b1bc54": "コンテキストをコピーしています…", "bda161176d64ec51": "モデルを選択", "54a5cee284438dd6": "モデルと推論の設定", @@ -1465,6 +1473,7 @@ "9f1b29c948772f0f": "リンクを開く", "258d16c1554b734c": "リンクをコピー", "d7dc565616d13a5c": "リンクを共有", + "51244cd196696a00": "Cite", "6cdca065884f77f2": "コピー", "0165ef55eb6c8a99": "Markdown としてコピー", "7c1923203049d602": "コードをコピー", @@ -1482,6 +1491,8 @@ "v": "v" } ], + "ede9a884a11b7972": "Assistant quote", + "f563a55ee229090e": "Open quote", "7b30d976b8508ddf": "メッセージを送信", "40c503999bce960e": "新しいタスク", "2225f6bda46f4cc6": "キーボードを閉じる", @@ -4303,6 +4314,8 @@ "cebceafe7ddc7d5d": "承認へのフィードバック", "0830bd81f19bb753": "承認のフィードバックは、添付ファイルや追加のコンテキストなしで送信してください。", "d15878f290283f53": "メッセージを編集できませんでした", + "dd426ccfb3da6826": "Could not add quote", + "ba2b33c3082441c4": "This quote would make the message too long to send. Shorten the draft or select less text.", "188db618b91bf237": "会話を表示できませんでした", "86ba20bb0ac0e5d0": "このリクエストを拒否するにはフィードバックを送信してください", "880aa376639f0b04": "メッセージを送信して拒否し、エージェントに別の指示を出します", @@ -4324,6 +4337,13 @@ "c0e2a25e01e3236f": "{name} をダウンロード", "71e7894d52a4dc83": "テンプレートを使用", "0d2983c2dbaac338": "{name} テンプレートを使用", + "9c588b380359c9ac": "Quote is too long", + "4867b752740e9a9b": "Select up to {max} characters to cite.", + "ea59a48fb9657a5c": "Unable to locate quote", + "9680ed7cf7c79355": "Select more surrounding text to cite its source accurately.", + "623b6e7bc72d2688": "Choose quote source", + "ae98d7a6f90f56f2": "This text appears more than once. Choose the passage you selected.", + "a047920204bc0ec7": "Occurrence {index} of {count}", "cd03eb1b84271c02": "エージェント", "0226edfcba8db105": "{label}: {summary}", "5d2859f3b56ad6cf": "ダブルタップでメッセージを非表示にします。", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index b1ef20ba0f347..1a90d119c5edf 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -1237,6 +1237,14 @@ "6df89a3609273ddf": "홈으로 돌아가기", "ca91bde751481f6e": "경로를 찾을 수 없음", "fa7ad42d8043440e": "홈으로 돌아가기", + "67e94b9fb8ee633b": "Quote", + "90b2fa60b4cd0c15": "댓글", + "60f8d5f18d14777e": "Comment on quote", + "b9185b31f8d03aaa": "Add an optional comment…", + "c59ddf9a3543013f": "Go to message", + "58d429970e815c66": "Copy quote", + "200acb0e96f98096": "초안에서 제거", + "cf063d4a1ffd5c6e": "This comment makes the message too long to send. Shorten it to save and close.", "9d1893839b7b4881": "Dev", "ae2263d9d6e71fd8": "Preview", "525f2b92a20a9707": "Beta", @@ -1262,7 +1270,6 @@ "fb28c2c6667398c7": "병합됨", "8c5799964db00630": "페이지", "bf14b3522e13a2c3": "URL", - "90b2fa60b4cd0c15": "댓글", "669b9d73d58ea020": "선택 영역", "6345ddd2e293ddd5": "수정 요청됨", "74e6003622876943": "요소", @@ -1282,7 +1289,6 @@ "eca94e6557931eae": "연결되면 다시 시도하세요.", "be3fcbc1324d5f38": "{term, select, mr {병합 요청} cr {변경 요청} other {풀 리퀘스트}} 열기", "19f953915a468edd": "첨부 파일 열기", - "200acb0e96f98096": "초안에서 제거", "13559139cab80bd6": [ { "i": 1, @@ -1306,6 +1312,8 @@ "8fce5e0d1adf9939": "일부 컨텍스트를 사용할 수 없습니다", "c80fb12238256d0d": "해당 참조는 사용할 수 없음으로 표시됩니다.", "d3fdcfa142649a36": "다시 복사해 보세요.", + "71369ce364d8ed08": "Could not update quote", + "5f794b9980f91c26": "This comment would make the message too long to send. Shorten the comment or draft.", "b9cf50b7e7b1bc54": "컨텍스트 복사 중…", "bda161176d64ec51": "모델 선택", "54a5cee284438dd6": "모델 및 추론 설정", @@ -1465,6 +1473,7 @@ "9f1b29c948772f0f": "링크 열기", "258d16c1554b734c": "링크 복사", "d7dc565616d13a5c": "링크 공유", + "51244cd196696a00": "Cite", "6cdca065884f77f2": "복사", "0165ef55eb6c8a99": "Markdown으로 복사", "7c1923203049d602": "코드 복사", @@ -1482,6 +1491,8 @@ "v": "v" } ], + "ede9a884a11b7972": "Assistant quote", + "f563a55ee229090e": "Open quote", "7b30d976b8508ddf": "메시지 보내기", "40c503999bce960e": "새 작업", "2225f6bda46f4cc6": "키보드 닫기", @@ -4308,6 +4319,8 @@ "cebceafe7ddc7d5d": "승인 피드백", "0830bd81f19bb753": "첨부 파일이나 추가 컨텍스트 없이 승인 피드백을 보내세요.", "d15878f290283f53": "메시지를 편집할 수 없습니다", + "dd426ccfb3da6826": "Could not add quote", + "ba2b33c3082441c4": "This quote would make the message too long to send. Shorten the draft or select less text.", "188db618b91bf237": "대화를 표시할 수 없습니다", "86ba20bb0ac0e5d0": "이 요청을 거부하려면 피드백을 보내세요", "880aa376639f0b04": "거부하고 에이전트의 방향을 바꾸려면 메시지를 보내세요", @@ -4329,6 +4342,13 @@ "c0e2a25e01e3236f": "{name} 다운로드", "71e7894d52a4dc83": "템플릿 사용", "0d2983c2dbaac338": "{name} 템플릿 사용", + "9c588b380359c9ac": "Quote is too long", + "4867b752740e9a9b": "Select up to {max} characters to cite.", + "ea59a48fb9657a5c": "Unable to locate quote", + "9680ed7cf7c79355": "Select more surrounding text to cite its source accurately.", + "623b6e7bc72d2688": "Choose quote source", + "ae98d7a6f90f56f2": "This text appears more than once. Choose the passage you selected.", + "a047920204bc0ec7": "Occurrence {index} of {count}", "cd03eb1b84271c02": "에이전트", "0226edfcba8db105": "{label}: {summary}", "5d2859f3b56ad6cf": "두 번 탭하여 메시지를 숨깁니다.", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index b40494fca3885..a37d5647292ee 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -1237,6 +1237,14 @@ "6df89a3609273ddf": "Voltar ao início", "ca91bde751481f6e": "Rota não encontrada", "fa7ad42d8043440e": "Voltar ao início", + "67e94b9fb8ee633b": "Quote", + "90b2fa60b4cd0c15": "Comentário", + "60f8d5f18d14777e": "Comment on quote", + "b9185b31f8d03aaa": "Add an optional comment…", + "c59ddf9a3543013f": "Go to message", + "58d429970e815c66": "Copy quote", + "200acb0e96f98096": "Remover do rascunho", + "cf063d4a1ffd5c6e": "This comment makes the message too long to send. Shorten it to save and close.", "9d1893839b7b4881": "Dev", "ae2263d9d6e71fd8": "Preview", "525f2b92a20a9707": "Beta", @@ -1262,7 +1270,6 @@ "fb28c2c6667398c7": "mesclado", "8c5799964db00630": "Página", "bf14b3522e13a2c3": "URL", - "90b2fa60b4cd0c15": "Comentário", "669b9d73d58ea020": "Seleção", "6345ddd2e293ddd5": "Alterações solicitadas", "74e6003622876943": "Elemento", @@ -1282,7 +1289,6 @@ "eca94e6557931eae": "Tente novamente quando estiver conectado.", "be3fcbc1324d5f38": "Abrir {term, select, mr {o merge request} cr {a solicitação de alteração} other {o pull request}}", "19f953915a468edd": "Abrir anexo", - "200acb0e96f98096": "Remover do rascunho", "13559139cab80bd6": [ "Linhas ", { @@ -1306,6 +1312,8 @@ "8fce5e0d1adf9939": "Parte do contexto está indisponível", "c80fb12238256d0d": "Essas referências estão marcadas como indisponíveis.", "d3fdcfa142649a36": "Tente copiar novamente.", + "71369ce364d8ed08": "Could not update quote", + "5f794b9980f91c26": "This comment would make the message too long to send. Shorten the comment or draft.", "b9cf50b7e7b1bc54": "Copiando contexto…", "bda161176d64ec51": "Escolher modelo", "54a5cee284438dd6": "Configurações de modelo e raciocínio", @@ -1465,6 +1473,7 @@ "9f1b29c948772f0f": "Abrir link", "258d16c1554b734c": "Copiar link", "d7dc565616d13a5c": "Compartilhar link", + "51244cd196696a00": "Cite", "6cdca065884f77f2": "Copiar", "0165ef55eb6c8a99": "Copiar como Markdown", "7c1923203049d602": "Copiar código", @@ -1482,6 +1491,8 @@ "v": "v" } ], + "ede9a884a11b7972": "Assistant quote", + "f563a55ee229090e": "Open quote", "7b30d976b8508ddf": "Enviar mensagem", "40c503999bce960e": "Nova tarefa", "2225f6bda46f4cc6": "Ocultar teclado", @@ -4322,6 +4333,8 @@ "cebceafe7ddc7d5d": "Feedback da aprovação", "0830bd81f19bb753": "Envie o feedback da aprovação sem anexos nem contexto adicional.", "d15878f290283f53": "Não foi possível editar a mensagem", + "dd426ccfb3da6826": "Could not add quote", + "ba2b33c3082441c4": "This quote would make the message too long to send. Shorten the draft or select less text.", "188db618b91bf237": "Não foi possível exibir a conversa", "86ba20bb0ac0e5d0": "Envie um feedback para recusar esta solicitação", "880aa376639f0b04": "Envie uma mensagem para recusar e redirecionar o agente", @@ -4343,6 +4356,13 @@ "c0e2a25e01e3236f": "Baixar {name}", "71e7894d52a4dc83": "Usar modelo", "0d2983c2dbaac338": "Usar o template {name}", + "9c588b380359c9ac": "Quote is too long", + "4867b752740e9a9b": "Select up to {max} characters to cite.", + "ea59a48fb9657a5c": "Unable to locate quote", + "9680ed7cf7c79355": "Select more surrounding text to cite its source accurately.", + "623b6e7bc72d2688": "Choose quote source", + "ae98d7a6f90f56f2": "This text appears more than once. Choose the passage you selected.", + "a047920204bc0ec7": "Occurrence {index} of {count}", "cd03eb1b84271c02": "Agente", "0226edfcba8db105": "{label}: {summary}", "5d2859f3b56ad6cf": "Toque duas vezes para ocultar a mensagem.", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index cadf07e57eda9..0e2b0affd43d3 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -1237,6 +1237,14 @@ "6df89a3609273ddf": "На главную", "ca91bde751481f6e": "Маршрут не найден", "fa7ad42d8043440e": "На главную", + "67e94b9fb8ee633b": "Quote", + "90b2fa60b4cd0c15": "Комментарий", + "60f8d5f18d14777e": "Comment on quote", + "b9185b31f8d03aaa": "Add an optional comment…", + "c59ddf9a3543013f": "Go to message", + "58d429970e815c66": "Copy quote", + "200acb0e96f98096": "Убрать из черновика", + "cf063d4a1ffd5c6e": "This comment makes the message too long to send. Shorten it to save and close.", "9d1893839b7b4881": "Dev", "ae2263d9d6e71fd8": "Предварительная версия", "525f2b92a20a9707": "Бета", @@ -1262,7 +1270,6 @@ "fb28c2c6667398c7": "слит", "8c5799964db00630": "Страница", "bf14b3522e13a2c3": "URL", - "90b2fa60b4cd0c15": "Комментарий", "669b9d73d58ea020": "Выделение", "6345ddd2e293ddd5": "Запрошены изменения", "74e6003622876943": "Элемент", @@ -1282,7 +1289,6 @@ "eca94e6557931eae": "Попробуйте ещё раз после подключения.", "be3fcbc1324d5f38": "{term, select, mr {Открыть мерж-реквест} cr {Открыть запрос на изменение} other {Открыть пул-реквест}}", "19f953915a468edd": "Открыть вложение", - "200acb0e96f98096": "Убрать из черновика", "13559139cab80bd6": [ "Строки ", { @@ -1306,6 +1312,8 @@ "8fce5e0d1adf9939": "Часть контекста недоступна", "c80fb12238256d0d": "Эти ссылки помечены как недоступные.", "d3fdcfa142649a36": "Попробуйте скопировать снова.", + "71369ce364d8ed08": "Could not update quote", + "5f794b9980f91c26": "This comment would make the message too long to send. Shorten the comment or draft.", "b9cf50b7e7b1bc54": "Копирование контекста…", "bda161176d64ec51": "Выберите модель", "54a5cee284438dd6": "Настройки модели и рассуждений", @@ -1465,6 +1473,7 @@ "9f1b29c948772f0f": "Открыть ссылку", "258d16c1554b734c": "Копировать ссылку", "d7dc565616d13a5c": "Поделиться ссылкой", + "51244cd196696a00": "Cite", "6cdca065884f77f2": "Копировать", "0165ef55eb6c8a99": "Копировать как Markdown", "7c1923203049d602": "Копировать код", @@ -1482,6 +1491,8 @@ "v": "v" } ], + "ede9a884a11b7972": "Assistant quote", + "f563a55ee229090e": "Open quote", "7b30d976b8508ddf": "Отправить сообщение", "40c503999bce960e": "Новая задача", "2225f6bda46f4cc6": "Скрыть клавиатуру", @@ -4400,6 +4411,8 @@ "cebceafe7ddc7d5d": "Отзыв на подтверждение", "0830bd81f19bb753": "Отправьте отзыв на подтверждение без вложений и добавленного контекста.", "d15878f290283f53": "Не удалось изменить сообщение", + "dd426ccfb3da6826": "Could not add quote", + "ba2b33c3082441c4": "This quote would make the message too long to send. Shorten the draft or select less text.", "188db618b91bf237": "Не удалось отобразить беседу", "86ba20bb0ac0e5d0": "Отправьте отзыв, чтобы отклонить этот запрос", "880aa376639f0b04": "Отправьте сообщение, чтобы отклонить запрос и перенаправить агента", @@ -4421,6 +4434,13 @@ "c0e2a25e01e3236f": "Скачать {name}", "71e7894d52a4dc83": "Использовать шаблон", "0d2983c2dbaac338": "Использовать шаблон {name}", + "9c588b380359c9ac": "Quote is too long", + "4867b752740e9a9b": "Select up to {max} characters to cite.", + "ea59a48fb9657a5c": "Unable to locate quote", + "9680ed7cf7c79355": "Select more surrounding text to cite its source accurately.", + "623b6e7bc72d2688": "Choose quote source", + "ae98d7a6f90f56f2": "This text appears more than once. Choose the passage you selected.", + "a047920204bc0ec7": "Occurrence {index} of {count}", "cd03eb1b84271c02": "Агент", "0226edfcba8db105": "{label}: {summary}", "5d2859f3b56ad6cf": "Дважды нажмите, чтобы скрыть сообщение.", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 3a0273aef36fd..8df0a79302ef8 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -1237,6 +1237,14 @@ "6df89a3609273ddf": "Gå till start", "ca91bde751481f6e": "Sidan hittades inte", "fa7ad42d8043440e": "Gå till start", + "67e94b9fb8ee633b": "Quote", + "90b2fa60b4cd0c15": "Kommentar", + "60f8d5f18d14777e": "Comment on quote", + "b9185b31f8d03aaa": "Add an optional comment…", + "c59ddf9a3543013f": "Go to message", + "58d429970e815c66": "Copy quote", + "200acb0e96f98096": "Ta bort från utkastet", + "cf063d4a1ffd5c6e": "This comment makes the message too long to send. Shorten it to save and close.", "9d1893839b7b4881": "Dev", "ae2263d9d6e71fd8": "Förhandsversion", "525f2b92a20a9707": "Beta", @@ -1262,7 +1270,6 @@ "fb28c2c6667398c7": "mergad", "8c5799964db00630": "Sida", "bf14b3522e13a2c3": "URL", - "90b2fa60b4cd0c15": "Kommentar", "669b9d73d58ea020": "Markering", "6345ddd2e293ddd5": "Begärda ändringar", "74e6003622876943": "Element", @@ -1282,7 +1289,6 @@ "eca94e6557931eae": "Försök igen när du är ansluten.", "be3fcbc1324d5f38": "Öppna {term, select, mr {merge request} cr {ändringsbegäran} other {pull request}}", "19f953915a468edd": "Öppna bilaga", - "200acb0e96f98096": "Ta bort från utkastet", "13559139cab80bd6": [ "Rad ", { @@ -1306,6 +1312,8 @@ "8fce5e0d1adf9939": "Viss kontext är inte tillgänglig", "c80fb12238256d0d": "De referenserna är markerade som inte tillgängliga.", "d3fdcfa142649a36": "Försök kopiera igen.", + "71369ce364d8ed08": "Could not update quote", + "5f794b9980f91c26": "This comment would make the message too long to send. Shorten the comment or draft.", "b9cf50b7e7b1bc54": "Kopierar kontext…", "bda161176d64ec51": "Välj modell", "54a5cee284438dd6": "Inställningar för modell och resonerande", @@ -1465,6 +1473,7 @@ "9f1b29c948772f0f": "Öppna länk", "258d16c1554b734c": "Kopiera länk", "d7dc565616d13a5c": "Dela länk", + "51244cd196696a00": "Cite", "6cdca065884f77f2": "Kopiera", "0165ef55eb6c8a99": "Kopiera som Markdown", "7c1923203049d602": "Kopiera kod", @@ -1482,6 +1491,8 @@ "v": "v" } ], + "ede9a884a11b7972": "Assistant quote", + "f563a55ee229090e": "Open quote", "7b30d976b8508ddf": "Skicka meddelande", "40c503999bce960e": "Ny uppgift", "2225f6bda46f4cc6": "Stäng tangentbordet", @@ -4328,6 +4339,8 @@ "cebceafe7ddc7d5d": "Feedback på godkännande", "0830bd81f19bb753": "Skicka feedback om godkännandet utan bilagor eller tillagd kontext.", "d15878f290283f53": "Kunde inte redigera meddelandet", + "dd426ccfb3da6826": "Could not add quote", + "ba2b33c3082441c4": "This quote would make the message too long to send. Shorten the draft or select less text.", "188db618b91bf237": "Konversationen kunde inte visas", "86ba20bb0ac0e5d0": "Skicka feedback för att avböja den här begäran", "880aa376639f0b04": "Skicka ett meddelande för att avböja och styra om agenten", @@ -4349,6 +4362,13 @@ "c0e2a25e01e3236f": "Ladda ned {name}", "71e7894d52a4dc83": "Använd mall", "0d2983c2dbaac338": "Använd mallen {name}", + "9c588b380359c9ac": "Quote is too long", + "4867b752740e9a9b": "Select up to {max} characters to cite.", + "ea59a48fb9657a5c": "Unable to locate quote", + "9680ed7cf7c79355": "Select more surrounding text to cite its source accurately.", + "623b6e7bc72d2688": "Choose quote source", + "ae98d7a6f90f56f2": "This text appears more than once. Choose the passage you selected.", + "a047920204bc0ec7": "Occurrence {index} of {count}", "cd03eb1b84271c02": "Agent", "0226edfcba8db105": "{label}: {summary}", "5d2859f3b56ad6cf": "Dubbeltryck för att dölja meddelandet.", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index f1c394c60c606..4cea621febc50 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -1237,6 +1237,14 @@ "6df89a3609273ddf": "返回主页", "ca91bde751481f6e": "未找到路由", "fa7ad42d8043440e": "返回主页", + "67e94b9fb8ee633b": "Quote", + "90b2fa60b4cd0c15": "评论", + "60f8d5f18d14777e": "Comment on quote", + "b9185b31f8d03aaa": "Add an optional comment…", + "c59ddf9a3543013f": "Go to message", + "58d429970e815c66": "Copy quote", + "200acb0e96f98096": "从草稿中移除", + "cf063d4a1ffd5c6e": "This comment makes the message too long to send. Shorten it to save and close.", "9d1893839b7b4881": "Dev", "ae2263d9d6e71fd8": "预览版", "525f2b92a20a9707": "测试版", @@ -1262,7 +1270,6 @@ "fb28c2c6667398c7": "已合并", "8c5799964db00630": "页面", "bf14b3522e13a2c3": "URL", - "90b2fa60b4cd0c15": "评论", "669b9d73d58ea020": "选区", "6345ddd2e293ddd5": "已请求更改", "74e6003622876943": "元素", @@ -1282,7 +1289,6 @@ "eca94e6557931eae": "连接后请重试。", "be3fcbc1324d5f38": "打开 {term, select, mr {MR} cr {change request} other {PR}}", "19f953915a468edd": "打开附件", - "200acb0e96f98096": "从草稿中移除", "13559139cab80bd6": [ "第 ", { @@ -1307,6 +1313,8 @@ "8fce5e0d1adf9939": "部分上下文不可用", "c80fb12238256d0d": "这些引用已标记为不可用。", "d3fdcfa142649a36": "请尝试重新复制。", + "71369ce364d8ed08": "Could not update quote", + "5f794b9980f91c26": "This comment would make the message too long to send. Shorten the comment or draft.", "b9cf50b7e7b1bc54": "正在复制上下文…", "bda161176d64ec51": "选择模型", "54a5cee284438dd6": "模型和推理设置", @@ -1466,6 +1474,7 @@ "9f1b29c948772f0f": "打开链接", "258d16c1554b734c": "复制链接", "d7dc565616d13a5c": "分享链接", + "51244cd196696a00": "Cite", "6cdca065884f77f2": "复制", "0165ef55eb6c8a99": "复制为 Markdown", "7c1923203049d602": "复制代码", @@ -1483,6 +1492,8 @@ "v": "v" } ], + "ede9a884a11b7972": "Assistant quote", + "f563a55ee229090e": "Open quote", "7b30d976b8508ddf": "发送消息", "40c503999bce960e": "新建任务", "2225f6bda46f4cc6": "收起键盘", @@ -4311,6 +4322,8 @@ "cebceafe7ddc7d5d": "批准反馈", "0830bd81f19bb753": "发送审批反馈时请不要带附件或额外上下文。", "d15878f290283f53": "无法编辑消息", + "dd426ccfb3da6826": "Could not add quote", + "ba2b33c3082441c4": "This quote would make the message too long to send. Shorten the draft or select less text.", "188db618b91bf237": "无法显示对话", "86ba20bb0ac0e5d0": "发送反馈以拒绝这个请求", "880aa376639f0b04": "发送消息以拒绝,并给智能体新的指示", @@ -4332,6 +4345,13 @@ "c0e2a25e01e3236f": "下载 {name}", "71e7894d52a4dc83": "使用模板", "0d2983c2dbaac338": "使用 {name} 模板", + "9c588b380359c9ac": "Quote is too long", + "4867b752740e9a9b": "Select up to {max} characters to cite.", + "ea59a48fb9657a5c": "Unable to locate quote", + "9680ed7cf7c79355": "Select more surrounding text to cite its source accurately.", + "623b6e7bc72d2688": "Choose quote source", + "ae98d7a6f90f56f2": "This text appears more than once. Choose the passage you selected.", + "a047920204bc0ec7": "Occurrence {index} of {count}", "cd03eb1b84271c02": "智能体", "0226edfcba8db105": "{label}:{summary}", "5d2859f3b56ad6cf": "轻点两下以隐藏消息。", diff --git a/apps/mobile/src/native/EnrichedMarkdownText.tsx b/apps/mobile/src/native/EnrichedMarkdownText.tsx index 827ad3f3ade61..60992377199ef 100644 --- a/apps/mobile/src/native/EnrichedMarkdownText.tsx +++ b/apps/mobile/src/native/EnrichedMarkdownText.tsx @@ -451,7 +451,7 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) { props.onCiteText ? [ { - text: "Cite", + text: gt("Cite", { $context: "verb, quote selected text" }), icon: "quote.bubble", onPress: ({ text }) => props.onCiteText?.(text), }, diff --git a/apps/mobile/src/native/SelectableMarkdownText.tsx b/apps/mobile/src/native/SelectableMarkdownText.tsx index d05e91304bf94..6f8f00d5c2dfd 100644 --- a/apps/mobile/src/native/SelectableMarkdownText.tsx +++ b/apps/mobile/src/native/SelectableMarkdownText.tsx @@ -1,5 +1,6 @@ import { Platform } from "react-native"; import { useState } from "react"; +import { useGT } from "gt-react-native"; import type { AssistantCitation } from "@t3tools/contracts"; import { parseAssistantCitationHref } from "@t3tools/shared/assistantCitations"; import { AssistantCitationSheet } from "../components/AssistantCitationSheet"; @@ -23,6 +24,7 @@ export type { export function SelectableMarkdownText(props: SelectableMarkdownTextProps) { const [citation, setCitation] = useState(null); + const gt = useGT(); const hasCitations = props.markdown.includes("t3-citation:"); const theme = useUniwindTheme(); const selectionColor = themeColorWithAlpha(theme["--color-focus"], 0.32); @@ -50,10 +52,10 @@ export function SelectableMarkdownText(props: SelectableMarkdownTextProps) { ? (href) => parseAssistantCitationHref(href) ? { - title: "Assistant quote", + title: gt("Assistant quote"), actions: [ - { id: "open-quote", title: "Open quote" }, - { id: "copy-quote", title: "Copy quote" }, + { id: "open-quote", title: gt("Open quote") }, + { id: "copy-quote", title: gt("Copy quote") }, ], } : props.fileContextMenu?.(href)