Open History to see the last commit
1import type { ChatAttachment } from "@t3tools/contracts";
2import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";
3import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
4import { truncate } from "@t3tools/shared/String";
5
6export interface ThreadTitleSeedInput {
7 readonly text: string;
8 readonly attachments: ReadonlyArray<Pick<ChatAttachment, "type" | "name">>;
9 readonly fallbackLabels?: ReadonlyArray<string | null | undefined>;
10}
11
12function normalizeTitleSeed(value: string): string {
13 return assistantCitationsToPlainText(value).trim().replace(/\s+/gu, " ");
14}
15
16export function threadTitleTextFromPrompt(value: string): string {
17 const imageIds = new Set<string>();
18 const prose = replaceComposerContextReferences(value, (reference) => {
19 if (reference.kind === "image") {
20 imageIds.add(reference.contextId);
21 return "";
22 }
23 return reference.label;
24 });
25 return (
26 normalizeTitleSeed(prose) ||
27 (imageIds.size > 0 ? (imageIds.size === 1 ? "Attached image" : "Attached images") : "")
28 );
29}
30
31export function deriveThreadTitleSeed(input: ThreadTitleSeedInput): string {
32 const text = threadTitleTextFromPrompt(input.text);
33 if (text.length > 0) {
34 return truncate(text);
35 }
36
37 const images = input.attachments.filter((attachment) => attachment.type === "image");
38 if (images.length > 0) {
39 return images.length === 1 ? "Attached image" : "Attached images";
40 }
41
42 const attachmentName = normalizeTitleSeed(input.attachments[0]?.name ?? "");
43 if (attachmentName.length > 0) {
44 return truncate(`File: ${attachmentName}`);
45 }
46
47 for (const label of input.fallbackLabels ?? []) {
48 const normalized = normalizeTitleSeed(label ?? "");
49 if (normalized.length > 0) {
50 return truncate(normalized);
51 }
52 }
53
54 return "New thread";
55}