Open History to see the last commit
1import { mFallback, msg } from "gt-i18n";
2import type { M } from "gt-i18n";
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: M): string {
33 return count === 1 ? resolve(msg("Attached image")) : resolve(msg("Attached images"));
34}
35
36export function threadTitleTextFromPrompt(value: string, resolve: M = mFallback): string {
37 const imageIds = new Set<string>();
38 const prose = replaceComposerContextReferences(value, (reference) => {
39 if (reference.kind === "image") {
40 imageIds.add(reference.contextId);
41 return "";
42 }
43 return reference.label;
44 });
45 return (
46 normalizeTitleSeed(modelMentionsAsSlugs(composerFileLinksToPlainText(prose))) ||
47 (imageIds.size > 0 ? attachedImagesTitle(imageIds.size, resolve) : "")
48 );
49}
50
51export function deriveThreadTitleSeed(input: ThreadTitleSeedInput, resolve: M = mFallback): string {
52 const text = threadTitleTextFromPrompt(input.text, resolve);
53 if (text.length > 0) {
54 return truncate(text);
55 }
56
57 const images = input.attachments.filter((attachment) => attachment.type === "image");
58 if (images.length > 0) {
59 return attachedImagesTitle(images.length, resolve);
60 }
61
62 const attachmentName = normalizeTitleSeed(input.attachments[0]?.name ?? "");
63 if (attachmentName.length > 0) {
64 return truncate(resolve(msg`File: ${{ name: attachmentName }}`));
65 }
66
67 for (const label of input.fallbackLabels ?? []) {
68 const normalized = normalizeTitleSeed(label ?? "");
69 if (normalized.length > 0) {
70 return truncate(normalized);
71 }
72 }
73
74 return resolve(msg("New thread"));
75}