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";
5import remarkParse from "remark-parse";
6import { unified } from "unified";
7
8import {
9 formatHostedThreadLink,
10 formatThreadLink,
11 guessThreadLinkRef,
12 hostedThreadLink,
13 parseThreadLinkHref,
14 replaceThreadLinks,
15 threadLinkCandidates,
16 threadLinkRefs,
17} from "./threadLinks.ts";
18import { relabelThreadLinks } from "./threadLinksCopy.ts";
19
20const ref = (environmentId: string, threadId = "chat-1") => ({
21 environmentId: EnvironmentId.make(environmentId),
22 threadId: ThreadId.make(threadId),
23});
24const v1 = (threadId: string) => ({ environmentId: null, threadId: ThreadId.make(threadId) });
25const local = EnvironmentId.make("local");
26const titlesIn =
27 (titles: Record<string, Record<string, string>>) =>
28 ({ environmentId, threadId }: ScopedThreadRef) =>
29 titles[environmentId]?.[threadId];
30const japanese: MFunctionType = (encodedMsg, options) => {
31 const english = mFallback(encodedMsg, options);
32 return (
33 english === "Thread no longer available" ? "スレッドは利用できなくなりました" : english
34 ) as typeof english;
35};
36
37describe("thread link destinations", () => {
38 it("names a v1 link's thread in the message's environment, as written and then decoded", () => {
39 expect(threadLinkCandidates(v1("provider%3A1"), local)).toEqual([
40 ref("local", "provider%3A1"),
41 ref("local", "provider:1"),
42 ]);
43 });
44
45 it("opens the unique matching chat in another environment for a v1 link", () => {
46 const destination = ref("remote");
47 expect(guessThreadLinkRef(v1("chat-1"), [ref("local", "other-chat"), destination])).toEqual(
48 destination,
49 );
50 });
51
52 it("opens a v2 link only in its own environment", () => {
53 const there = ref("there", "a%3A1");
54 expect(threadLinkCandidates(there, local)).toEqual([there, ref("there", "a:1")]);
55 expect(guessThreadLinkRef(there, [ref("elsewhere", "a%3A1"), ref("elsewhere", "a:1")])).toBe(
56 null,
57 );
58 });
59
60 it("leaves ambiguous or missing destinations unresolved", () => {
61 const link = v1("provider%3A1");
62 const literal = ref("remote", "provider%3A1");
63 const decoded = ref("remote", "provider:1");
64 expect(
65 guessThreadLinkRef(link, [literal, ref("other-remote", literal.threadId), decoded]),
66 ).toBeNull();
67 expect(guessThreadLinkRef(link, [decoded, ref("other-remote", decoded.threadId)])).toBeNull();
68 expect(guessThreadLinkRef(link, [ref("remote", "other-chat")])).toBeNull();
69 });
70});
71
72describe("thread links", () => {
73 it("takes the ids verbatim, percent escapes included", () => {
74 expect(parseThreadLinkHref("t3-thread://v1/mcp:1234")).toEqual(v1("mcp:1234"));
75 expect(parseThreadLinkHref("t3-thread://v1/thread:delegated-task:mcp%3A1")).toEqual(
76 v1("thread:delegated-task:mcp%3A1"),
77 );
78 expect(parseThreadLinkHref("t3-thread://v2/env-1/thread:a/b%3A1")).toEqual(
79 ref("env-1", "thread:a/b%3A1"),
80 );
81 });
82
83 it("rejects other links and an empty id", () => {
84 expect(parseThreadLinkHref("https://t3.codes")).toBeNull();
85 expect(parseThreadLinkHref("t3-thread://v1/")).toBeNull();
86 expect(parseThreadLinkHref("t3-thread://v1/ ")).toBeNull();
87 expect(parseThreadLinkHref("t3-thread://v2/env-1")).toBeNull();
88 expect(parseThreadLinkHref("t3-thread://v2/env-1/")).toBeNull();
89 expect(parseThreadLinkHref("t3-thread://v2//chat-1")).toBeNull();
90 });
91
92 it("resolves a percent-encoded id when the id as written names no thread", () => {
93 const title = titlesIn({ local: { "thread:project:1": "Decoded", "provider%3A1": "Literal" } });
94 expect(
95 relabelThreadLinks(
96 "[a](t3-thread://v1/thread%3Aproject%3A1) [b](t3-thread://v1/provider%3A1)",
97 local,
98 title,
99 ),
100 ).toBe("[Decoded](t3-thread://v1/thread:project:1) [Literal](t3-thread://v1/provider%3A1)");
101 const untitled = titlesIn({ local: { "a%3A1": "", "a:1": "Other" } });
102 expect(relabelThreadLinks("[Kept](t3-thread://v1/a%3A1)", local, untitled)).toBe(
103 "[Kept](t3-thread://v1/a%3A1)",
104 );
105 });
106
107 it("titles a v2 link from its own environment and writes it with that title", () => {
108 const title = titlesIn({ local: { t1: "Here" }, there: { t1: "There" } });
109 expect(
110 relabelThreadLinks(
111 "<t3-thread://v2/there/t1> and [old](t3-thread://v2/local/t1)",
112 local,
113 title,
114 ),
115 ).toBe("[There](t3-thread://v2/there/t1) and [Here](t3-thread://v2/local/t1)");
116 });
117
118 it("reads an angle-bracketed destination as the labeled link, not an autolink", () => {
119 const title = titlesIn({ local: { t1: "Here" }, there: { t1: "There" } });
120 expect(
121 relabelThreadLinks(
122 "[old](<t3-thread://v2/there/t1>) and [older](<t3-thread://v2/local/t1>)",
123 local,
124 title,
125 ),
126 ).toBe("[There](t3-thread://v2/there/t1) and [Here](t3-thread://v2/local/t1)");
127 expect(
128 relabelThreadLinks("[Kept label](<t3-thread://v2/local/t1>)", local, () => undefined),
129 ).toBe("Kept label");
130 expect(threadLinkRefs("[a](<t3-thread://v2/there/t2>)", local)).toEqual([ref("there", "t2")]);
131 for (const threadId of ["mcp:launch:qa(1)", "mcp:launch:qa)"]) {
132 const thread = ref("there", threadId);
133 const link = formatThreadLink(thread, "Original");
134 expect(link).toBe(`[Original](<t3-thread://v2/there/${threadId}>)`);
135 expect(threadLinkRefs(link, local)).toEqual([thread]);
136 expect(relabelThreadLinks(link, local, () => "Renamed")).toBe(
137 `[Renamed](<t3-thread://v2/there/${threadId}>)`,
138 );
139 expect(relabelThreadLinks(link, local, () => undefined)).toBe("Original");
140 }
141 for (const threadId of ["mcp:launch:qa(1)", "feature(a(b))"]) {
142 const thread = ref("there", threadId);
143 const unbracketed = `[Original](t3-thread://v2/there/${threadId})`;
144 expect(threadLinkRefs(unbracketed, local)).toEqual([thread]);
145 expect(relabelThreadLinks(unbracketed, local, () => "Renamed")).toBe(
146 `[Renamed](<t3-thread://v2/there/${threadId}>)`,
147 );
148 expect(relabelThreadLinks(unbracketed, local, () => undefined)).toBe("Original");
149 }
150 expect(threadLinkRefs("[Original](t3-thread://v2/there/feature\\(test\\))", local)).toEqual([
151 ref("there", "feature(test)"),
152 ]);
153 expect(
154 relabelThreadLinks(
155 "[Original](t3-thread://v2/there/feature\\(test\\))",
156 local,
157 () => undefined,
158 ),
159 ).toBe("Original");
160 const unbalanced = "[Original](t3-thread://v2/there/feature(test)";
161 expect(threadLinkRefs(unbalanced, local)).toEqual([]);
162 expect(relabelThreadLinks(unbalanced, local, () => "Renamed")).toBe(unbalanced);
163 });
164
165 it.each(["Release", "Release [draft]"])("keeps literal thread IDs with label %j", (label) => {
166 for (const [href, id] of [
167 ["t3-thread://v2/there/a&b", "a&b"],
168 ["<t3-thread://v2/there/a&b>", "a&b"],
169 [String.raw`t3-thread://v2/there/task\(a\)`, "task(a)"],
170 ] as const) {
171 expect(threadLinkRefs(`[${label}](${href})`, local)).toEqual([ref("there", id)]);
172 }
173 });
174
175 it.each(["Release", "Release [draft]"])("keeps titled links with label %j", (label) => {
176 for (const href of ["t3-thread://v2/there/t1", "https://app.t3.codes/threads/there/t1"]) {
177 const markdown = `[${label}](${href} "Title")`;
178 expect(replaceThreadLinks(markdown, () => "linked")).toBe(markdown);
179 }
180 });
181
182 it.each(["", "!"])("rewrites a plain multiline label (%j)", (prefix) => {
183 const markdown = `${prefix}[Release\nnotes](https://app.t3.codes/threads/there/t1)`;
184 expect(replaceThreadLinks(markdown, (_link, label) => `{${label}}`)).toBe(
185 `${prefix}{Release\nnotes}`,
186 );
187 });
188
189 it.each([
190 ["Release [draft]", String.raw`https://app.t3.codes/threads/there/task\.foo`, "task.foo"],
191 ["Release [draft]", "https://app.t3.codes/threads/there/task.foo", "task.foo"],
192 ['Release <i title="][">', "https://app.t3.codes/threads/there/t1", "t1"],
193 ["Release [draft]\nnotes", "https://app.t3.codes/threads/there/t1", "t1"],
194 ["Release [draft]", " https://app.t3.codes/threads/there/t1 ", "t1"],
195 ["Release `[` notes", "https://app.t3.codes/threads/there/t1", "t1"],
196 [String.raw`Release [[draft]] \[notes\]`, "<t3-thread://v2/there/t1>", "t1"],
197 ["Release [draft]", "t3-thread://v2/there/task(a)", "task(a)"],
198 ["Release [draft]", "<https://app.t3.codes/threads/there/t1>", "t1"],
199 ])("rewrites the whole link with nested label %s and destination %s", (label, href, threadId) => {
200 expect(
201 replaceThreadLinks(`See [${label}](${href}).`, (link, text) => `{${link.threadId}: ${text}}`),
202 ).toBe(`See {${threadId}: ${label}}.`);
203 });
204
205 it.each(["", "!"])("keeps a thread URL inside an ordinary destination (%j)", (prefix) => {
206 const markdown = `${prefix}[Read [draft] https://app.t3.codes/threads/there/t1](https://example.com)`;
207 expect(replaceThreadLinks(markdown, () => "linked")).toBe(markdown);
208 });
209
210 it("rewrites a thread destination on a nested-bracket image like a flat image", () => {
211 const markdown = "![Release [draft]](https://app.t3.codes/threads/there/t1)";
212 expect(replaceThreadLinks(markdown, (_link, label) => `{${label}}`)).toBe("!{Release [draft]}");
213 });
214
215 it("rewrites a nested label when Markdown nesting exceeds GFM's stack", () => {
216 const quotes = ">".repeat(6000);
217 const markdown = `${quotes} [Release [draft]](https://app.t3.codes/threads/there/t1)`;
218 expect(replaceThreadLinks(markdown, () => "linked")).toBe(`${quotes} linked`);
219 });
220
221 it("turns a v2 link it cannot resolve into plain text, never the raw link", () => {
222 expect(
223 relabelThreadLinks(
224 "<t3-thread://v2/there/t1>, <t3-thread://v2/local/t1>, [Old title](t3-thread://v2/there/t1)",
225 local,
226 () => undefined,
227 ),
228 ).toBe("Thread on another machine, Thread no longer available, Old title");
229 expect(relabelThreadLinks("[Old](t3-thread://v1/t1)", local, () => undefined)).toBe(
230 "[Old](t3-thread://v1/t1)",
231 );
232 expect(relabelThreadLinks("See <t3-thread://v1/gone>", local, () => undefined, japanese)).toBe(
233 "See スレッドは利用できなくなりました",
234 );
235 });
236
237 it.each(["\r", "\r\n", "\n"])(
238 "keeps BOM-prefixed thread link examples literal with %j line endings",
239 (eol) => {
240 const link = "<t3-thread://v2/local/t>";
241 for (const fence of ["~~~", "```"]) {
242 const example = [`\uFEFF${fence}`, link, fence].join(eol);
243 expect(replaceThreadLinks(`${example}${eol}${link}`, () => "linked")).toBe(
244 `${example}${eol}linked`,
245 );
246 }
247 },
248 );
249
250 it.each([
251 [" ", ""],
252 ["\t", ""],
253 ["> ", "> "],
254 ["- ", ""],
255 ])(
256 "rewrites prose links after an indented code line that looks like a fence (%j)",
257 (indent, prose) => {
258 for (const bom of ["", "\uFEFF"]) {
259 const example = `${bom}${indent}~~~\n${prose.trimEnd()}\n${prose}See `;
260 expect(replaceThreadLinks(`${example}<t3-thread://v2/local/t>`, () => "linked")).toBe(
261 `${example}linked`,
262 );
263 }
264 },
265 );
266
267 it.each([
268 ["a blank line", "Intro\n\n", " ", "~~~", ""],
269 ["an indented heading", "Intro\n # Example\n", " ", "~~~", ""],
270 ["a closed fence", "Intro\n```\nexample\n```\n", " ", "~~~", ""],
271 ["a literal list marker", "# Example\n", " ", "- ```md", ""],
272 ["a heading in a quote", "> # Example\n", "> ", "~~~", "> "],
273 ])(
274 "keeps indented code literal and rewrites prose after %s",
275 (_name, before, indent, fence, quote) => {
276 const inside = "<t3-thread://v2/local/code>";
277 const outside = "<t3-thread://v2/local/prose>";
278 const example = `${before}${indent}${fence}\n${indent}${inside}\n${quote.trimEnd()}\n${quote}See `;
279 expect(replaceThreadLinks(`${example}${outside}`, () => "linked")).toBe(`${example}linked`);
280 },
281 );
282
283 it.each([
284 ["a paragraph with four spaces", "Intro\n ~~~"],
285 ["a paragraph with a tab", "Intro\n\t```"],
286 ["a list paragraph", "- Intro\n ~~~"],
287 ["an HTML block", "<div>\n ~~~\n</div>"],
288 ["deeply nested quotes", ">".repeat(6000) + " text\n\n ~~~"],
289 ])("rewrites the prose link after %s", (_name, before) => {
290 const prose = `${before}\n\nSee `;
291 expect(replaceThreadLinks(`${prose}<t3-thread://v2/local/prose>`, () => "linked")).toBe(
292 `${prose}linked`,
293 );
294 });
295
296 it("rewrites a link in footnote prose before an indented fence", () => {
297 const footnote = "Note[^n].\n\n[^n]: note\n\n See ";
298 expect(
299 replaceThreadLinks(`${footnote}<t3-thread://v2/local/prose>\n\n ~~~`, () => "linked"),
300 ).toBe(`${footnote}linked\n\n ~~~`);
301 });
302
303 it.each([
304 ["a paragraph code span", "Intro\n ```\n <t3-thread://v2/local/code>\n ```"],
305 [
306 "a fence with over-indented markers",
307 "~~~\n ~~~\n ~~~\n<t3-thread://v2/local/code>\n~~~",
308 ],
309 [
310 "a fence in a footnote",
311 "Note[^n].\n\n[^n]: note\n\n ~~~\n <t3-thread://v2/local/code>\n ~~~",
312 ],
313 ])("keeps links literal inside %s and rewrites the link after it", (_name, code) => {
314 const prose = `${code}\n\nSee `;
315 expect(replaceThreadLinks(`${prose}<t3-thread://v2/local/prose>`, () => "linked")).toBe(
316 `${prose}linked`,
317 );
318 });
319
320 it.each([
321 ["4 spaces", " ```md\n <t3-thread://v1/abc>\n ```", ""],
322 ["tab", "\t```md\n\t<t3-thread://v1/abc>\n\t```", ""],
323 ["list + 5 spaces", "- ```md\n <t3-thread://v1/abc>\n ```", ""],
324 ["nested list", "- a\n - ```md\n <t3-thread://v1/abc>\n ```", ""],
325 ["nested list with tab", "-\t- ~~~\n <t3-thread://v1/abc>", ""],
326 ["quote + 5 spaces", "> ```md\n> <t3-thread://v1/abc>\n> ```", "> "],
327 [
328 "spaced nested quote + 5 spaces",
329 "> > ```md\n> > <t3-thread://v1/abc>",
330 "> > ",
331 ],
332 ["quote + list + 5 spaces", "> - ```md\n> <t3-thread://v1/abc>\n> ```", "> "],
333 ["quote + space + tab + list", "> \t- ```md\n> <t3-thread://v1/abc>", "> "],
334 [
335 "quote + list after para",
336 "> para\n> - ```md\n> <t3-thread://v1/abc>\n> ```",
337 "> ",
338 ],
339 ["1. after paragraph", "Intro\n1. ```md\n <t3-thread://v1/abc>\n ```", ""],
340 ["ordered list >= 2 after blank", "Intro\n\n2. ```md\n <t3-thread://v1/abc>", ""],
341 [
342 "quote after blank line past closer",
343 "Example\n\n> ~~~\n> ~~~\n> <t3-thread://v1/abc>",
344 "> ",
345 ],
346 ["quote after autolink", "<https://example.com>\n> ~~~\n> <t3-thread://v1/abc>", "> "],
347 ["blank line inside indented code", " ```md\n\n <t3-thread://v1/abc>", ""],
348 ["quote after indented code", " ```md\n> ```\n> <t3-thread://v1/abc>", "> "],
349 ["4 spaces after closer", " ```md\n a\n ```\n <t3-thread://v1/abc>", ""],
350 ["4 spaces with U+2028", " ```\u2028<t3-thread://v1/t1>```", ""],
351 ["hosted link", " ```\n https://app.t3.codes/threads/env/thr\n ```", ""],
352 ])(
353 "keeps links inside fence-looking indented code blocks literal (%s)",
354 (_name, block, prose) => {
355 expect(replaceThreadLinks(block, () => "linked")).toBe(block);
356 const after = `${block}\n${prose.trimEnd()}\n${prose}See `;
357 expect(replaceThreadLinks(`${after}<t3-thread://v2/local/t>`, () => "linked")).toBe(
358 `${after}linked`,
359 );
360 },
361 );
362
363 it("leaves links inside code spans and fences as written", () => {
364 const markdown = [
365 "Live [old](t3-thread://v1/t1), literal `[old](t3-thread://v1/t1)`.",
366 "```md",
367 "<t3-thread://v2/local/t1>",
368 "```",
369 "After <t3-thread://v2/local/t1>",
370 ].join("\n");
371 expect(relabelThreadLinks(markdown, local, () => "New")).toBe(
372 [
373 "Live [New](t3-thread://v1/t1), literal `[old](t3-thread://v1/t1)`.",
374 "```md",
375 "<t3-thread://v2/local/t1>",
376 "```",
377 "After [New](t3-thread://v2/local/t1)",
378 ].join("\n"),
379 );
380 const nested = [
381 "> > ```md",
382 ">> <t3-thread://v2/local/t1>",
383 ">>```",
384 "> > <t3-thread://v2/local/t1>",
385 ];
386 expect(relabelThreadLinks(nested.join("\n"), local, () => "New")).toBe(
387 [...nested.slice(0, 3), "> > [New](t3-thread://v2/local/t1)"].join("\n"),
388 );
389 const deepNested = "> > > > > ```\n> > > > > <t3-thread://v2/local/t1> ```";
390 expect(relabelThreadLinks(deepNested, local, () => "New")).toBe(deepNested);
391 const labels: Array<string | undefined> = [];
392 const separated = "[Label\u2028> > example](t3-thread://v1/t1)";
393 expect(replaceThreadLinks(separated, (_link, label) => void labels.push(label))).toBe(
394 separated,
395 );
396 expect(labels).toEqual(["Label\u2028> > example"]);
397 for (const escaped of ["\\``<t3-thread://v2/env-1/t1>`", "\\```<t3-thread://v2/env-1/t1>``"]) {
398 expect(threadLinkRefs(escaped, local)).toEqual([]);
399 }
400 const indented = " <t3-thread://v2/local/demo>\n\nSee <t3-thread://v2/local/prose>";
401 expect(threadLinkRefs(indented, local)).toEqual([ref("local", "prose")]);
402 expect(relabelThreadLinks(indented, local, () => "New")).toBe(
403 " <t3-thread://v2/local/demo>\n\nSee [New](t3-thread://v2/local/prose)",
404 );
405 expect(relabelThreadLinks("\t<t3-thread://v2/local/demo>", local, () => "New")).toBe(
406 "\t<t3-thread://v2/local/demo>",
407 );
408 expect(relabelThreadLinks("> <t3-thread://v2/local/demo>", local, () => "New")).toBe(
409 "> <t3-thread://v2/local/demo>",
410 );
411 expect(relabelThreadLinks("Intro\n <t3-thread://v2/local/prose>", local, () => "New")).toBe(
412 "Intro\n [New](t3-thread://v2/local/prose)",
413 );
414 });
415
416 it("ends code where CommonMark does, so a link after it stays live", () => {
417 const after = "See <t3-thread://v2/env-1/t1>";
418 const hidden = "<t3-thread://v2/local/in-code>";
419 for (const markdown of [
420 ["```ts", 'const fence = "```";', hidden, "```", after],
421 ["> ```ts", '> const fence = "```";', `> ${hidden}`, "> ```", `> ${after}`],
422 ["> ```", ` > ${hidden}`, "> ```", after],
423 ["- ```bash", " echo hi", " ```", "", after],
424 ["- ```text", ` ${hidden}`, "", after],
425 ["- item", "", " ```text", ` ${hidden}`, "", after],
426 ["[^note]: - ```text", " https://app.t3.codes/threads/local/in-code", "", after],
427 [
428 "[^outer]: [^inner]: - ```text",
429 " https://app.t3.codes/threads/local/in-code",
430 "",
431 after,
432 ],
433 ["- > ```md", ` > ${hidden}`, " > ```", "", after],
434 [">> ```md", `> > ${hidden}`, ">> ```", `> ${after}`],
435 ["> > ~~~", `>> ${hidden}`, ">> ~~~", after],
436 ["1. Run:", "", " ```bash", ' echo "```"', ` ${hidden}`, " ```", "", after],
437 ["````md", "```", hidden, "````", after],
438 ["Use ~~~ to mark it.", after],
439 ["> para", "> ~~~", `> ${after}`],
440 ["> para", `> ~~~ ${after}`],
441 ["- > para", " > ```md", ` > ${after}`],
442 [`Intro\u2028- ~~~ ${after}`],
443 ["Intro", `2. ~~~ ${after}`],
444 ["Intro", `2. - ~~~ ${after}`],
445 [">\t- ```md", `> ${after}`],
446 ["> para", "lazy", "> ~~~", `> ${after}`],
447 ["> para", "> 2. >", `> 2. ~~~ ${after}`],
448 ["> para\r", "> ~~~\r", `> ${after}`],
449 [`> para\r\r> ~~~\r> ${hidden}\r> ${after}`],
450 ["para", " - ```", ` ${after}`],
451 ["para", " - ```", ` ${after}`],
452 [" ~~~", `- ${after}`],
453 [" ~~~md", " ~~~", " ~~~", after],
454 ["- item", " > ~~~", ` > ${hidden}`, ` ${after}`],
455 ["10. > ```md", ` > ${hidden} \`\`\``, "", after],
456 [" - > ```md", ` > ${hidden} \`\`\``, "", after],
457 ["> - Run this:", ">", "> ```bash", "> echo hi", ">", "> ```", `> ${after}`],
458 ["Example", "", "> ~~~", ">\t\t~~~", `> ${hidden}`, ">\t\t~~~", `> ${after}`],
459 [after, "> ~~~", `> ${hidden}`],
460 [`1. \`\`\`md ${hidden}`, ` \t${after}`],
461 ["> ```md", `> \t${after}`],
462 ["> ```md", `>\t ${after}`],
463 ["```" + hidden + "``` then", after],
464 ["Use ```example", hidden, "end``` then", after],
465 ["Stray ` tick", "", after, "and `code`"],
466 ["Stray ` tick", `# ${after}`, "and `code`"],
467 ["Stray ` tick", `- ${after}`, "and `code`"],
468 ["Stray ` tick", `> ${after} and \`code\``],
469 ["> Stray ` tick", `> > ${after} and \`code\``],
470 ["- Stray ` tick", ` > ${after} and \`code\``],
471 ["> Use `example", `> ${hidden} end\``, `> ${after}`],
472 ["> > Use `example", `> > ${hidden} end\``, `> > ${after}`],
473 ["> Use `example", `${hidden} end\``, after],
474 ["Use `example", ` > ${hidden} end\``, after],
475 ["> Use `example", `> > ${hidden} end\``, `> ${after}`],
476 ["> Intro", "Use `example", `> ${hidden} end\``, `> ${after}`],
477 ["> > Intro", "> Use `example", `> > ${hidden} end\``, `> > ${after}`],
478 ["1. Stray ` tick", ` > ${after} and \`code\``],
479 ["1. Intro", "", " Stray ` tick", ` > ${after} and \`code\``],
480 ["- Intro", "", "Use `example", ` > ${hidden} end\``, after],
481 ...["- - -", "* \t* *", "___", "===", "-"].flatMap((boundary) => [
482 ["Stray ` tick", boundary, `${after} and \`code\``],
483 ["> Stray ` tick", `> ${boundary}`, `> ${after} and \`code\``],
484 ]),
485 ["Stray ` tick\r", " ---\r", `${after} and \`code\``],
486 ["> Stray ` tick", "---", `${after} and \`code\``],
487 ["Use `example", "```" + hidden + "`", after],
488 ["\\\\``" + after + "`"],
489 [`Use \`example\r${hidden} end\`. Stray \` tick\r\r${after}\rand \`code\``],
490 [`Stray \` tick\r# ${after}\rand \`code\``],
491 ]) {
492 const joined = markdown.join("\n");
493 expect(threadLinkRefs(joined, local)).toEqual([ref("env-1", "t1")]);
494 expect(relabelThreadLinks(joined, local, () => "New")).toBe(
495 joined.replace("<t3-thread://v2/env-1/t1>", "[New](t3-thread://v2/env-1/t1)"),
496 );
497 }
498 });
499
500 it("keeps multiline code literal when a line only resembles a block boundary", () => {
501 for (const markdown of [
502 ...["--- text", "== =", "-_*", " ==="].map((line) => ["Use `example", line]),
503 ["> Use `example", "> ---"],
504 ["> Use `example", "==="],
505 ]) {
506 const source = [...markdown, "<t3-thread://v2/local/t1> end`"].join("\n");
507 expect(threadLinkRefs(source, local)).toEqual([]);
508 expect(relabelThreadLinks(source, local, () => "New")).toBe(source);
509 }
510 });
511
512 it("lists the threads a message's links can name, outside code", () => {
513 expect(
514 threadLinkRefs(
515 "<t3-thread://v2/there/t1> [a](t3-thread://v1/t%3A2) `<t3-thread://v2/code/t3>`",
516 local,
517 ),
518 ).toEqual([ref("there", "t1"), ref("local", "t%3A2"), ref("local", "t:2")]);
519 });
520
521 it("lists a message's thread links on runtimes whose matchAll omits named groups, such as Hermes", () => {
522 const matchAll = String.prototype.matchAll;
523 using _hermes = vi.spyOn(String.prototype, "matchAll").mockImplementation(function (
524 this: string,
525 regexp: RegExp,
526 ) {
527 return matchAll.call(this, regexp).map((match) => {
528 delete match.groups;
529 return match;
530 });
531 });
532 expect(threadLinkRefs("<t3-thread://v2/local/t1> [a](t3-thread://v2/there/t2)", local)).toEqual(
533 [ref("local", "t1"), ref("there", "t2")],
534 );
535 });
536
537 it("writes a titleless autolink that opens that exact thread", () => {
538 const link = formatThreadLink(ref("env-1", "thread:delegated-task:mcp%3A1"));
539 expect(link).toBe("<t3-thread://v2/env-1/thread:delegated-task:mcp%3A1>");
540 expect(parseThreadLinkHref(link.slice(1, -1))).toEqual(
541 ref("env-1", "thread:delegated-task:mcp%3A1"),
542 );
543 });
544
545 it("formats a label that would otherwise break the Markdown link", () => {
546 expect(formatThreadLink(ref("e", "t1"), "Fix [ci] \\ build")).toBe(
547 "[Fix ci build](t3-thread://v2/e/t1)",
548 );
549 expect(formatThreadLink(ref("e", "t1"), " ] ")).toBe("<t3-thread://v2/e/t1>");
550 });
551});
552
553describe("hosted thread links", () => {
554 it("escapes every id character a sentence or path could claim, and reads it back", () => {
555 const thread = ref("env.1", "thread:delegated/mcp%3A1.");
556 const link = hostedThreadLink(thread);
557 expect(link).toBe("https://app.t3.codes/threads/env%2E1/thread%3Adelegated%2Fmcp%253A1%2E");
558 expect(parseThreadLinkHref(link)).toEqual({ ...thread, hosted: true });
559 expect(hostedThreadLink(thread, "https://preview.t3.codes/")).toMatch(
560 /^https:\/\/preview\.t3\.codes\/threads\//,
561 );
562
563 const literal = ref("local", "task%3A1");
564 const literalUrl = hostedThreadLink(literal);
565 expect(literalUrl).toBe("https://app.t3.codes/threads/local/task%253A1");
566 expect(threadLinkCandidates(parseThreadLinkHref(literalUrl)!, local)).toEqual([literal]);
567 expect(threadLinkRefs(literalUrl, local)).toEqual([literal]);
568 expect(relabelThreadLinks(literalUrl, local, titlesIn({ local: { "task:1": "Other" } }))).toBe(
569 "Thread no longer available",
570 );
571 expect(
572 relabelThreadLinks(
573 literalUrl,
574 local,
575 titlesIn({ local: { "task%3A1": "Literal", "task:1": "Other" } }),
576 ),
577 ).toBe("[Literal](t3-thread://v2/local/task%3A1)");
578 });
579
580 it("reads only a bare thread path on the hosted app", () => {
581 expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1/thread-1")).toEqual({
582 ...ref("env-1", "thread-1"),
583 hosted: true,
584 });
585 expect(parseThreadLinkHref("https://app.t3.codes/threads/env.1/task.foo")).toEqual({
586 ...ref("env.1", "task.foo"),
587 hosted: true,
588 });
589 expect(parseThreadLinkHref("https://app.t3.codes/threads/local/task.")).toBeNull();
590 expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1/thread-1?prompt=go")).toBeNull();
591 expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1/thread-1/extra")).toBeNull();
592 expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1")).toBeNull();
593 expect(parseThreadLinkHref("https://app.t3.codes/env-1/thread-1")).toBeNull();
594 expect(parseThreadLinkHref("https://evil.test/threads/env-1/thread-1")).toBeNull();
595 });
596
597 it("writes a copied link a reader can follow, labeled when it has a title", () => {
598 expect(formatHostedThreadLink(ref("e", "t1"), "Fix [ci]")).toBe(
599 "[Fix ci](https://app.t3.codes/threads/e/t1)",
600 );
601 expect(formatHostedThreadLink(ref("e", "t1"), " ")).toBe("https://app.t3.codes/threads/e/t1");
602 });
603
604 it("titles hosted links in every Markdown form and writes them as v2 links", () => {
605 const title = titlesIn({ there: { t1: "There" }, local: { "task.foo": "Dotted" } });
606 expect(
607 relabelThreadLinks(
608 [
609 "See https://app.t3.codes/threads/there/t1.",
610 "See https://app.t3.codes/threads/local/task.foo.",
611 "[old](https://app.t3.codes/threads/there/t1)",
612 "<https://app.t3.codes/threads/there/t1>",
613 "`https://app.t3.codes/threads/there/t1`",
614 "https://app.t3.codes/threads/there/t1?prompt=go",
615 "https://app.t3.codes/threads/local/task.foo?prompt=go",
616 "https://app.t3.codes/threads/local/task.foo/extra",
617 ].join("\n"),
618 local,
619 title,
620 ),
621 ).toBe(
622 [
623 "See [There](t3-thread://v2/there/t1).",
624 "See [Dotted](t3-thread://v2/local/task.foo).",
625 "[There](t3-thread://v2/there/t1)",
626 "[There](t3-thread://v2/there/t1)",
627 "`https://app.t3.codes/threads/there/t1`",
628 "https://app.t3.codes/threads/there/t1?prompt=go",
629 "https://app.t3.codes/threads/local/task.foo?prompt=go",
630 "https://app.t3.codes/threads/local/task.foo/extra",
631 ].join("\n"),
632 );
633 expect(
634 relabelThreadLinks("https://app.t3.codes/threads/there/t1", local, () => undefined),
635 ).toBe("Thread on another machine");
636 expect(threadLinkRefs("Open https://app.t3.codes/threads/there/t%3A1", local)).toEqual([
637 ref("there", "t:1"),
638 ]);
639 expect(threadLinkRefs("https://app.t3.codes/threads/local/task.foo", local)).toEqual([
640 ref("local", "task.foo"),
641 ]);
642 expect(threadLinkRefs("https://app.t3.codes/threads/local/task.foo?prompt=go", local)).toEqual(
643 [],
644 );
645 });
646
647 it("leaves a hosted link that is part of another link as written", () => {
648 const hosted = "https://app.t3.codes/threads/there/t1";
649 const relabeled = "[There](t3-thread://v2/there/t1)";
650 const title = titlesIn({ there: { t1: "There" } });
651 for (const [markdown, expected] of [
652 [`https://example.com/?next=${hosted}`],
653 [`[Example](https://example.com/?next=${hosted})`],
654 [`[ ${hosted} ](https://example.com)`],
655 [`[${hosted}](<https://example.com/a b> "Title")`],
656 [`[${hosted}](t3-thread://v2/local/id "Title")`],
657 [`[a](https://example.com/x_(y)) ${hosted}`, `[a](https://example.com/x_(y)) ${relabeled}`],
658 [`(${hosted}) **${hosted}**`, `(${relabeled}) **${relabeled}**`],
659 [`[[[ [old](${hosted})`, `[[[ ${relabeled}`],
660 [`\\\\[old](${hosted})`, `\\\\${relabeled}`],
661 [`\\\\\\\\[old](${hosted})`, `\\\\\\\\${relabeled}`],
662 [`\\[old](${hosted})`, `\\[old](${relabeled})`],
663 [`\\[ ${hosted} ](https://example.com)`, `\\[ ${relabeled} ](https://example.com)`],
664 ["\\[old](t3-thread://v2/there/t1) \\<t3-thread://v2/there/t1>"],
665 ] as const) {
666 expect(relabelThreadLinks(markdown, local, title)).toBe(expected ?? markdown);
667 expect(threadLinkRefs(markdown, local)).toEqual(
668 expected === undefined ? [] : [ref("there", "t1")],
669 );
670 }
671 });
672
673 it("keeps Markdown reference link definitions intact when relabeling", () => {
674 const hosted = "https://app.t3.codes/threads/local/demo";
675 for (const markdown of [
676 `[Review][thread]\n\n[thread]: ${hosted}`,
677 `[Review][thread]\n\n[thread]:${hosted}`,
678 `[Review][thread]\n\n[thread]: <${hosted}>`,
679 `[Review][thread]\n\n[thread]: <t3-thread://v2/local/demo>`,
680 `[Review][thread]\n\n[thread]:\n ${hosted}`,
681 `[Review][thread]\n\n [thread]: ${hosted} "Demo"`,
682 `> [Review][thread]\n>\n> [thread]: ${hosted}`,
683 ]) {
684 for (const title of [() => "Demo", () => undefined]) {
685 expect(relabelThreadLinks(markdown, local, title)).toBe(markdown);
686 }
687 }
688
689 const withLiveAfter = `[Review][thread]\n\n[thread]: ${hosted}\n\nSee ${hosted}`;
690 expect(relabelThreadLinks(withLiveAfter, local, () => "Demo")).toBe(
691 `[Review][thread]\n\n[thread]: ${hosted}\n\nSee [Demo](t3-thread://v2/local/demo)`,
692 );
693
694 for (const markdown of [
695 `[${hosted}][site]\n\n[site]: https://example.com`,
696 `![${hosted}][site]\n\n[site]: https://example.com`,
697 ]) {
698 expect(relabelThreadLinks(markdown, local, () => "Demo")).toBe(markdown);
699 expect(threadLinkRefs(markdown, local)).toEqual([]);
700 }
701 const labelWithLiveAfter = `[${hosted}][site]\n\n[site]: https://example.com\n\n${hosted}`;
702 expect(relabelThreadLinks(labelWithLiveAfter, local, () => "Demo")).toBe(
703 `[${hosted}][site]\n\n[site]: https://example.com\n\n[Demo](t3-thread://v2/local/demo)`,
704 );
705
706 const paragraphContinuation = `Intro\n[thread]: ${hosted}`;
707 expect(relabelThreadLinks(paragraphContinuation, local, () => "Demo")).toBe(
708 `Intro\n[thread]: [Demo](t3-thread://v2/local/demo)`,
709 );
710 });
711
712 it("keeps relabeled links navigable when the thread id contains a space", () => {
713 const linkUrl = (markdown: string) => {
714 const paragraph = unified().use(remarkParse).parse(markdown).children[0];
715 const node = paragraph?.type === "paragraph" ? paragraph.children[0] : undefined;
716 return node?.type === "link" ? node.url : undefined;
717 };
718 const thread = ref("local", "work item");
719 const titles = titlesIn({ local: { "work item": "Review", "work%20item": "Encoded" } });
720
721 const relabeled = relabelThreadLinks(hostedThreadLink(thread), local, titles);
722 expect(parseThreadLinkHref(linkUrl(relabeled) ?? "")).toEqual({ ...thread, hosted: true });
723 expect(threadLinkRefs(relabeled, local)).toEqual([thread]);
724
725 const v1Relabeled = relabelThreadLinks("[old](t3-thread://v1/work%20item)", local, titles);
726 expect(linkUrl(v1Relabeled)).toBe("t3-thread://v1/work%20item");
727 expect(formatThreadLink(v1("work item"))).toBe("<t3-thread://v1/work%20item>");
728 });
729});