Open History to see the last commit
1import { describe, expect, it, vi } from "vite-plus/test";
2import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
3import { mFallback } from "gt-i18n";
4import type { MFunctionType } from "gt-i18n/types";
5
6import {
7 formatHostedThreadLink,
8 formatThreadLink,
9 guessThreadLinkRef,
10 hostedThreadLink,
11 parseThreadLinkHref,
12 replaceThreadLinks,
13 threadLinkCandidates,
14 threadLinkRefs,
15} from "./threadLinks.ts";
16import { relabelThreadLinks } from "./threadLinksCopy.ts";
17
18const ref = (environmentId: string, threadId = "chat-1") => ({
19 environmentId: EnvironmentId.make(environmentId),
20 threadId: ThreadId.make(threadId),
21});
22const v1 = (threadId: string) => ({ environmentId: null, threadId: ThreadId.make(threadId) });
23const local = EnvironmentId.make("local");
24const titlesIn =
25 (titles: Record<string, Record<string, string>>) =>
26 ({ environmentId, threadId }: ScopedThreadRef) =>
27 titles[environmentId]?.[threadId];
28const japanese: MFunctionType = (encodedMsg, options) => {
29 const english = mFallback(encodedMsg, options);
30 return (
31 english === "Thread no longer available" ? "スレッドは利用できなくなりました" : english
32 ) as typeof english;
33};
34
35describe("thread link destinations", () => {
36 it("names a v1 link's thread in the message's environment, as written and then decoded", () => {
37 expect(threadLinkCandidates(v1("provider%3A1"), local)).toEqual([
38 ref("local", "provider%3A1"),
39 ref("local", "provider:1"),
40 ]);
41 });
42
43 it("opens the unique matching chat in another environment for a v1 link", () => {
44 const destination = ref("remote");
45 expect(guessThreadLinkRef(v1("chat-1"), [ref("local", "other-chat"), destination])).toEqual(
46 destination,
47 );
48 });
49
50 it("opens a v2 link only in its own environment", () => {
51 const there = ref("there", "a%3A1");
52 expect(threadLinkCandidates(there, local)).toEqual([there, ref("there", "a:1")]);
53 expect(guessThreadLinkRef(there, [ref("elsewhere", "a%3A1"), ref("elsewhere", "a:1")])).toBe(
54 null,
55 );
56 });
57
58 it("leaves ambiguous or missing destinations unresolved", () => {
59 const link = v1("provider%3A1");
60 const literal = ref("remote", "provider%3A1");
61 const decoded = ref("remote", "provider:1");
62 expect(
63 guessThreadLinkRef(link, [literal, ref("other-remote", literal.threadId), decoded]),
64 ).toBeNull();
65 expect(guessThreadLinkRef(link, [decoded, ref("other-remote", decoded.threadId)])).toBeNull();
66 expect(guessThreadLinkRef(link, [ref("remote", "other-chat")])).toBeNull();
67 });
68});
69
70describe("thread links", () => {
71 it("takes the ids verbatim, percent escapes included", () => {
72 expect(parseThreadLinkHref("t3-thread://v1/mcp:1234")).toEqual(v1("mcp:1234"));
73 expect(parseThreadLinkHref("t3-thread://v1/thread:delegated-task:mcp%3A1")).toEqual(
74 v1("thread:delegated-task:mcp%3A1"),
75 );
76 expect(parseThreadLinkHref("t3-thread://v2/env-1/thread:a/b%3A1")).toEqual(
77 ref("env-1", "thread:a/b%3A1"),
78 );
79 });
80
81 it("rejects other links and an empty id", () => {
82 expect(parseThreadLinkHref("https://t3.codes")).toBeNull();
83 expect(parseThreadLinkHref("t3-thread://v1/")).toBeNull();
84 expect(parseThreadLinkHref("t3-thread://v1/ ")).toBeNull();
85 expect(parseThreadLinkHref("t3-thread://v2/env-1")).toBeNull();
86 expect(parseThreadLinkHref("t3-thread://v2/env-1/")).toBeNull();
87 expect(parseThreadLinkHref("t3-thread://v2//chat-1")).toBeNull();
88 });
89
90 it("resolves a percent-encoded id when the id as written names no thread", () => {
91 const title = titlesIn({ local: { "thread:project:1": "Decoded", "provider%3A1": "Literal" } });
92 expect(
93 relabelThreadLinks(
94 "[a](t3-thread://v1/thread%3Aproject%3A1) [b](t3-thread://v1/provider%3A1)",
95 local,
96 title,
97 ),
98 ).toBe("[Decoded](t3-thread://v1/thread:project:1) [Literal](t3-thread://v1/provider%3A1)");
99 const untitled = titlesIn({ local: { "a%3A1": "", "a:1": "Other" } });
100 expect(relabelThreadLinks("[Kept](t3-thread://v1/a%3A1)", local, untitled)).toBe(
101 "[Kept](t3-thread://v1/a%3A1)",
102 );
103 });
104
105 it("titles a v2 link from its own environment and writes it with that title", () => {
106 const title = titlesIn({ local: { t1: "Here" }, there: { t1: "There" } });
107 expect(
108 relabelThreadLinks(
109 "<t3-thread://v2/there/t1> and [old](t3-thread://v2/local/t1)",
110 local,
111 title,
112 ),
113 ).toBe("[There](t3-thread://v2/there/t1) and [Here](t3-thread://v2/local/t1)");
114 });
115
116 it("reads an angle-bracketed destination as the labeled link, not an autolink", () => {
117 const title = titlesIn({ local: { t1: "Here" }, there: { t1: "There" } });
118 expect(
119 relabelThreadLinks(
120 "[old](<t3-thread://v2/there/t1>) and [older](<t3-thread://v2/local/t1>)",
121 local,
122 title,
123 ),
124 ).toBe("[There](t3-thread://v2/there/t1) and [Here](t3-thread://v2/local/t1)");
125 expect(
126 relabelThreadLinks("[Kept label](<t3-thread://v2/local/t1>)", local, () => undefined),
127 ).toBe("Kept label");
128 expect(threadLinkRefs("[a](<t3-thread://v2/there/t2>)", local)).toEqual([ref("there", "t2")]);
129 for (const threadId of ["mcp:launch:qa(1)", "mcp:launch:qa)"]) {
130 const thread = ref("there", threadId);
131 const link = formatThreadLink(thread, "Original");
132 expect(link).toBe(`[Original](<t3-thread://v2/there/${threadId}>)`);
133 expect(threadLinkRefs(link, local)).toEqual([thread]);
134 expect(relabelThreadLinks(link, local, () => "Renamed")).toBe(
135 `[Renamed](<t3-thread://v2/there/${threadId}>)`,
136 );
137 expect(relabelThreadLinks(link, local, () => undefined)).toBe("Original");
138 }
139 });
140
141 it("turns a v2 link it cannot resolve into plain text, never the raw link", () => {
142 expect(
143 relabelThreadLinks(
144 "<t3-thread://v2/there/t1>, <t3-thread://v2/local/t1>, [Old title](t3-thread://v2/there/t1)",
145 local,
146 () => undefined,
147 ),
148 ).toBe("Thread on another machine, Thread no longer available, Old title");
149 expect(relabelThreadLinks("[Old](t3-thread://v1/t1)", local, () => undefined)).toBe(
150 "[Old](t3-thread://v1/t1)",
151 );
152 expect(relabelThreadLinks("See <t3-thread://v1/gone>", local, () => undefined, japanese)).toBe(
153 "See スレッドは利用できなくなりました",
154 );
155 });
156
157 it("leaves links inside code spans and fences as written", () => {
158 const markdown = [
159 "Live [old](t3-thread://v1/t1), literal `[old](t3-thread://v1/t1)`.",
160 "```md",
161 "<t3-thread://v2/local/t1>",
162 "```",
163 "After <t3-thread://v2/local/t1>",
164 ].join("\n");
165 expect(relabelThreadLinks(markdown, local, () => "New")).toBe(
166 [
167 "Live [New](t3-thread://v1/t1), literal `[old](t3-thread://v1/t1)`.",
168 "```md",
169 "<t3-thread://v2/local/t1>",
170 "```",
171 "After [New](t3-thread://v2/local/t1)",
172 ].join("\n"),
173 );
174 const nested = [
175 "> > ```md",
176 ">> <t3-thread://v2/local/t1>",
177 ">>```",
178 "> > <t3-thread://v2/local/t1>",
179 ];
180 expect(relabelThreadLinks(nested.join("\n"), local, () => "New")).toBe(
181 [...nested.slice(0, 3), "> > [New](t3-thread://v2/local/t1)"].join("\n"),
182 );
183 const labels: Array<string | undefined> = [];
184 const separated = "[Label\u2028> > example](t3-thread://v1/t1)";
185 expect(replaceThreadLinks(separated, (_link, label) => void labels.push(label))).toBe(
186 separated,
187 );
188 expect(labels).toEqual(["Label\u2028> > example"]);
189 for (const escaped of ["\\``<t3-thread://v2/env-1/t1>`", "\\```<t3-thread://v2/env-1/t1>``"]) {
190 expect(threadLinkRefs(escaped, local)).toEqual([]);
191 }
192 });
193
194 it("ends code where CommonMark does, so a link after it stays live", () => {
195 const after = "See <t3-thread://v2/env-1/t1>";
196 const hidden = "<t3-thread://v2/local/in-code>";
197 for (const markdown of [
198 ["```ts", 'const fence = "```";', hidden, "```", after],
199 ["> ```ts", '> const fence = "```";', `> ${hidden}`, "> ```", `> ${after}`],
200 ["> ```", ` > ${hidden}`, "> ```", after],
201 ["- ```bash", " echo hi", " ```", "", after],
202 ["- > ```md", ` > ${hidden}`, " > ```", "", after],
203 [">> ```md", `> > ${hidden}`, ">> ```", `> ${after}`],
204 ["> > ~~~", `>> ${hidden}`, ">> ~~~", after],
205 ["1. Run:", "", " ```bash", ' echo "```"', ` ${hidden}`, " ```", "", after],
206 ["````md", "```", hidden, "````", after],
207 ["Use ~~~ to mark it.", after],
208 ["```" + hidden + "``` then", after],
209 ["Use ```example", hidden, "end``` then", after],
210 ["Stray ` tick", "", after, "and `code`"],
211 ["Stray ` tick", `# ${after}`, "and `code`"],
212 ["Stray ` tick", `- ${after}`, "and `code`"],
213 ["Stray ` tick", `> ${after} and \`code\``],
214 ["> Stray ` tick", `> > ${after} and \`code\``],
215 ["- Stray ` tick", ` > ${after} and \`code\``],
216 ["> Use `example", `> ${hidden} end\``, `> ${after}`],
217 ["> > Use `example", `> > ${hidden} end\``, `> > ${after}`],
218 ["> Use `example", `${hidden} end\``, after],
219 ["Use `example", ` > ${hidden} end\``, after],
220 ["> Use `example", `> > ${hidden} end\``, `> ${after}`],
221 ["> Intro", "Use `example", `> ${hidden} end\``, `> ${after}`],
222 ["> > Intro", "> Use `example", `> > ${hidden} end\``, `> > ${after}`],
223 ["1. Stray ` tick", ` > ${after} and \`code\``],
224 ["1. Intro", "", " Stray ` tick", ` > ${after} and \`code\``],
225 ["- Intro", "", "Use `example", ` > ${hidden} end\``, after],
226 ...["- - -", "* \t* *", "___", "===", "-"].flatMap((boundary) => [
227 ["Stray ` tick", boundary, `${after} and \`code\``],
228 ["> Stray ` tick", `> ${boundary}`, `> ${after} and \`code\``],
229 ]),
230 ["Stray ` tick\r", " ---\r", `${after} and \`code\``],
231 ["> Stray ` tick", "---", `${after} and \`code\``],
232 ["Use `example", "```" + hidden + "`", after],
233 ["\\\\``" + after + "`"],
234 ]) {
235 const joined = markdown.join("\n");
236 expect(threadLinkRefs(joined, local)).toEqual([ref("env-1", "t1")]);
237 expect(relabelThreadLinks(joined, local, () => "New")).toBe(
238 joined.replace("<t3-thread://v2/env-1/t1>", "[New](t3-thread://v2/env-1/t1)"),
239 );
240 }
241 });
242
243 it("keeps multiline code literal when a line only resembles a block boundary", () => {
244 for (const markdown of [
245 ...["--- text", "== =", "-_*", " ==="].map((line) => ["Use `example", line]),
246 ["> Use `example", "> ---"],
247 ["> Use `example", "==="],
248 ]) {
249 const source = [...markdown, "<t3-thread://v2/local/t1> end`"].join("\n");
250 expect(threadLinkRefs(source, local)).toEqual([]);
251 expect(relabelThreadLinks(source, local, () => "New")).toBe(source);
252 }
253 });
254
255 it("lists the threads a message's links can name, outside code", () => {
256 expect(
257 threadLinkRefs(
258 "<t3-thread://v2/there/t1> [a](t3-thread://v1/t%3A2) `<t3-thread://v2/code/t3>`",
259 local,
260 ),
261 ).toEqual([ref("there", "t1"), ref("local", "t%3A2"), ref("local", "t:2")]);
262 });
263
264 it("lists a message's thread links on runtimes whose matchAll omits named groups, such as Hermes", () => {
265 const matchAll = String.prototype.matchAll;
266 using _hermes = vi.spyOn(String.prototype, "matchAll").mockImplementation(function (
267 this: string,
268 regexp: RegExp,
269 ) {
270 return matchAll.call(this, regexp).map((match) => {
271 delete match.groups;
272 return match;
273 });
274 });
275 expect(threadLinkRefs("<t3-thread://v2/local/t1> [a](t3-thread://v2/there/t2)", local)).toEqual(
276 [ref("local", "t1"), ref("there", "t2")],
277 );
278 });
279
280 it("writes a titleless autolink that opens that exact thread", () => {
281 const link = formatThreadLink(ref("env-1", "thread:delegated-task:mcp%3A1"));
282 expect(link).toBe("<t3-thread://v2/env-1/thread:delegated-task:mcp%3A1>");
283 expect(parseThreadLinkHref(link.slice(1, -1))).toEqual(
284 ref("env-1", "thread:delegated-task:mcp%3A1"),
285 );
286 });
287
288 it("formats a label that would otherwise break the Markdown link", () => {
289 expect(formatThreadLink(ref("e", "t1"), "Fix [ci] \\ build")).toBe(
290 "[Fix ci build](t3-thread://v2/e/t1)",
291 );
292 expect(formatThreadLink(ref("e", "t1"), " ] ")).toBe("<t3-thread://v2/e/t1>");
293 });
294});
295
296describe("hosted thread links", () => {
297 it("escapes every id character a sentence or path could claim, and reads it back", () => {
298 const thread = ref("env.1", "thread:delegated/mcp%3A1.");
299 const link = hostedThreadLink(thread);
300 expect(link).toBe("https://app.t3.codes/threads/env%2E1/thread%3Adelegated%2Fmcp%253A1%2E");
301 expect(parseThreadLinkHref(link)).toEqual(thread);
302 expect(hostedThreadLink(thread, "https://preview.t3.codes/")).toMatch(
303 /^https:\/\/preview\.t3\.codes\/threads\//,
304 );
305 });
306
307 it("reads only a bare thread path on the hosted app", () => {
308 expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1/thread-1")).toEqual(
309 ref("env-1", "thread-1"),
310 );
311 expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1/thread-1?prompt=go")).toBeNull();
312 expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1/thread-1/extra")).toBeNull();
313 expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1")).toBeNull();
314 expect(parseThreadLinkHref("https://app.t3.codes/env-1/thread-1")).toBeNull();
315 expect(parseThreadLinkHref("https://evil.test/threads/env-1/thread-1")).toBeNull();
316 });
317
318 it("writes a copied link a reader can follow, labeled when it has a title", () => {
319 expect(formatHostedThreadLink(ref("e", "t1"), "Fix [ci]")).toBe(
320 "[Fix ci](https://app.t3.codes/threads/e/t1)",
321 );
322 expect(formatHostedThreadLink(ref("e", "t1"), " ")).toBe("https://app.t3.codes/threads/e/t1");
323 });
324
325 it("titles hosted links in every Markdown form and writes them as v2 links", () => {
326 const title = titlesIn({ there: { t1: "There" } });
327 expect(
328 relabelThreadLinks(
329 [
330 "See https://app.t3.codes/threads/there/t1.",
331 "[old](https://app.t3.codes/threads/there/t1)",
332 "<https://app.t3.codes/threads/there/t1>",
333 "`https://app.t3.codes/threads/there/t1`",
334 "https://app.t3.codes/threads/there/t1?prompt=go",
335 ].join("\n"),
336 local,
337 title,
338 ),
339 ).toBe(
340 [
341 "See [There](t3-thread://v2/there/t1).",
342 "[There](t3-thread://v2/there/t1)",
343 "[There](t3-thread://v2/there/t1)",
344 "`https://app.t3.codes/threads/there/t1`",
345 "https://app.t3.codes/threads/there/t1?prompt=go",
346 ].join("\n"),
347 );
348 expect(
349 relabelThreadLinks("https://app.t3.codes/threads/there/t1", local, () => undefined),
350 ).toBe("Thread on another machine");
351 expect(threadLinkRefs("Open https://app.t3.codes/threads/there/t%3A1", local)).toEqual([
352 ref("there", "t:1"),
353 ]);
354 });
355
356 it("leaves a hosted link that is part of another link as written", () => {
357 const hosted = "https://app.t3.codes/threads/there/t1";
358 const relabeled = "[There](t3-thread://v2/there/t1)";
359 const title = titlesIn({ there: { t1: "There" } });
360 for (const [markdown, expected] of [
361 [`https://example.com/?next=${hosted}`],
362 [`[Example](https://example.com/?next=${hosted})`],
363 [`[ ${hosted} ](https://example.com)`],
364 [`[${hosted}](<https://example.com/a b> "Title")`],
365 [`[a](https://example.com/x_(y)) ${hosted}`, `[a](https://example.com/x_(y)) ${relabeled}`],
366 [`(${hosted}) **${hosted}**`, `(${relabeled}) **${relabeled}**`],
367 [`[[[ [old](${hosted})`, `[[[ ${relabeled}`],
368 [`\\\\[old](${hosted})`, `\\\\${relabeled}`],
369 [`\\\\\\\\[old](${hosted})`, `\\\\\\\\${relabeled}`],
370 [`\\[old](${hosted})`, `\\[old](${relabeled})`],
371 [`\\[ ${hosted} ](https://example.com)`, `\\[ ${relabeled} ](https://example.com)`],
372 ["\\[old](t3-thread://v2/there/t1) \\<t3-thread://v2/there/t1>"],
373 ] as const) {
374 expect(relabelThreadLinks(markdown, local, title)).toBe(expected ?? markdown);
375 expect(threadLinkRefs(markdown, local)).toEqual(
376 expected === undefined ? [] : [ref("there", "t1")],
377 );
378 }
379 });
380});