Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threadLinks.test.ts

829 lines36.1 KB

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&amp;b", "a&amp;b"],
168 ["<t3-thread://v2/there/a&amp;b>", "a&amp;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&#46;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 ['```<b title="`">', ""],
389 [
390 '<span title="` > [Hidden](t3-thread://v2/env/attribute)">note</span>',
391 "`[Hidden](t3-thread://v2/env/code)`",
392 ],
393 ['<div title="``">\n', "`[Hidden](t3-thread://v2/env/code)`"],
394 ])("rewrites links after HTML attribute backticks (%s)", (html, code) => {
395 const markdown = `${html} [Thread](t3-thread://v2/env/id) ${code}`;
396 expect(replaceThreadLinks(markdown, (link, label) => `{${link.threadId}: ${label}}`)).toBe(
397 `${html} {id: Thread} ${code}`,
398 );
399 });
400​
401 it("keeps code spans inside a raw HTML block literal when a fence follows", () => {
402 const markdown =
403 '<div title="`">\n`[Code](t3-thread://v2/env/code)` [Live](t3-thread://v2/env/live)\n</div>\n\n```\nx\n```';
404 expect(replaceThreadLinks(markdown, (link) => `{${link.threadId}}`)).toBe(
405 markdown.replace("[Live](t3-thread://v2/env/live)", "{live}"),
406 );
407 });
408​
409 it("ends a raw HTML block's code-span search at the block", () => {
410 const markdown =
411 '<script title="`">\n`\n</script>\n[Live](t3-thread://v2/env/live) `\n\n```\nx\n```';
412 expect(replaceThreadLinks(markdown, (link) => `{${link.threadId}}`)).toBe(
413 markdown.replace("[Live](t3-thread://v2/env/live)", "{live}"),
414 );
415 });
416​
417 it("keeps an escaped HTML opener's backtick as a code span", () => {
418 const markdown = '\\<span title="`"> [Thread](t3-thread://v2/env/id) `';
419 expect(replaceThreadLinks(markdown, () => "chip")).toBe(markdown);
420 });
421​
422 it("leaves tag-like text inside a fence unmasked", () => {
423 const markdown = '~~~\n<span title="`\n~~~\n[Live](t3-thread://v2/env/live) `">';
424 expect(replaceThreadLinks(markdown, (link) => `{${link.threadId}}`)).toBe(
425 '~~~\n<span title="`\n~~~\n{live} `">',
426 );
427 });
428​
429 it("leaves tag-like text inside a code span unmasked", () => {
430 const markdown = '`<span title="`"> [Live](t3-thread://v2/env/live) `x`';
431 expect(replaceThreadLinks(markdown, (link) => `{${link.threadId}}`)).toBe(
432 '`<span title="`"> {live} `x`',
433 );
434 });
435​
436 it("leaves links inside code spans and fences as written", () => {
437 const markdown = [
438 "Live [old](t3-thread://v1/t1), literal `[old](t3-thread://v1/t1)`.",
439 "```md",
440 "<t3-thread://v2/local/t1>",
441 "```",
442 "After <t3-thread://v2/local/t1>",
443 ].join("\n");
444 expect(relabelThreadLinks(markdown, local, () => "New")).toBe(
445 [
446 "Live [New](t3-thread://v1/t1), literal `[old](t3-thread://v1/t1)`.",
447 "```md",
448 "<t3-thread://v2/local/t1>",
449 "```",
450 "After [New](t3-thread://v2/local/t1)",
451 ].join("\n"),
452 );
453 const nested = [
454 "> > ```md",
455 ">> <t3-thread://v2/local/t1>",
456 ">>```",
457 "> > <t3-thread://v2/local/t1>",
458 ];
459 expect(relabelThreadLinks(nested.join("\n"), local, () => "New")).toBe(
460 [...nested.slice(0, 3), "> > [New](t3-thread://v2/local/t1)"].join("\n"),
461 );
462 const deepNested = "> > > > > ```\n> > > > > <t3-thread://v2/local/t1> ```";
463 expect(relabelThreadLinks(deepNested, local, () => "New")).toBe(deepNested);
464 const labels: Array<string | undefined> = [];
465 const separated = "[Label\u2028> > example](t3-thread://v1/t1)";
466 expect(replaceThreadLinks(separated, (_link, label) => void labels.push(label))).toBe(
467 separated,
468 );
469 expect(labels).toEqual(["Label\u2028> > example"]);
470 for (const escaped of ["\\``<t3-thread://v2/env-1/t1>`", "\\```<t3-thread://v2/env-1/t1>``"]) {
471 expect(threadLinkRefs(escaped, local)).toEqual([]);
472 }
473 const indented = " <t3-thread://v2/local/demo>\n\nSee <t3-thread://v2/local/prose>";
474 expect(threadLinkRefs(indented, local)).toEqual([ref("local", "prose")]);
475 expect(relabelThreadLinks(indented, local, () => "New")).toBe(
476 " <t3-thread://v2/local/demo>\n\nSee [New](t3-thread://v2/local/prose)",
477 );
478 expect(relabelThreadLinks("\t<t3-thread://v2/local/demo>", local, () => "New")).toBe(
479 "\t<t3-thread://v2/local/demo>",
480 );
481 expect(relabelThreadLinks("> <t3-thread://v2/local/demo>", local, () => "New")).toBe(
482 "> <t3-thread://v2/local/demo>",
483 );
484 expect(relabelThreadLinks("Intro\n <t3-thread://v2/local/prose>", local, () => "New")).toBe(
485 "Intro\n [New](t3-thread://v2/local/prose)",
486 );
487 });
488​
489 it("ends code where CommonMark does, so a link after it stays live", () => {
490 const after = "See <t3-thread://v2/env-1/t1>";
491 const hidden = "<t3-thread://v2/local/in-code>";
492 for (const markdown of [
493 ["```ts", 'const fence = "```";', hidden, "```", after],
494 ["> ```ts", '> const fence = "```";', `> ${hidden}`, "> ```", `> ${after}`],
495 ["> ```", ` > ${hidden}`, "> ```", after],
496 ["- ```bash", " echo hi", " ```", "", after],
497 ["- ```text", ` ${hidden}`, "", after],
498 ["- item", "", " ```text", ` ${hidden}`, "", after],
499 ["[^note]: - ```text", " https://app.t3.codes/threads/local/in-code", "", after],
500 [
501 "[^outer]: [^inner]: - ```text",
502 " https://app.t3.codes/threads/local/in-code",
503 "",
504 after,
505 ],
506 ["- > ```md", ` > ${hidden}`, " > ```", "", after],
507 [">> ```md", `> > ${hidden}`, ">> ```", `> ${after}`],
508 ["> > ~~~", `>> ${hidden}`, ">> ~~~", after],
509 ["1. Run:", "", " ```bash", ' echo "```"', ` ${hidden}`, " ```", "", after],
510 ["````md", "```", hidden, "````", after],
511 ["Use ~~~ to mark it.", after],
512 ["> para", "> ~~~", `> ${after}`],
513 ["> para", `> ~~~ ${after}`],
514 ["- > para", " > ```md", ` > ${after}`],
515 [`Intro\u2028- ~~~ ${after}`],
516 ["Intro", `2. ~~~ ${after}`],
517 ["Intro", `2. - ~~~ ${after}`],
518 [">\t- ```md", `> ${after}`],
519 ["> para", "lazy", "> ~~~", `> ${after}`],
520 ["> para", "> 2. >", `> 2. ~~~ ${after}`],
521 ["> para\r", "> ~~~\r", `> ${after}`],
522 [`> para\r\r> ~~~\r> ${hidden}\r> ${after}`],
523 ["para", " - ```", ` ${after}`],
524 ["para", " - ```", ` ${after}`],
525 [" ~~~", `- ${after}`],
526 [" ~~~md", " ~~~", " ~~~", after],
527 ["- item", " > ~~~", ` > ${hidden}`, ` ${after}`],
528 ["10. > ```md", ` > ${hidden} \`\`\``, "", after],
529 [" - > ```md", ` > ${hidden} \`\`\``, "", after],
530 ["> - Run this:", ">", "> ```bash", "> echo hi", ">", "> ```", `> ${after}`],
531 ["Example", "", "> ~~~", ">\t\t~~~", `> ${hidden}`, ">\t\t~~~", `> ${after}`],
532 [after, "> ~~~", `> ${hidden}`],
533 [`1. \`\`\`md ${hidden}`, ` \t${after}`],
534 ["> ```md", `> \t${after}`],
535 ["> ```md", `>\t ${after}`],
536 ["```" + hidden + "``` then", after],
537 ["Use ```example", hidden, "end``` then", after],
538 ["Stray ` tick", "", after, "and `code`"],
539 ["Stray ` tick", `# ${after}`, "and `code`"],
540 ["Stray ` tick", `- ${after}`, "and `code`"],
541 ["Stray ` tick", `> ${after} and \`code\``],
542 ["> Stray ` tick", `> > ${after} and \`code\``],
543 ["- Stray ` tick", ` > ${after} and \`code\``],
544 ["> Use `example", `> ${hidden} end\``, `> ${after}`],
545 ["> > Use `example", `> > ${hidden} end\``, `> > ${after}`],
546 ["> Use `example", `${hidden} end\``, after],
547 ["Use `example", ` > ${hidden} end\``, after],
548 ["> Use `example", `> > ${hidden} end\``, `> ${after}`],
549 ["> Intro", "Use `example", `> ${hidden} end\``, `> ${after}`],
550 ["> > Intro", "> Use `example", `> > ${hidden} end\``, `> > ${after}`],
551 ["1. Stray ` tick", ` > ${after} and \`code\``],
552 ["1. Intro", "", " Stray ` tick", ` > ${after} and \`code\``],
553 ["- Intro", "", "Use `example", ` > ${hidden} end\``, after],
554 ...["- - -", "* \t* *", "___", "===", "-"].flatMap((boundary) => [
555 ["Stray ` tick", boundary, `${after} and \`code\``],
556 ["> Stray ` tick", `> ${boundary}`, `> ${after} and \`code\``],
557 ]),
558 ["Stray ` tick\r", " ---\r", `${after} and \`code\``],
559 ["> Stray ` tick", "---", `${after} and \`code\``],
560 ["Use `example", "```" + hidden + "`", after],
561 ["\\\\``" + after + "`"],
562 [`Use \`example\r${hidden} end\`. Stray \` tick\r\r${after}\rand \`code\``],
563 [`Stray \` tick\r# ${after}\rand \`code\``],
564 ]) {
565 const joined = markdown.join("\n");
566 expect(threadLinkRefs(joined, local)).toEqual([ref("env-1", "t1")]);
567 expect(relabelThreadLinks(joined, local, () => "New")).toBe(
568 joined.replace("<t3-thread://v2/env-1/t1>", "[New](t3-thread://v2/env-1/t1)"),
569 );
570 }
571 });
572​
573 it("keeps multiline code literal when a line only resembles a block boundary", () => {
574 for (const markdown of [
575 ...["--- text", "== =", "-_*", " ==="].map((line) => ["Use `example", line]),
576 ["> Use `example", "> ---"],
577 ["> Use `example", "==="],
578 ]) {
579 const source = [...markdown, "<t3-thread://v2/local/t1> end`"].join("\n");
580 expect(threadLinkRefs(source, local)).toEqual([]);
581 expect(relabelThreadLinks(source, local, () => "New")).toBe(source);
582 }
583 });
584​
585 it("lists the threads a message's links can name, outside code", () => {
586 expect(
587 threadLinkRefs(
588 "<t3-thread://v2/there/t1> [a](t3-thread://v1/t%3A2) `<t3-thread://v2/code/t3>`",
589 local,
590 ),
591 ).toEqual([ref("there", "t1"), ref("local", "t%3A2"), ref("local", "t:2")]);
592 });
593​
594 it("lists a message's thread links on runtimes whose matchAll omits named groups, such as Hermes", () => {
595 const matchAll = String.prototype.matchAll;
596 using _hermes = vi.spyOn(String.prototype, "matchAll").mockImplementation(function (
597 this: string,
598 regexp: RegExp,
599 ) {
600 return matchAll.call(this, regexp).map((match) => {
601 delete match.groups;
602 return match;
603 });
604 });
605 expect(threadLinkRefs("<t3-thread://v2/local/t1> [a](t3-thread://v2/there/t2)", local)).toEqual(
606 [ref("local", "t1"), ref("there", "t2")],
607 );
608 });
609​
610 it("writes a titleless autolink that opens that exact thread", () => {
611 const link = formatThreadLink(ref("env-1", "thread:delegated-task:mcp%3A1"));
612 expect(link).toBe("<t3-thread://v2/env-1/thread:delegated-task:mcp%3A1>");
613 expect(parseThreadLinkHref(link.slice(1, -1))).toEqual(
614 ref("env-1", "thread:delegated-task:mcp%3A1"),
615 );
616 });
617​
618 it("formats a label that would otherwise break the Markdown link", () => {
619 expect(formatThreadLink(ref("e", "t1"), "Fix [ci] \\ build")).toBe(
620 "[Fix ci build](t3-thread://v2/e/t1)",
621 );
622 expect(formatThreadLink(ref("e", "t1"), " ] ")).toBe("<t3-thread://v2/e/t1>");
623 });
624});
625​
626describe("hosted thread links", () => {
627 it("escapes every id character a sentence or path could claim, and reads it back", () => {
628 const thread = ref("env.1", "thread:delegated/mcp%3A1.");
629 const link = hostedThreadLink(thread);
630 expect(link).toBe("https://app.t3.codes/threads/env%2E1/thread%3Adelegated%2Fmcp%253A1%2E");
631 expect(parseThreadLinkHref(link)).toEqual({ ...thread, hosted: true });
632 expect(hostedThreadLink(thread, "https://preview.t3.codes/")).toMatch(
633 /^https:\/\/preview\.t3\.codes\/threads\//,
634 );
635​
636 const literal = ref("local", "task%3A1");
637 const literalUrl = hostedThreadLink(literal);
638 expect(literalUrl).toBe("https://app.t3.codes/threads/local/task%253A1");
639 expect(threadLinkCandidates(parseThreadLinkHref(literalUrl)!, local)).toEqual([literal]);
640 expect(threadLinkRefs(literalUrl, local)).toEqual([literal]);
641 expect(relabelThreadLinks(literalUrl, local, titlesIn({ local: { "task:1": "Other" } }))).toBe(
642 "Thread no longer available",
643 );
644 expect(
645 relabelThreadLinks(
646 literalUrl,
647 local,
648 titlesIn({ local: { "task%3A1": "Literal", "task:1": "Other" } }),
649 ),
650 ).toBe("[Literal](t3-thread://v2/local/task%3A1)");
651 });
652​
653 it("reads only a bare thread path on the hosted app", () => {
654 expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1/thread-1")).toEqual({
655 ...ref("env-1", "thread-1"),
656 hosted: true,
657 });
658 expect(parseThreadLinkHref("https://app.t3.codes/threads/env.1/task.foo")).toEqual({
659 ...ref("env.1", "task.foo"),
660 hosted: true,
661 });
662 expect(parseThreadLinkHref("https://app.t3.codes/threads/local/task.")).toBeNull();
663 expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1/thread-1?prompt=go")).toBeNull();
664 expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1/thread-1/extra")).toBeNull();
665 expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1")).toBeNull();
666 expect(parseThreadLinkHref("https://app.t3.codes/env-1/thread-1")).toBeNull();
667 expect(parseThreadLinkHref("https://evil.test/threads/env-1/thread-1")).toBeNull();
668 });
669​
670 it("writes a copied link a reader can follow, labeled when it has a title", () => {
671 expect(formatHostedThreadLink(ref("e", "t1"), "Fix [ci]")).toBe(
672 "[Fix ci](https://app.t3.codes/threads/e/t1)",
673 );
674 expect(formatHostedThreadLink(ref("e", "t1"), " ")).toBe("https://app.t3.codes/threads/e/t1");
675 });
676​
677 it("titles hosted links in every Markdown form and writes them as v2 links", () => {
678 const title = titlesIn({ there: { t1: "There" }, local: { "task.foo": "Dotted" } });
679 expect(
680 relabelThreadLinks(
681 [
682 "See https://app.t3.codes/threads/there/t1.",
683 "See https://app.t3.codes/threads/local/task.foo.",
684 "[old](https://app.t3.codes/threads/there/t1)",
685 "<https://app.t3.codes/threads/there/t1>",
686 "`https://app.t3.codes/threads/there/t1`",
687 "https://app.t3.codes/threads/there/t1?prompt=go",
688 "https://app.t3.codes/threads/local/task.foo?prompt=go",
689 "https://app.t3.codes/threads/local/task.foo/extra",
690 ].join("\n"),
691 local,
692 title,
693 ),
694 ).toBe(
695 [
696 "See [There](t3-thread://v2/there/t1).",
697 "See [Dotted](t3-thread://v2/local/task.foo).",
698 "[There](t3-thread://v2/there/t1)",
699 "[There](t3-thread://v2/there/t1)",
700 "`https://app.t3.codes/threads/there/t1`",
701 "https://app.t3.codes/threads/there/t1?prompt=go",
702 "https://app.t3.codes/threads/local/task.foo?prompt=go",
703 "https://app.t3.codes/threads/local/task.foo/extra",
704 ].join("\n"),
705 );
706 expect(
707 relabelThreadLinks("https://app.t3.codes/threads/there/t1", local, () => undefined),
708 ).toBe("Thread on another machine");
709 expect(threadLinkRefs("Open https://app.t3.codes/threads/there/t%3A1", local)).toEqual([
710 ref("there", "t:1"),
711 ]);
712 expect(threadLinkRefs("https://app.t3.codes/threads/local/task.foo", local)).toEqual([
713 ref("local", "task.foo"),
714 ]);
715 expect(threadLinkRefs("https://app.t3.codes/threads/local/task.foo?prompt=go", local)).toEqual(
716 [],
717 );
718 });
719​
720 it("leaves a hosted link that is part of another link as written", () => {
721 const hosted = "https://app.t3.codes/threads/there/t1";
722 const relabeled = "[There](t3-thread://v2/there/t1)";
723 const title = titlesIn({ there: { t1: "There" } });
724 for (const [markdown, expected] of [
725 [`https://example.com/?next=${hosted}`],
726 [`[Example](https://example.com/?next=${hosted})`],
727 [`[ ${hosted} ](https://example.com)`],
728 [`[${hosted}](<https://example.com/a b> "Title")`],
729 [`[${hosted}]( https://example.com "Example")`],
730 [`[${hosted}](\n<https://example.com>)`],
731 [`[${hosted}]( "two words")`],
732 [`[${hosted}](<https://example.com/a\\>b>)`],
733 [
734 `[${hosted}]( https://example.com/a(b(c))) ${hosted}`,
735 `[${hosted}]( https://example.com/a(b(c))) ${relabeled}`,
736 ],
737 [
738 `[${hosted}](https://example.com/a\\(b) ${hosted}`,
739 `[${hosted}](https://example.com/a\\(b) ${relabeled}`,
740 ],
741 [
742 `[${hosted}](https://example.com/a(b ${hosted})`,
743 `[${relabeled}](https://example.com/a(b ${relabeled})`,
744 ],
745 [
746 `[${hosted}]( https://example.com) ${hosted}`,
747 `[${hosted}]( https://example.com) ${relabeled}`,
748 ],
749 [`[${hosted}](t3-thread://v2/local/id "Title")`],
750 [`[a](https://example.com/x_(y)) ${hosted}`, `[a](https://example.com/x_(y)) ${relabeled}`],
751 [`(${hosted}) **${hosted}**`, `(${relabeled}) **${relabeled}**`],
752 [`[[[ [old](${hosted})`, `[[[ ${relabeled}`],
753 [`\\\\[old](${hosted})`, `\\\\${relabeled}`],
754 [`\\\\\\\\[old](${hosted})`, `\\\\\\\\${relabeled}`],
755 [`\\[old](${hosted})`, `\\[old](${relabeled})`],
756 [`\\[ ${hosted} ](https://example.com)`, `\\[ ${relabeled} ](https://example.com)`],
757 ["\\[old](t3-thread://v2/there/t1) \\<t3-thread://v2/there/t1>"],
758 ] as const) {
759 expect(relabelThreadLinks(markdown, local, title)).toBe(expected ?? markdown);
760 expect(threadLinkRefs(markdown, local)).toEqual(
761 expected === undefined ? [] : [ref("there", "t1")],
762 );
763 }
764 });
765​
766 it("rewrites a hosted link after many unclosed website links", () => {
767 const openers = "[x](".repeat(50_000);
768 expect(replaceThreadLinks(`${openers} <t3-thread://v2/local/prose>`, () => "linked")).toBe(
769 `${openers} linked`,
770 );
771 });
772​
773 it("keeps Markdown reference link definitions intact when relabeling", () => {
774 const hosted = "https://app.t3.codes/threads/local/demo";
775 for (const markdown of [
776 `[Review][thread]\n\n[thread]: ${hosted}`,
777 `[Review][thread]\n\n[thread]:${hosted}`,
778 `[Review][thread]\n\n[thread]: <${hosted}>`,
779 `[Review][thread]\n\n[thread]: <t3-thread://v2/local/demo>`,
780 `[Review][thread]\n\n[thread]:\n ${hosted}`,
781 `[Review][thread]\n\n [thread]: ${hosted} "Demo"`,
782 `> [Review][thread]\n>\n> [thread]: ${hosted}`,
783 ]) {
784 for (const title of [() => "Demo", () => undefined]) {
785 expect(relabelThreadLinks(markdown, local, title)).toBe(markdown);
786 }
787 }
788​
789 const withLiveAfter = `[Review][thread]\n\n[thread]: ${hosted}\n\nSee ${hosted}`;
790 expect(relabelThreadLinks(withLiveAfter, local, () => "Demo")).toBe(
791 `[Review][thread]\n\n[thread]: ${hosted}\n\nSee [Demo](t3-thread://v2/local/demo)`,
792 );
793​
794 for (const markdown of [
795 `[${hosted}][site]\n\n[site]: https://example.com`,
796 `![${hosted}][site]\n\n[site]: https://example.com`,
797 ]) {
798 expect(relabelThreadLinks(markdown, local, () => "Demo")).toBe(markdown);
799 expect(threadLinkRefs(markdown, local)).toEqual([]);
800 }
801 const labelWithLiveAfter = `[${hosted}][site]\n\n[site]: https://example.com\n\n${hosted}`;
802 expect(relabelThreadLinks(labelWithLiveAfter, local, () => "Demo")).toBe(
803 `[${hosted}][site]\n\n[site]: https://example.com\n\n[Demo](t3-thread://v2/local/demo)`,
804 );
805​
806 const paragraphContinuation = `Intro\n[thread]: ${hosted}`;
807 expect(relabelThreadLinks(paragraphContinuation, local, () => "Demo")).toBe(
808 `Intro\n[thread]: [Demo](t3-thread://v2/local/demo)`,
809 );
810 });
811​
812 it("keeps relabeled links navigable when the thread id contains a space", () => {
813 const linkUrl = (markdown: string) => {
814 const paragraph = unified().use(remarkParse).parse(markdown).children[0];
815 const node = paragraph?.type === "paragraph" ? paragraph.children[0] : undefined;
816 return node?.type === "link" ? node.url : undefined;
817 };
818 const thread = ref("local", "work item");
819 const titles = titlesIn({ local: { "work item": "Review", "work%20item": "Encoded" } });
820​
821 const relabeled = relabelThreadLinks(hostedThreadLink(thread), local, titles);
822 expect(parseThreadLinkHref(linkUrl(relabeled) ?? "")).toEqual({ ...thread, hosted: true });
823 expect(threadLinkRefs(relabeled, local)).toEqual([thread]);
824​
825 const v1Relabeled = relabelThreadLinks("[old](t3-thread://v1/work%20item)", local, titles);
826 expect(linkUrl(v1Relabeled)).toBe("t3-thread://v1/work%20item");
827 expect(formatThreadLink(v1("work item"))).toBe("<t3-thread://v1/work%20item>");
828 });
829});