The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import * as Dialog from "./ui/Dialog"; |
| 3 | import { ComposerContextId } from "@t3tools/contracts"; |
| 4 | import { useAtomValue } from "@effect/atom-react"; |
| 5 | import { AsyncResult } from "effect/reactivity"; |
| 6 | import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; |
| 7 | import { T, useGT } from "gt-react-native"; |
| 8 | import { useEffect, useState } from "react"; |
| 9 | import type { EnvironmentId } from "@t3tools/contracts"; |
| 10 | import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard"; |
| 11 | import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences"; |
| 12 | import { |
| 13 | collectAssistantCitations, |
| 14 | serializeAssistantCitation, |
| 15 | withAssistantCitationComment, |
| 16 | } from "@t3tools/shared/assistantCitations"; |
| 17 | import { AssistantCitationSheet } from "./AssistantCitationSheet"; |
| 18 | import { ComposerEditor as NativeComposerEditor } from "../native/T3ComposerEditor"; |
| 19 | import type { ComposerEditorProps as NativeComposerEditorProps } from "../native/T3ComposerEditor"; |
| 20 | import { |
| 21 | appendComposerDraftAttachments, |
| 22 | composerContextImportsAtom, |
| 23 | createComposerDraftContextHistory, |
| 24 | getComposerDraftAfterSelection, |
| 25 | getComposerDraftSnapshot, |
| 26 | insertComposerDraftContext, |
| 27 | insertComposerDraftText, |
| 28 | rememberComposerDraftSelection, |
| 29 | setComposerDraftContext, |
| 30 | setComposerContextImporting, |
| 31 | useComposerDraft, |
| 32 | useComposerDraftResetGeneration, |
| 33 | } from "../state/use-composer-drafts"; |
| 34 | import { importComposerContextClipboard } from "../lib/composerContextClipboard"; |
| 35 | import { startComposerDraftOperation } from "../state/composerDraftOperations"; |
| 36 | import { appAtomRegistry } from "../state/atom-registry"; |
| 37 | import { enrichedModelDetails, enrichedModelReference } from "../lib/enrichedLinkPresentation"; |
| 38 | import { useModelMentions } from "../state/model-mentions"; |
| 39 | import { mobilePreferencesAtom } from "../state/preferences"; |
| 40 | import { useOpenThreadLink } from "../features/threads/useOpenThreadLink"; |
| 41 | import { useLinkedEnvironments } from "../state/peerLinks"; |
| 42 | import { ComposerContextSheet } from "./ComposerContextSheet"; |
| 43 | import { AppText as Text } from "./ui/AppText"; |
| 44 | import { |
| 45 | assistantCitationDraftWithinLimit, |
| 46 | composerDocumentAttachment, |
| 47 | composerMentionPath, |
| 48 | type ComposerDocumentAttachment, |
| 49 | } from "../lib/composerContext"; |
| 50 | import { m } from "../i18n/messages"; |
| 51 | |
| 52 | export type ComposerEditorProps = NativeComposerEditorProps & { |
| 53 | readonly draftKey?: string | null; |
| 54 | readonly hidden?: boolean; |
| 55 | readonly environmentId?: EnvironmentId; |
| 56 | readonly onOpenMention?: (path: string) => void; |
| 57 | readonly onOpenAttachment?: (attachment: ComposerDocumentAttachment) => void; |
| 58 | readonly chipsInert?: boolean; |
| 59 | readonly onInertChipPress?: () => void; |
| 60 | }; |
| 61 | |
| 62 | export function ComposerEditor({ |
| 63 | draftKey, |
| 64 | hidden, |
| 65 | environmentId, |
| 66 | onOpenMention, |
| 67 | onOpenAttachment, |
| 68 | chipsInert, |
| 69 | onInertChipPress, |
| 70 | ...props |
| 71 | }: ComposerEditorProps) { |
| 72 | const gt = useGT(); |
| 73 | const draft = useComposerDraft(draftKey ?? null); |
| 74 | const readResetGeneration = useComposerDraftResetGeneration(draftKey ?? null); |
| 75 | const preferencesResult = useAtomValue(mobilePreferencesAtom); |
| 76 | const preferredEnterBehavior = AsyncResult.isSuccess(preferencesResult) |
| 77 | ? preferencesResult.value.composerEnterBehavior |
| 78 | : undefined; |
| 79 | const contextHistory = createComposerDraftContextHistory(); |
| 80 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- releases the attachment file leases held for native text undo when the history is replaced or unmounts |
| 81 | useEffect(() => () => contextHistory.dispose(), [contextHistory]); |
| 82 | const changeText = (text: string) => { |
| 83 | const restored = contextHistory.restore( |
| 84 | text, |
| 85 | draftKey ? getComposerDraftSnapshot(draftKey) : draft, |
| 86 | ); |
| 87 | props.onChangeText(text); |
| 88 | if (draftKey) { |
| 89 | setComposerDraftContext(draftKey, restored.context); |
| 90 | appendComposerDraftAttachments(draftKey, restored.attachments, { restore: true }); |
| 91 | } |
| 92 | }; |
| 93 | const [selected, setSelected] = useState<{ source: string; start: number; end: number } | null>( |
| 94 | null, |
| 95 | ); |
| 96 | const linkedEnvironments = useLinkedEnvironments(environmentId ?? null); |
| 97 | const models = useModelMentions(environmentId ?? draft.project?.environmentId, props.value); |
| 98 | const contextImports = useAtomValue(composerContextImportsAtom); |
| 99 | const importing = draftKey ? contextImports[draftKey] === true : false; |
| 100 | const pasteContext = async ( |
| 101 | clipboard: Parameters<NonNullable<NativeComposerEditorProps["onPasteContext"]>>[0], |
| 102 | ) => { |
| 103 | if ( |
| 104 | !draftKey || |
| 105 | appAtomRegistry.get(composerContextImportsAtom)[draftKey] || |
| 106 | props.readOnly || |
| 107 | props.editable === false |
| 108 | ) |
| 109 | return; |
| 110 | const insertion = { text: clipboard.value, ...clipboard.selection }; |
| 111 | const operation = startComposerDraftOperation(draftKey); |
| 112 | const { signal } = operation; |
| 113 | setComposerContextImporting(draftKey, true); |
| 114 | const settled = await settlePromise(async () => { |
| 115 | const retained = getComposerDraftAfterSelection(draftKey, insertion); |
| 116 | const result = await importComposerContextClipboard( |
| 117 | clipboard, |
| 118 | retained.attachments.length, |
| 119 | signal, |
| 120 | retained.context?.records.length ?? 0, |
| 121 | environmentId, |
| 122 | linkedEnvironments, |
| 123 | ); |
| 124 | if (signal.aborted) return; |
| 125 | if (!result) { |
| 126 | insertComposerDraftText(draftKey, clipboard.text, insertion); |
| 127 | return; |
| 128 | } |
| 129 | if (!insertComposerDraftContext(draftKey, result, insertion)) { |
| 130 | Dialog.alert( |
| 131 | gt("Could not paste context"), |
| 132 | gt("Remove some attachments or context items from the draft, then paste again."), |
| 133 | ); |
| 134 | return; |
| 135 | } |
| 136 | const warnings: string[] = []; |
| 137 | if (result.failures.length > 0) |
| 138 | warnings.push( |
| 139 | gt( |
| 140 | "Some attachments could not be copied. Reconnect to the source environment and copy them again.", |
| 141 | ), |
| 142 | ); |
| 143 | if (result.skippedThreads.length > 0) |
| 144 | warnings.push( |
| 145 | gt( |
| 146 | "{count, plural, one {{titles} is on another machine.} other {{titles} are on another machine.}}", |
| 147 | { |
| 148 | count: result.skippedThreads.length, |
| 149 | titles: result.skippedThreads.map((title) => `"${title}"`).join(", "), |
| 150 | }, |
| 151 | ), |
| 152 | ); |
| 153 | if (warnings.length > 0) |
| 154 | Dialog.alert( |
| 155 | gt("Some context is unavailable"), |
| 156 | [...warnings, gt("Those references are marked unavailable.")].join("\n\n"), |
| 157 | ); |
| 158 | }); |
| 159 | operation.finish(); |
| 160 | setComposerContextImporting(draftKey, false); |
| 161 | if (AsyncResult.isFailure(settled) && !signal.aborted) { |
| 162 | const error = squashAtomCommandFailure(settled); |
| 163 | Dialog.alert( |
| 164 | gt("Could not paste context"), |
| 165 | error instanceof Error |
| 166 | ? (errorDisplayMessage(error, m) ?? error.message) |
| 167 | : gt("Try copying again."), |
| 168 | ); |
| 169 | } |
| 170 | }; |
| 171 | const clipboardFragment = |
| 172 | environmentId && draft.context |
| 173 | ? encodeComposerContextFragment({ |
| 174 | version: 1, |
| 175 | source: { environmentId }, |
| 176 | records: draft.context.records.map((record) => { |
| 177 | if (!("attachmentId" in record)) return record; |
| 178 | const attachment = draft.attachments.find((entry) => entry.id === record.attachmentId); |
| 179 | return { |
| 180 | ...record, |
| 181 | attachmentId: |
| 182 | attachment?.uploadEnvironmentId === environmentId |
| 183 | ? (attachment.uploadedAttachmentId ?? record.attachmentId) |
| 184 | : record.attachmentId, |
| 185 | }; |
| 186 | }), |
| 187 | }) |
| 188 | : ""; |
| 189 | const openThreadLink = useOpenThreadLink(environmentId ?? null); |
| 190 | const selectedReference = selected |
| 191 | ? collectComposerContextReferences(selected.source)[0] |
| 192 | : undefined; |
| 193 | const selectedCitation = selected |
| 194 | ? collectAssistantCitations(selected.source)[0]?.citation |
| 195 | : undefined; |
| 196 | const selectedSkillName = selected?.source.match(/^\p{Sc}(.+)$/u)?.[1]; |
| 197 | const selectedSkill = selectedSkillName |
| 198 | ? props.skills?.find((skill) => skill.name === selectedSkillName) |
| 199 | : undefined; |
| 200 | const record = draft.context?.records.find( |
| 201 | (entry) => entry.contextId === selectedReference?.contextId, |
| 202 | ); |
| 203 | const removeSelected = |
| 204 | props.readOnly || props.editable === false |
| 205 | ? undefined |
| 206 | : () => { |
| 207 | if (!selected) return; |
| 208 | if (props.value.slice(selected.start, selected.end) === selected.source) { |
| 209 | changeText(props.value.slice(0, selected.start) + props.value.slice(selected.end)); |
| 210 | props.onSelectionChange?.({ start: selected.start, end: selected.start }); |
| 211 | } |
| 212 | setSelected(null); |
| 213 | }; |
| 214 | const commentSelectedCitation = |
| 215 | props.readOnly || props.editable === false || !selected || !selectedCitation |
| 216 | ? undefined |
| 217 | : (comment: string) => { |
| 218 | if (props.value.slice(selected.start, selected.end) !== selected.source) return; |
| 219 | const next = serializeAssistantCitation( |
| 220 | withAssistantCitationComment(selectedCitation, comment), |
| 221 | ); |
| 222 | const text = |
| 223 | props.value.slice(0, selected.start) + next + props.value.slice(selected.end); |
| 224 | if (!assistantCitationDraftWithinLimit(text)) { |
| 225 | Dialog.alert( |
| 226 | gt("Could not update quote"), |
| 227 | gt( |
| 228 | "This comment would make the message too long to send. Shorten the comment or draft.", |
| 229 | ), |
| 230 | ); |
| 231 | return; |
| 232 | } |
| 233 | const cursor = selected.start + next.length; |
| 234 | if (draftKey) |
| 235 | rememberComposerDraftSelection(draftKey, text, { start: cursor, end: cursor }); |
| 236 | changeText(text); |
| 237 | }; |
| 238 | return ( |
| 239 | <> |
| 240 | {/* Reset revision history with the recreated iOS view without aborting context imports. */} |
| 241 | <NativeComposerEditor |
| 242 | key={hidden ? "hidden" : "visible"} |
| 243 | {...props} |
| 244 | models={models} |
| 245 | enterBehavior={props.enterBehavior ?? preferredEnterBehavior} |
| 246 | onChangeText={changeText} |
| 247 | readResetGeneration={readResetGeneration} |
| 248 | readOnly={props.readOnly || importing} |
| 249 | onSubmit={importing ? undefined : props.onSubmit} |
| 250 | clipboardFragment={clipboardFragment ?? undefined} |
| 251 | onPasteContext={(clipboard) => void pasteContext(clipboard)} |
| 252 | context={draft.context} |
| 253 | onContextPress={(selection) => { |
| 254 | if (chipsInert) { |
| 255 | onInertChipPress?.(); |
| 256 | return; |
| 257 | } |
| 258 | const path = composerMentionPath(selection.source, draft.context); |
| 259 | if (path && onOpenMention) { |
| 260 | onOpenMention(path); |
| 261 | return; |
| 262 | } |
| 263 | const model = enrichedModelReference(selection.source, models); |
| 264 | if (model) { |
| 265 | Dialog.alert(model.label, enrichedModelDetails(model)); |
| 266 | return; |
| 267 | } |
| 268 | const document = composerDocumentAttachment(selection.source, draft.context); |
| 269 | if (document && onOpenAttachment) { |
| 270 | onOpenAttachment(document); |
| 271 | return; |
| 272 | } |
| 273 | setSelected(selection); |
| 274 | }} |
| 275 | onSelectionChange={(selection) => { |
| 276 | if (draftKey) |
| 277 | rememberComposerDraftSelection( |
| 278 | draftKey, |
| 279 | getComposerDraftSnapshot(draftKey).text, |
| 280 | selection, |
| 281 | ); |
| 282 | props.onSelectionChange?.(selection); |
| 283 | }} |
| 284 | /> |
| 285 | {importing ? ( |
| 286 | <Text className="py-2 text-xs text-foreground-muted"> |
| 287 | <T>Copying context…</T> |
| 288 | </Text> |
| 289 | ) : null} |
| 290 | {selectedCitation ? ( |
| 291 | <AssistantCitationSheet |
| 292 | citation={selectedCitation} |
| 293 | onClose={() => setSelected(null)} |
| 294 | onRemove={removeSelected} |
| 295 | onCommentChange={commentSelectedCitation} |
| 296 | canChangeComment={ |
| 297 | selected && commentSelectedCitation |
| 298 | ? (comment) => |
| 299 | assistantCitationDraftWithinLimit( |
| 300 | props.value.slice(0, selected.start) + |
| 301 | serializeAssistantCitation( |
| 302 | withAssistantCitationComment(selectedCitation, comment), |
| 303 | ) + |
| 304 | props.value.slice(selected.end), |
| 305 | ) |
| 306 | : undefined |
| 307 | } |
| 308 | /> |
| 309 | ) : null} |
| 310 | {selected && (selectedReference || selectedSkill) ? ( |
| 311 | <ComposerContextSheet |
| 312 | label={ |
| 313 | selectedReference?.label ?? |
| 314 | selectedSkill?.displayName ?? |
| 315 | selectedSkill?.name ?? |
| 316 | gt("Skill", { $context: "agent skill" }) |
| 317 | } |
| 318 | record={ |
| 319 | record ?? |
| 320 | (selectedSkill |
| 321 | ? { |
| 322 | version: 1, |
| 323 | kind: "skill", |
| 324 | contextId: ComposerContextId.make("skill-preview"), |
| 325 | label: selectedSkill.name, |
| 326 | name: selectedSkill.name, |
| 327 | } |
| 328 | : undefined) |
| 329 | } |
| 330 | {...(selectedSkill?.description ? { skillDescription: selectedSkill.description } : {})} |
| 331 | {...(selectedSkill?.path && onOpenMention |
| 332 | ? { |
| 333 | onOpenSkill: () => { |
| 334 | setSelected(null); |
| 335 | onOpenMention(selectedSkill.path!); |
| 336 | }, |
| 337 | } |
| 338 | : {})} |
| 339 | onOpenThread={(thread) => { |
| 340 | setSelected(null); |
| 341 | openThreadLink(thread); |
| 342 | }} |
| 343 | environmentId={environmentId ?? draft.project?.environmentId} |
| 344 | projectId={draft.project?.projectId} |
| 345 | records={draft.context?.records} |
| 346 | attachments={draft.attachments} |
| 347 | onClose={() => setSelected(null)} |
| 348 | onRemove={removeSelected} |
| 349 | /> |
| 350 | ) : null} |
| 351 | </> |
| 352 | ); |
| 353 | } |
| 354 | export type { |
| 355 | ComposerEditorHandle, |
| 356 | ComposerEditorSelection, |
| 357 | ComposerTextPaste, |
| 358 | } from "../native/T3ComposerEditor"; |