Open History to see the last commit
1import { mFallback, msg } from "gt-i18n";
2import type { MFunctionType } from "gt-i18n/types";
3import type { ChatAttachment } from "@t3tools/contracts";
4import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";
5import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
6import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens";
7import { truncate } from "@t3tools/shared/String";
8
9import { collectComposerModelMentions } from "../composerModelMentions.ts";
10
11export interface ThreadTitleSeedInput {
12 readonly text: string;
13 readonly attachments: ReadonlyArray<Pick<ChatAttachment, "type" | "name">>;
14 readonly fallbackLabels?: ReadonlyArray<string | null | undefined>;
15}
16
17function normalizeTitleSeed(value: string): string {
18 // Mentioned macOS paths can be NFD; titles show them composed.
19 return assistantCitationsToPlainText(value).trim().replace(/\s+/gu, " ").normalize("NFC");
20}
21
22function modelMentionsAsSlugs(value: string): string {
23 let result = "";
24 let cursor = 0;
25 for (const mention of collectComposerModelMentions(value)) {
26 result += value.slice(cursor, mention.start) + mention.model;
27 cursor = mention.end;
28 }
29 return result + value.slice(cursor);
30}
31
32function attachedImagesTitle(count: number, resolve: MFunctionType): string {
33 return count === 1 ? resolve(msg("Attached image")) : resolve(msg("Attached images"));
34}
35
36export function threadTitleTextFromPrompt(
37 value: string,
38 resolve: MFunctionType = mFallback,
39): string {
40 const imageIds = new Set<string>();
41 const prose = replaceComposerContextReferences(value, (reference) => {
42 if (reference.kind === "image") {
43 imageIds.add(reference.contextId);
44 return "";
45 }
46 return reference.label;
47 });
48 return (
49 normalizeTitleSeed(modelMentionsAsSlugs(composerFileLinksToPlainText(prose))) ||
50 (imageIds.size > 0 ? attachedImagesTitle(imageIds.size, resolve) : "")
51 );
52}
53
54export function deriveThreadTitleSeed(
55 input: ThreadTitleSeedInput,
56 resolve: MFunctionType = mFallback,
57): string {
58 const text = threadTitleTextFromPrompt(input.text, resolve);
59 if (text.length > 0) {
60 return truncate(text);
61 }
62
63 const images = input.attachments.filter((attachment) => attachment.type === "image");
64 if (images.length > 0) {
65 return attachedImagesTitle(images.length, resolve);
66 }
67
68 const attachmentName = normalizeTitleSeed(input.attachments[0]?.name ?? "");
69 if (attachmentName.length > 0) {
70 return truncate(resolve(msg("File: {name}", { name: attachmentName })));
71 }
72
73 for (const label of input.fallbackLabels ?? []) {
74 const normalized = normalizeTitleSeed(label ?? "");
75 if (normalized.length > 0) {
76 return truncate(normalized);
77 }
78 }
79
80 return resolve(msg("New thread"));
81}