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 { M } from "gt-i18n";
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: M = (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([
183 String.raw`[Example](https://app.t3.codes/threads/there/t1 "say \"hi\"")`,
184 String.raw`[https://app.t3.codes/threads/there/t1](https://example.com 'a \'b')`,
185 "[https://app.t3.codes/threads/there/t1](t3-thread://v2/there/t2 (My Title))",
186 "[https://app.t3.codes/threads/there/t1](t3-thread://v2/there/t2 (first\nsecond))",
187 '[Example](https://app.t3.codes/threads/there/t1 "first\r\nsecond")',
188 ])("keeps titled Markdown intact: %s", (markdown) => {
189 expect(replaceThreadLinks(markdown, () => "[There](t3-thread://v2/there/t1)")).toBe(markdown);
190 });
191
192 it.each([
193 ["(", ")"],
194 ['"', '"'],
195 ["'", "'"],
196 ])("replaces bare thread URLs after a blank line in a %s...%s title", (open, close) => {
197 for (const blankLine of ["\r\r", "\n\n", "\n \t\n", "\r\n\r\n"]) {
198 const markdown = `[x](https://example.com ${open}a${blankLine}https://app.t3.codes/threads/there/t1${close})`;
199 expect(replaceThreadLinks(markdown, () => "[There](t3-thread://v2/there/t1)")).toBe(
200 `[x](https://example.com ${open}a${blankLine}[There](t3-thread://v2/there/t1)${close})`,
201 );
202 }
203 });
204
205 it.each(["", "!"])("rewrites a plain multiline label (%j)", (prefix) => {
206 const markdown = `${prefix}[Release\nnotes](https://app.t3.codes/threads/there/t1)`;
207 expect(replaceThreadLinks(markdown, (_link, label) => `{${label}}`)).toBe(
208 `${prefix}{Release\nnotes}`,
209 );
210 });
211
212 it.each([
213 ["Release [draft]", String.raw`https://app.t3.codes/threads/there/task\.foo`, "task.foo"],
214 ["Release [draft]", "https://app.t3.codes/threads/there/task.foo", "task.foo"],
215 ['Release <i title="][">', "https://app.t3.codes/threads/there/t1", "t1"],
216 ["Release [draft]\nnotes", "https://app.t3.codes/threads/there/t1", "t1"],
217 ["Release [draft]", " https://app.t3.codes/threads/there/t1 ", "t1"],
218 ["Release `[` notes", "https://app.t3.codes/threads/there/t1", "t1"],
219 [String.raw`Release [[draft]] \[notes\]`, "<t3-thread://v2/there/t1>", "t1"],
220 ["Release [draft]", "t3-thread://v2/there/task(a)", "task(a)"],
221 ["Release [draft]", "<https://app.t3.codes/threads/there/t1>", "t1"],
222 ])("rewrites the whole link with nested label %s and destination %s", (label, href, threadId) => {
223 expect(
224 replaceThreadLinks(`See [${label}](${href}).`, (link, text) => `{${link.threadId}: ${text}}`),
225 ).toBe(`See {${threadId}: ${label}}.`);
226 });
227
228 it.each(["", "!"])("keeps a thread URL inside an ordinary destination (%j)", (prefix) => {
229 const markdown = `${prefix}[Read [draft] https://app.t3.codes/threads/there/t1](https://example.com)`;
230 expect(replaceThreadLinks(markdown, () => "linked")).toBe(markdown);
231 });
232
233 it("rewrites a thread destination on a nested-bracket image like a flat image", () => {
234 const markdown = "![Release [draft]](https://app.t3.codes/threads/there/t1)";
235 expect(replaceThreadLinks(markdown, (_link, label) => `{${label}}`)).toBe("!{Release [draft]}");
236 });
237
238 it("rewrites a nested label when Markdown nesting exceeds GFM's stack", () => {
239 const quotes = ">".repeat(6000);
240 const markdown = `${quotes} [Release [draft]](https://app.t3.codes/threads/there/t1)`;
241 expect(replaceThreadLinks(markdown, () => "linked")).toBe(`${quotes} linked`);
242 });
243
244 it("turns a v2 link it cannot resolve into plain text, never the raw link", () => {
245 expect(
246 relabelThreadLinks(
247 "<t3-thread://v2/there/t1>, <t3-thread://v2/local/t1>, [Old title](t3-thread://v2/there/t1)",
248 local,
249 () => undefined,
250 ),
251 ).toBe("Thread on another machine, Thread no longer available, Old title");
252 expect(relabelThreadLinks("[Old](t3-thread://v1/t1)", local, () => undefined)).toBe(
253 "[Old](t3-thread://v1/t1)",
254 );
255 expect(relabelThreadLinks("See <t3-thread://v1/gone>", local, () => undefined, japanese)).toBe(
256 "See スレッドは利用できなくなりました",
257 );
258 });
259
260 it.each(["\r", "\r\n", "\n"])(
261 "keeps BOM-prefixed thread link examples literal with %j line endings",
262 (eol) => {
263 const link = "<t3-thread://v2/local/t>";
264 for (const fence of ["~~~", "```"]) {
265 const example = [`\uFEFF${fence}`, link, fence].join(eol);
266 expect(replaceThreadLinks(`${example}${eol}${link}`, () => "linked")).toBe(
267 `${example}${eol}linked`,
268 );
269 }
270 },
271 );
272
273 it.each([
274 [" ", ""],
275 ["\t", ""],
276 ["> ", "> "],
277 ["- ", ""],
278 ])(
279 "rewrites prose links after an indented code line that looks like a fence (%j)",
280 (indent, prose) => {
281 for (const bom of ["", "\uFEFF"]) {
282 const example = `${bom}${indent}~~~\n${prose.trimEnd()}\n${prose}See `;
283 expect(replaceThreadLinks(`${example}<t3-thread://v2/local/t>`, () => "linked")).toBe(
284 `${example}linked`,
285 );
286 }
287 },
288 );
289
290 it.each([
291 ["a blank line", "Intro\n\n", " ", "~~~", ""],
292 ["an indented heading", "Intro\n # Example\n", " ", "~~~", ""],
293 ["a closed fence", "Intro\n```\nexample\n```\n", " ", "~~~", ""],
294 ["a literal list marker", "# Example\n", " ", "- ```md", ""],
295 ["a heading in a quote", "> # Example\n", "> ", "~~~", "> "],
296 ])(
297 "keeps indented code literal and rewrites prose after %s",
298 (_name, before, indent, fence, quote) => {
299 const inside = "<t3-thread://v2/local/code>";
300 const outside = "<t3-thread://v2/local/prose>";
301 const example = `${before}${indent}${fence}\n${indent}${inside}\n${quote.trimEnd()}\n${quote}See `;
302 expect(replaceThreadLinks(`${example}${outside}`, () => "linked")).toBe(`${example}linked`);
303 },
304 );
305
306 it.each([
307 ["a paragraph with four spaces", "Intro\n ~~~"],
308 ["a paragraph with a tab", "Intro\n\t```"],
309 ["a list paragraph", "- Intro\n ~~~"],
310 ["an HTML block", "<div>\n ~~~\n</div>"],
311 ["deeply nested quotes", ">".repeat(6000) + " text\n\n ~~~"],
312 ])("rewrites the prose link after %s", (_name, before) => {
313 const prose = `${before}\n\nSee `;
314 expect(replaceThreadLinks(`${prose}<t3-thread://v2/local/prose>`, () => "linked")).toBe(
315 `${prose}linked`,
316 );
317 });
318
319 it("rewrites a link in footnote prose before an indented fence", () => {
320 const footnote = "Note[^n].\n\n[^n]: note\n\n See ";
321 expect(
322 replaceThreadLinks(`${footnote}<t3-thread://v2/local/prose>\n\n ~~~`, () => "linked"),
323 ).toBe(`${footnote}linked\n\n ~~~`);
324 });
325
326 it.each([
327 ["a paragraph code span", "Intro\n ```\n <t3-thread://v2/local/code>\n ```"],
328 [
329 "a fence with over-indented markers",
330 "~~~\n ~~~\n ~~~\n<t3-thread://v2/local/code>\n~~~",
331 ],
332 [
333 "a fence in a footnote",
334 "Note[^n].\n\n[^n]: note\n\n ~~~\n <t3-thread://v2/local/code>\n ~~~",
335 ],
336 ])("keeps links literal inside %s and rewrites the link after it", (_name, code) => {
337 const prose = `${code}\n\nSee `;
338 expect(replaceThreadLinks(`${prose}<t3-thread://v2/local/prose>`, () => "linked")).toBe(
339 `${prose}linked`,
340 );
341 });
342
343 it.each([
344 ["4 spaces", " ```md\n <t3-thread://v1/abc>\n ```", ""],
345 ["tab", "\t```md\n\t<t3-thread://v1/abc>\n\t```", ""],
346 ["list + 5 spaces", "- ```md\n <t3-thread://v1/abc>\n ```", ""],
347 ["nested list", "- a\n - ```md\n <t3-thread://v1/abc>\n ```", ""],
348 ["nested list with tab", "-\t- ~~~\n <t3-thread://v1/abc>", ""],
349 ["quote + 5 spaces", "> ```md\n> <t3-thread://v1/abc>\n> ```", "> "],
350 [
351 "spaced nested quote + 5 spaces",
352 "> > ```md\n> > <t3-thread://v1/abc>",
353 "> > ",
354 ],
355 ["quote + list + 5 spaces", "> - ```md\n> <t3-thread://v1/abc>\n> ```", "> "],
356 ["quote + space + tab + list", "> \t- ```md\n> <t3-thread://v1/abc>", "> "],
357 [
358 "quote + list after para",
359 "> para\n> - ```md\n> <t3-thread://v1/abc>\n> ```",
360 "> ",
361 ],
362 ["1. after paragraph", "Intro\n1. ```md\n <t3-thread://v1/abc>\n ```", ""],
363 ["ordered list >= 2 after blank", "Intro\n\n2. ```md\n <t3-thread://v1/abc>", ""],
364 [
365 "quote after blank line past closer",
366 "Example\n\n> ~~~\n> ~~~\n> <t3-thread://v1/abc>",
367 "> ",
368 ],
369 ["quote after autolink", "<https://example.com>\n> ~~~\n> <t3-thread://v1/abc>", "> "],
370 ["blank line inside indented code", " ```md\n\n <t3-thread://v1/abc>", ""],
371 ["quote after indented code", " ```md\n> ```\n> <t3-thread://v1/abc>", "> "],
372 ["4 spaces after closer", " ```md\n a\n ```\n <t3-thread://v1/abc>", ""],
373 ["4 spaces with U+2028", " ```\u2028<t3-thread://v1/t1>```", ""],
374 ["hosted link", " ```\n https://app.t3.codes/threads/env/thr\n ```", ""],
375 ])(
376 "keeps links inside fence-looking indented code blocks literal (%s)",
377 (_name, block, prose) => {
378 expect(replaceThreadLinks(block, () => "linked")).toBe(block);
379 const after = `${block}\n${prose.trimEnd()}\n${prose}See `;
380 expect(replaceThreadLinks(`${after}<t3-thread://v2/local/t>`, () => "linked")).toBe(
381 `${after}linked`,
382 );
383 },
384 );
385
386 it.each([
387 ['<span title="`">note</span>', "`code`"],
388 [
389 '<span title="` > [Hidden](t3-thread://v2/env/attribute)">note</span>',
390 "`[Hidden](t3-thread://v2/env/code)`",
391 ],
392 ['<div title="``">\n', "`[Hidden](t3-thread://v2/env/code)`"],
393 ])("rewrites links after HTML attribute backticks (%s)", (html, code) => {
394 const markdown = `${html} [Thread](t3-thread://v2/env/id) ${code}`;
395 expect(replaceThreadLinks(markdown, (link, label) => `{${link.threadId}: ${label}}`)).toBe(
396 `${html} {id: Thread} ${code}`,
397 );
398 });
399
400 it("keeps an escaped HTML opener's backtick as a code span", () => {
401 const markdown = '\\<span title="`"> [Thread](t3-thread://v2/env/id) `';
402 expect(replaceThreadLinks(markdown, () => "chip")).toBe(markdown);
403 });
404
405 it("leaves tag-like text inside a fence unmasked", () => {
406 const markdown = '~~~\n<span title="`\n~~~\n[Live](t3-thread://v2/env/live) `">';
407 expect(replaceThreadLinks(markdown, (link) => `{${link.threadId}}`)).toBe(
408 '~~~\n<span title="`\n~~~\n{live} `">',
409 );
410 });
411
412 it("leaves tag-like text inside a code span unmasked", () => {
413 const markdown = '`<span title="`"> [Live](t3-thread://v2/env/live) `x`';
414 expect(replaceThreadLinks(markdown, (link) => `{${link.threadId}}`)).toBe(
415 '`<span title="`"> {live} `x`',
416 );
417 });
418
419 it("leaves links inside code spans and fences as written", () => {
420 const markdown = [
421 "Live [old](t3-thread://v1/t1), literal `[old](t3-thread://v1/t1)`.",
422 "```md",
423 "<t3-thread://v2/local/t1>",
424 "```",
425 "After <t3-thread://v2/local/t1>",
426 ].join("\n");
427 expect(relabelThreadLinks(markdown, local, () => "New")).toBe(
428 [
429 "Live [New](t3-thread://v1/t1), literal `[old](t3-thread://v1/t1)`.",
430 "```md",
431 "<t3-thread://v2/local/t1>",
432 "```",
433 "After [New](t3-thread://v2/local/t1)",
434 ].join("\n"),
435 );
436 const nested = [
437 "> > ```md",
438 ">> <t3-thread://v2/local/t1>",
439 ">>```",
440 "> > <t3-thread://v2/local/t1>",
441 ];
442 expect(relabelThreadLinks(nested.join("\n"), local, () => "New")).toBe(
443 [...nested.slice(0, 3), "> > [New](t3-thread://v2/local/t1)"].join("\n"),
444 );
445 const deepNested = "> > > > > ```\n> > > > > <t3-thread://v2/local/t1> ```";
446 expect(relabelThreadLinks(deepNested, local, () => "New")).toBe(deepNested);
447 const labels: Array<string | undefined> = [];
448 const separated = "[Label\u2028> > example](t3-thread://v1/t1)";
449 expect(replaceThreadLinks(separated, (_link, label) => void labels.push(label))).toBe(
450 separated,
451 );
452 expect(labels).toEqual(["Label\u2028> > example"]);
453 for (const escaped of ["\\``<t3-thread://v2/env-1/t1>`", "\\```<t3-thread://v2/env-1/t1>``"]) {
454 expect(threadLinkRefs(escaped, local)).toEqual([]);
455 }
456 const indented = " <t3-thread://v2/local/demo>\n\nSee <t3-thread://v2/local/prose>";
457 expect(threadLinkRefs(indented, local)).toEqual([ref("local", "prose")]);
458 expect(relabelThreadLinks(indented, local, () => "New")).toBe(
459 " <t3-thread://v2/local/demo>\n\nSee [New](t3-thread://v2/local/prose)",
460 );
461 expect(relabelThreadLinks("\t<t3-thread://v2/local/demo>", local, () => "New")).toBe(
462 "\t<t3-thread://v2/local/demo>",
463 );
464 expect(relabelThreadLinks("> <t3-thread://v2/local/demo>", local, () => "New")).toBe(
465 "> <t3-thread://v2/local/demo>",
466 );
467 expect(relabelThreadLinks("Intro\n <t3-thread://v2/local/prose>", local, () => "New")).toBe(
468 "Intro\n [New](t3-thread://v2/local/prose)",
469 );
470 });
471
472 it("ends code where CommonMark does, so a link after it stays live", () => {
473 const after = "See <t3-thread://v2/env-1/t1>";
474 const hidden = "<t3-thread://v2/local/in-code>";
475 for (const markdown of [
476 ["```ts", 'const fence = "```";', hidden, "```", after],
477 ["> ```ts", '> const fence = "```";', `> ${hidden}`, "> ```", `> ${after}`],
478 ["> ```", ` > ${hidden}`, "> ```", after],
479 ["- ```bash", " echo hi", " ```", "", after],
480 ["- ```text", ` ${hidden}`, "", after],
481 ["- item", "", " ```text", ` ${hidden}`, "", after],
482 ["[^note]: - ```text", " https://app.t3.codes/threads/local/in-code", "", after],
483 [
484 "[^outer]: [^inner]: - ```text",
485 " https://app.t3.codes/threads/local/in-code",
486 "",
487 after,
488 ],
489 ["- > ```md", ` > ${hidden}`, " > ```", "", after],
490 [">> ```md", `> > ${hidden}`, ">> ```", `> ${after}`],
491 ["> > ~~~", `>> ${hidden}`, ">> ~~~", after],
492 ["1. Run:", "", " ```bash", ' echo "```"', ` ${hidden}`, " ```", "", after],
493 ["````md", "```", hidden, "````", after],
494 ["Use ~~~ to mark it.", after],
495 ["> para", "> ~~~", `> ${after}`],
496 ["> para", `> ~~~ ${after}`],
497 ["- > para", " > ```md", ` > ${after}`],
498 [`Intro\u2028- ~~~ ${after}`],
499 ["Intro", `2. ~~~ ${after}`],
500 ["Intro", `2. - ~~~ ${after}`],
501 [">\t- ```md", `> ${after}`],
502 ["> para", "lazy", "> ~~~", `> ${after}`],
503 ["> para", "> 2. >", `> 2. ~~~ ${after}`],
504 ["> para\r", "> ~~~\r", `> ${after}`],
505 [`> para\r\r> ~~~\r> ${hidden}\r> ${after}`],
506 ["para", " - ```", ` ${after}`],
507 ["para", " - ```", ` ${after}`],
508 [" ~~~", `- ${after}`],
509 [" ~~~md", " ~~~", " ~~~", after],
510 ["- item", " > ~~~", ` > ${hidden}`, ` ${after}`],
511 ["10. > ```md", ` > ${hidden} \`\`\``, "", after],
512 [" - > ```md", ` > ${hidden} \`\`\``, "", after],
513 ["> - Run this:", ">", "> ```bash", "> echo hi", ">", "> ```", `> ${after}`],
514 ["Example", "", "> ~~~", ">\t\t~~~", `> ${hidden}`, ">\t\t~~~", `> ${after}`],
515 [after, "> ~~~", `> ${hidden}`],
516 [`1. \`\`\`md ${hidden}`, ` \t${after}`],
517 ["> ```md", `> \t${after}`],
518 ["> ```md", `>\t ${after}`],
519 ["```" + hidden + "``` then", after],
520 ["Use ```example", hidden, "end``` then", after],
521 ["Stray ` tick", "", after, "and `code`"],
522 ["Stray ` tick", `# ${after}`, "and `code`"],
523 ["Stray ` tick", `- ${after}`, "and `code`"],
524 ["Stray ` tick", `> ${after} and \`code\``],
525 ["> Stray ` tick", `> > ${after} and \`code\``],
526 ["- Stray ` tick", ` > ${after} and \`code\``],
527 ["> Use `example", `> ${hidden} end\``, `> ${after}`],
528 ["> > Use `example", `> > ${hidden} end\``, `> > ${after}`],
529 ["> Use `example", `${hidden} end\``, after],
530 ["Use `example", ` > ${hidden} end\``, after],
531 ["> Use `example", `> > ${hidden} end\``, `> ${after}`],
532 ["> Intro", "Use `example", `> ${hidden} end\``, `> ${after}`],
533 ["> > Intro", "> Use `example", `> > ${hidden} end\``, `> > ${after}`],
534 ["1. Stray ` tick", ` > ${after} and \`code\``],
535 ["1. Intro", "", " Stray ` tick", ` > ${after} and \`code\``],
536 ["- Intro", "", "Use `example", ` > ${hidden} end\``, after],
537 ...["- - -", "* \t* *", "___", "===", "-"].flatMap((boundary) => [
538 ["Stray ` tick", boundary, `${after} and \`code\``],
539 ["> Stray ` tick", `> ${boundary}`, `> ${after} and \`code\``],
540 ]),
541 ["Stray ` tick\r", " ---\r", `${after} and \`code\``],
542 ["> Stray ` tick", "---", `${after} and \`code\``],
543 ["Use `example", "```" + hidden + "`", after],
544 ["\\\\``" + after + "`"],
545 [`Use \`example\r${hidden} end\`. Stray \` tick\r\r${after}\rand \`code\``],
546 [`Stray \` tick\r# ${after}\rand \`code\``],
547 ]) {
548 const joined = markdown.join("\n");
549 expect(threadLinkRefs(joined, local)).toEqual([ref("env-1", "t1")]);
550 expect(relabelThreadLinks(joined, local, () => "New")).toBe(
551 joined.replace("<t3-thread://v2/env-1/t1>", "[New](t3-thread://v2/env-1/t1)"),
552 );
553 }
554 });
555
556 it("keeps multiline code literal when a line only resembles a block boundary", () => {
557 for (const markdown of [
558 ...["--- text", "== =", "-_*", " ==="].map((line) => ["Use `example", line]),
559 ["> Use `example", "> ---"],
560 ["> Use `example", "==="],
561 ]) {
562 const source = [...markdown, "<t3-thread://v2/local/t1> end`"].join("\n");
563 expect(threadLinkRefs(source, local)).toEqual([]);
564 expect(relabelThreadLinks(source, local, () => "New")).toBe(source);
565 }
566 });
567
568 it("lists the threads a message's links can name, outside code", () => {
569 expect(
570 threadLinkRefs(
571 "<t3-thread://v2/there/t1> [a](t3-thread://v1/t%3A2) `<t3-thread://v2/code/t3>`",
572 local,
573 ),
574 ).toEqual([ref("there", "t1"), ref("local", "t%3A2"), ref("local", "t:2")]);
575 });
576
577 it("lists a message's thread links on runtimes whose matchAll omits named groups, such as Hermes", () => {
578 const matchAll = String.prototype.matchAll;
579 using _hermes = vi.spyOn(String.prototype, "matchAll").mockImplementation(function (
580 this: string,
581 regexp: RegExp,
582 ) {
583 return matchAll.call(this, regexp).map((match) => {
584 delete match.groups;
585 return match;
586 });
587 });
588 expect(threadLinkRefs("<t3-thread://v2/local/t1> [a](t3-thread://v2/there/t2)", local)).toEqual(
589 [ref("local", "t1"), ref("there", "t2")],
590 );
591 });
592
593 it("writes a titleless autolink that opens that exact thread", () => {
594 const link = formatThreadLink(ref("env-1", "thread:delegated-task:mcp%3A1"));
595 expect(link).toBe("<t3-thread://v2/env-1/thread:delegated-task:mcp%3A1>");
596 expect(parseThreadLinkHref(link.slice(1, -1))).toEqual(
597 ref("env-1", "thread:delegated-task:mcp%3A1"),
598 );
599 });
600
601 it("formats a label that would otherwise break the Markdown link", () => {
602 expect(formatThreadLink(ref("e", "t1"), "Fix [ci] \\ build")).toBe(
603 "[Fix ci build](t3-thread://v2/e/t1)",
604 );
605 expect(formatThreadLink(ref("e", "t1"), " ] ")).toBe("<t3-thread://v2/e/t1>");
606 });
607});
608
609describe("hosted thread links", () => {
610 it("escapes every id character a sentence or path could claim, and reads it back", () => {
611 const thread = ref("env.1", "thread:delegated/mcp%3A1.");
612 const link = hostedThreadLink(thread);
613 expect(link).toBe("https://app.t3.codes/threads/env%2E1/thread%3Adelegated%2Fmcp%253A1%2E");
614 expect(parseThreadLinkHref(link)).toEqual({ ...thread, hosted: true });
615 expect(hostedThreadLink(thread, "https://preview.t3.codes/")).toMatch(
616 /^https:\/\/preview\.t3\.codes\/threads\//,
617 );
618
619 const literal = ref("local", "task%3A1");
620 const literalUrl = hostedThreadLink(literal);
621 expect(literalUrl).toBe("https://app.t3.codes/threads/local/task%253A1");
622 expect(threadLinkCandidates(parseThreadLinkHref(literalUrl)!, local)).toEqual([literal]);
623 expect(threadLinkRefs(literalUrl, local)).toEqual([literal]);
624 expect(relabelThreadLinks(literalUrl, local, titlesIn({ local: { "task:1": "Other" } }))).toBe(
625 "Thread no longer available",
626 );
627 expect(
628 relabelThreadLinks(
629 literalUrl,
630 local,
631 titlesIn({ local: { "task%3A1": "Literal", "task:1": "Other" } }),
632 ),
633 ).toBe("[Literal](t3-thread://v2/local/task%3A1)");
634 });
635
636 it("reads only a bare thread path on the hosted app", () => {
637 expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1/thread-1")).toEqual({
638 ...ref("env-1", "thread-1"),
639 hosted: true,
640 });
641 expect(parseThreadLinkHref("https://app.t3.codes/threads/env.1/task.foo")).toEqual({
642 ...ref("env.1", "task.foo"),
643 hosted: true,
644 });
645 expect(parseThreadLinkHref("https://app.t3.codes/threads/local/task.")).toBeNull();
646 expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1/thread-1?prompt=go")).toBeNull();
647 expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1/thread-1/extra")).toBeNull();
648 expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1")).toBeNull();
649 expect(parseThreadLinkHref("https://app.t3.codes/env-1/thread-1")).toBeNull();
650 expect(parseThreadLinkHref("https://evil.test/threads/env-1/thread-1")).toBeNull();
651 });
652
653 it("writes a copied link a reader can follow, labeled when it has a title", () => {
654 expect(formatHostedThreadLink(ref("e", "t1"), "Fix [ci]")).toBe(
655 "[Fix ci](https://app.t3.codes/threads/e/t1)",
656 );
657 expect(formatHostedThreadLink(ref("e", "t1"), " ")).toBe("https://app.t3.codes/threads/e/t1");
658 });
659
660 it("titles hosted links in every Markdown form and writes them as v2 links", () => {
661 const title = titlesIn({ there: { t1: "There" }, local: { "task.foo": "Dotted" } });
662 expect(
663 relabelThreadLinks(
664 [
665 "See https://app.t3.codes/threads/there/t1.",
666 "See https://app.t3.codes/threads/local/task.foo.",
667 "[old](https://app.t3.codes/threads/there/t1)",
668 "<https://app.t3.codes/threads/there/t1>",
669 "`https://app.t3.codes/threads/there/t1`",
670 "https://app.t3.codes/threads/there/t1?prompt=go",
671 "https://app.t3.codes/threads/local/task.foo?prompt=go",
672 "https://app.t3.codes/threads/local/task.foo/extra",
673 ].join("\n"),
674 local,
675 title,
676 ),
677 ).toBe(
678 [
679 "See [There](t3-thread://v2/there/t1).",
680 "See [Dotted](t3-thread://v2/local/task.foo).",
681 "[There](t3-thread://v2/there/t1)",
682 "[There](t3-thread://v2/there/t1)",
683 "`https://app.t3.codes/threads/there/t1`",
684 "https://app.t3.codes/threads/there/t1?prompt=go",
685 "https://app.t3.codes/threads/local/task.foo?prompt=go",
686 "https://app.t3.codes/threads/local/task.foo/extra",
687 ].join("\n"),
688 );
689 expect(
690 relabelThreadLinks("https://app.t3.codes/threads/there/t1", local, () => undefined),
691 ).toBe("Thread on another machine");
692 expect(threadLinkRefs("Open https://app.t3.codes/threads/there/t%3A1", local)).toEqual([
693 ref("there", "t:1"),
694 ]);
695 expect(threadLinkRefs("https://app.t3.codes/threads/local/task.foo", local)).toEqual([
696 ref("local", "task.foo"),
697 ]);
698 expect(threadLinkRefs("https://app.t3.codes/threads/local/task.foo?prompt=go", local)).toEqual(
699 [],
700 );
701 });
702
703 it("leaves a hosted link that is part of another link as written", () => {
704 const hosted = "https://app.t3.codes/threads/there/t1";
705 const relabeled = "[There](t3-thread://v2/there/t1)";
706 const title = titlesIn({ there: { t1: "There" } });
707 for (const [markdown, expected] of [
708 [`https://example.com/?next=${hosted}`],
709 [`[Example](https://example.com/?next=${hosted})`],
710 [`[ ${hosted} ](https://example.com)`],
711 [`[${hosted}](<https://example.com/a b> "Title")`],
712 [`[${hosted}]( https://example.com "Example")`],
713 [`[${hosted}](\n<https://example.com>)`],
714 [`[${hosted}]( "two words")`],
715 [`[${hosted}](<https://example.com/a\\>b>)`],
716 [
717 `[${hosted}]( https://example.com/a(b(c))) ${hosted}`,
718 `[${hosted}]( https://example.com/a(b(c))) ${relabeled}`,
719 ],
720 [
721 `[${hosted}](https://example.com/a\\(b) ${hosted}`,
722 `[${hosted}](https://example.com/a\\(b) ${relabeled}`,
723 ],
724 [
725 `[${hosted}](https://example.com/a(b ${hosted})`,
726 `[${relabeled}](https://example.com/a(b ${relabeled})`,
727 ],
728 [
729 `[${hosted}]( https://example.com) ${hosted}`,
730 `[${hosted}]( https://example.com) ${relabeled}`,
731 ],
732 [`[${hosted}](t3-thread://v2/local/id "Title")`],
733 [`[a](https://example.com/x_(y)) ${hosted}`, `[a](https://example.com/x_(y)) ${relabeled}`],
734 [`(${hosted}) **${hosted}**`, `(${relabeled}) **${relabeled}**`],
735 [`[[[ [old](${hosted})`, `[[[ ${relabeled}`],
736 [`\\\\[old](${hosted})`, `\\\\${relabeled}`],
737 [`\\\\\\\\[old](${hosted})`, `\\\\\\\\${relabeled}`],
738 [`\\[old](${hosted})`, `\\[old](${relabeled})`],
739 [`\\[ ${hosted} ](https://example.com)`, `\\[ ${relabeled} ](https://example.com)`],
740 ["\\[old](t3-thread://v2/there/t1) \\<t3-thread://v2/there/t1>"],
741 ] as const) {
742 expect(relabelThreadLinks(markdown, local, title)).toBe(expected ?? markdown);
743 expect(threadLinkRefs(markdown, local)).toEqual(
744 expected === undefined ? [] : [ref("there", "t1")],
745 );
746 }
747 });
748
749 it("rewrites a hosted link after many unclosed website links", () => {
750 const openers = "[x](".repeat(50_000);
751 expect(replaceThreadLinks(`${openers} <t3-thread://v2/local/prose>`, () => "linked")).toBe(
752 `${openers} linked`,
753 );
754 });
755
756 it("keeps Markdown reference link definitions intact when relabeling", () => {
757 const hosted = "https://app.t3.codes/threads/local/demo";
758 for (const markdown of [
759 `[Review][thread]\n\n[thread]: ${hosted}`,
760 `[Review][thread]\n\n[thread]:${hosted}`,
761 `[Review][thread]\n\n[thread]: <${hosted}>`,
762 `[Review][thread]\n\n[thread]: <t3-thread://v2/local/demo>`,
763 `[Review][thread]\n\n[thread]:\n ${hosted}`,
764 `[Review][thread]\n\n [thread]: ${hosted} "Demo"`,
765 `> [Review][thread]\n>\n> [thread]: ${hosted}`,
766 ]) {
767 for (const title of [() => "Demo", () => undefined]) {
768 expect(relabelThreadLinks(markdown, local, title)).toBe(markdown);
769 }
770 }
771
772 const withLiveAfter = `[Review][thread]\n\n[thread]: ${hosted}\n\nSee ${hosted}`;
773 expect(relabelThreadLinks(withLiveAfter, local, () => "Demo")).toBe(
774 `[Review][thread]\n\n[thread]: ${hosted}\n\nSee [Demo](t3-thread://v2/local/demo)`,
775 );
776
777 for (const markdown of [
778 `[${hosted}][site]\n\n[site]: https://example.com`,
779 `![${hosted}][site]\n\n[site]: https://example.com`,
780 ]) {
781 expect(relabelThreadLinks(markdown, local, () => "Demo")).toBe(markdown);
782 expect(threadLinkRefs(markdown, local)).toEqual([]);
783 }
784 const labelWithLiveAfter = `[${hosted}][site]\n\n[site]: https://example.com\n\n${hosted}`;
785 expect(relabelThreadLinks(labelWithLiveAfter, local, () => "Demo")).toBe(
786 `[${hosted}][site]\n\n[site]: https://example.com\n\n[Demo](t3-thread://v2/local/demo)`,
787 );
788
789 const paragraphContinuation = `Intro\n[thread]: ${hosted}`;
790 expect(relabelThreadLinks(paragraphContinuation, local, () => "Demo")).toBe(
791 `Intro\n[thread]: [Demo](t3-thread://v2/local/demo)`,
792 );
793 });
794
795 it("keeps relabeled links navigable when the thread id contains a space", () => {
796 const linkUrl = (markdown: string) => {
797 const paragraph = unified().use(remarkParse).parse(markdown).children[0];
798 const node = paragraph?.type === "paragraph" ? paragraph.children[0] : undefined;
799 return node?.type === "link" ? node.url : undefined;
800 };
801 const thread = ref("local", "work item");
802 const titles = titlesIn({ local: { "work item": "Review", "work%20item": "Encoded" } });
803
804 const relabeled = relabelThreadLinks(hostedThreadLink(thread), local, titles);
805 expect(parseThreadLinkHref(linkUrl(relabeled) ?? "")).toEqual({ ...thread, hosted: true });
806 expect(threadLinkRefs(relabeled, local)).toEqual([thread]);
807
808 const v1Relabeled = relabelThreadLinks("[old](t3-thread://v1/work%20item)", local, titles);
809 expect(linkUrl(v1Relabeled)).toBe("t3-thread://v1/work%20item");
810 expect(formatThreadLink(v1("work item"))).toBe("<t3-thread://v1/work%20item>");
811 });
812});