@devries-cameron20 / t3code-1 / commits / 251369d31c
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

feat(server,web,mobile,desktop): Copy thread copies a link that opens the thread (#26290)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 3, 2026 at 13:44 UTC 251369d31cfdf520aabf3e3146531bdb2fb59477
32 files changed +636 -107
apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.kt
+4
@@ -9,6 +9,10 @@ import org.json.JSONObject
9 import org.json.JSONArray
10
11 internal object T3ComposerClipboard {
12 + // Pasted thread links become chips in JS; packages/shared/src/threadLinks.ts parses them.
13 + fun hasThreadLink(text: String): Boolean =
14 + text.contains("t3-thread://v2/") || text.contains("https://app.t3.codes/threads/")
15 +
16 fun write(context: Context, text: String, fragment: String) {
17 val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
18 val payload = try {
apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt
+17 -4
@@ -735,11 +735,24 @@ internal class SelectionAwareEditText(
735
736 private fun pasteContextOrImages(): Boolean {
737 val payload = T3ComposerClipboard.read(context)
738 - if (payload["html"]?.contains("data-t3-context-fragment=") == true) {
739 - pasteContextListener?.invoke(payload)
740 - return true
738 + return when {
739 + payload["html"]?.contains("data-t3-context-fragment=") == true -> pasteContext(payload)
740 + pasteImagesOrInterceptedText() -> true
741 + isSingleItemClip() && T3ComposerClipboard.hasThreadLink(payload["text"].orEmpty()) ->
742 + pasteContext(payload)
743 + else -> false
744 }
742 - return pasteImagesOrInterceptedText()
745 + }
746 +
747 + // read() sees only the first item; native paste keeps every item of a longer clip.
748 + private fun isSingleItemClip(): Boolean {
749 + val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
750 + return clipboard?.primaryClip?.itemCount == 1
751 + }
752 +
753 + private fun pasteContext(payload: Map<String, String>): Boolean {
754 + pasteContextListener?.invoke(payload)
755 + return true
756 }
757
758 private fun pasteImagesOrInterceptedText(): Boolean {
apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift
+5
@@ -4,6 +4,11 @@ import UIKit
4 enum T3ComposerClipboard {
5 static let fragmentType = "app.t3.context-fragment"
6
7 + // Pasted thread links become chips in JS; packages/shared/src/threadLinks.ts parses them.
8 + static func hasThreadLink(_ text: String) -> Bool {
9 + text.contains("t3-thread://v2/") || text.contains("https://app.t3.codes/threads/")
10 + }
11 +
12 static func write(text: String, fragment: String) {
13 var items: [String: Any] = ["public.utf8-plain-text": text]
14 if let data = fragment.data(using: .utf8),
apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
+6
@@ -226,6 +226,12 @@ private final class ComposerTextView: UITextView {
226 onPasteText?(text, selectedRange)
227 return
228 }
229 + // read() sees only the first item; native paste keeps every item of a longer pasteboard.
230 + if !bypassTextPasteInterception, pasteboard.numberOfItems == 1,
231 + T3ComposerClipboard.hasThreadLink(context["text", default: ""]) {
232 + onPasteContext?(context)
233 + return
234 + }
235 super.paste(sender)
236 }
237
apps/mobile/src/features/threads/ThreadFeed.tsx
+4 -3
@@ -61,7 +61,7 @@ import {
61 } from "@t3tools/contracts";
62 import { renderAssistantCitationsAsText } from "@t3tools/shared/assistantCitations";
63 import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
64 -import { parseThreadLinkHref } from "@t3tools/shared/threadLinks";
64 +import { hostedThreadLink, parseThreadLinkHref } from "@t3tools/shared/threadLinks";
65 import { PROMPT_LINK_MAX_PROMPT_LENGTH } from "@t3tools/shared/promptLinks";
66 import {
67 parseComposerContextHref,
@@ -3058,9 +3058,10 @@ export const ThreadFeed = memo(function ThreadFeed({
3058 else if (actionId === "copy-skill") copyTextWithHaptic(`$${skill.name}`);
3059 return;
3060 }
3061 - if (resolveLinkedThread(href)) {
3061 + const thread = resolveLinkedThread(href);
3062 + if (thread) {
3063 if (actionId === "open-thread") onMarkdownLinkPress(href);
3063 - else if (actionId === "copy-thread-link") copyTextWithHaptic(href);
3064 + else if (actionId === "copy-thread-link") copyTextWithHaptic(hostedThreadLink(thread));
3065 return;
3066 }
3067 const target = resolveFileChipTarget(href, props.workspaceRoot);
apps/mobile/src/lib/composerContextClipboard.test.ts
+33
@@ -42,6 +42,9 @@ vi.mock("../state/session", () => ({
42 environmentSession: { preparedConnectionValueAtom: vi.fn() },
43 }));
44 vi.mock("../state/assets", () => ({ assetEnvironment: { createUrl: (value: unknown) => value } }));
45 +vi.mock("../state/threads", () => ({
46 + environmentThreadShells: { threadShellAtom: (value: unknown) => value },
47 +}));
48 vi.mock("../state/use-composer-drafts", () => ({
49 waitForComposerDraftsLoaded: async () => {},
50 findLocalComposerClipboardAttachment: mocks.local,
@@ -336,4 +339,34 @@ describe("mobile context clipboard imports", () => {
339 collectComposerContextReferences(result!.text).map((reference) => reference.contextId),
340 ).toEqual(result!.context.records.map((record) => record.contextId));
341 });
342 +
343 + it("pastes a thread link as a chip only where the destination's agent reads its machine", async () => {
344 + const text = [
345 + "https://app.t3.codes/threads/destination/local-thread",
346 + "<t3-thread://v2/source/foreign-thread>",
347 + ].join(" ");
348 + const result = await importComposerContextClipboard(
349 + { text, fragment: "", html: "" },
350 + 0,
351 + new AbortController().signal,
352 + 0,
353 + EnvironmentId.make("destination"),
354 + );
355 + const [record] = result!.context.records;
356 + expect(record).toMatchObject({
357 + kind: "thread",
358 + environmentId: "destination",
359 + threadId: "local-thread",
360 + });
361 + expect(result!.text).toBe(
362 + `[Thread](t3-context://v1/thread/${record!.contextId}) <t3-thread://v2/source/foreign-thread>`,
363 + );
364 + expect(
365 + await importComposerContextClipboard(
366 + { text: "plain text", fragment: "", html: "" },
367 + 0,
368 + new AbortController().signal,
369 + ),
370 + ).toBeNull();
371 + });
372 });
apps/mobile/src/lib/composerContextClipboard.ts
+36 -5
@@ -13,13 +13,17 @@ import {
13 decodeComposerContextFragment,
14 encodeComposerContextFragment,
15 } from "@t3tools/shared/composerContextClipboard";
16 -import { threadContextsOutsideEnvironment } from "@t3tools/shared/composerContextReferences";
16 +import {
17 + threadContextsOutsideEnvironment,
18 + threadLinkContextReferences,
19 +} from "@t3tools/shared/composerContextReferences";
20 import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
21 import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
22 import * as Option from "effect/Option";
23 import { appAtomRegistry } from "../state/atom-registry";
24 import { assetEnvironment } from "../state/assets";
25 import { environmentSession } from "../state/session";
26 +import { environmentThreadShells } from "../state/threads";
27 import { workspaceConnections } from "../state/workspace";
28 import { downloadAttachmentForPreview } from "./attachmentDownload";
29 import {
@@ -71,11 +75,38 @@ export async function importComposerContextClipboard(
75 /** The machines the destination links to, whose threads its agent can read too. */
76 linkedEnvironments: ReadonlyMap<EnvironmentId, string> = new Map(),
77 ) {
74 - const fragment =
78 + const copied =
79 decodeComposerContextFragment(input.fragment) ?? decodeComposerContextClipboardHtml(input.html);
76 - if (!fragment) return null;
77 - const selected = referencedComposerContext(input.text, { version: 1, records: fragment.records });
78 - const imported = reidentifyComposerContext(input.text, selected?.records ?? [], uuidv4);
80 + // A thread link becomes a chip only where this agent can read its machine; others stay links.
81 + const threads = threadLinkContextReferences(
82 + input.text,
83 + copied?.records ?? [],
84 + (ref) => appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref))?.title,
85 + (record) =>
86 + destinationEnvironmentId === undefined ||
87 + record.environmentId === destinationEnvironmentId ||
88 + linkedEnvironments.has(record.environmentId)
89 + ? record.contextId
90 + : undefined,
91 + );
92 + const source =
93 + copied?.source ??
94 + (threads.records[0] ? { environmentId: threads.records[0].environmentId } : null);
95 + if (!source) return null;
96 + const fragment = {
97 + source,
98 + records: [
99 + ...(copied?.records ?? []).filter((record) =>
100 + threads.records.every((thread) => thread.contextId !== record.contextId),
101 + ),
102 + ...threads.records,
103 + ],
104 + };
105 + const selected = referencedComposerContext(threads.text, {
106 + version: 1,
107 + records: fragment.records,
108 + });
109 + const imported = reidentifyComposerContext(threads.text, selected?.records ?? [], uuidv4);
110 const skippedThreads =
111 destinationEnvironmentId === undefined
112 ? []
apps/server/src/auth/McpOAuth.ts
+10 -1
@@ -17,6 +17,7 @@ import {
17 mcpClientScopes,
18 type RuntimeMode,
19 } from "@t3tools/contracts";
20 +import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
21 import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
22 import * as Clock from "effect/Clock";
23 import * as Context from "effect/Context";
@@ -30,6 +31,7 @@ import * as Ref from "effect/Ref";
31 import * as Schema from "effect/Schema";
32 import { HttpServerRequest } from "effect/http";
33
34 +import { hostedAppUrlConfig } from "../cloud/publicConfig.ts";
35 import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
36 import * as ServerSettings from "../serverSettings.ts";
37 import * as McpHttpServer from "../mcp/McpHttpServer.ts";
@@ -577,6 +579,13 @@ export const layerMcpClientAuthenticator = Layer.effect(
579 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
580 const environment = yield* ServerEnvironment.ServerEnvironment;
581 const environmentId = yield* environment.getEnvironmentId;
582 + const hostedAppUrl = yield* hostedAppUrlConfig.pipe(
583 + Effect.catch((cause) =>
584 + Effect.logWarning("Outside MCP clients get app.t3.codes thread links", { cause }).pipe(
585 + Effect.as(DEFAULT_HOSTED_APP_URL),
586 + ),
587 + ),
588 + );
589 return McpHttpServer.McpClientAuthenticator.of({
590 authenticate: Effect.fn("McpHttpServer.McpClientAuthenticator.authenticate")(
591 function (request) {
@@ -592,7 +601,7 @@ export const layerMcpClientAuthenticator = Layer.effect(
601 label: client.label,
602 access: client.access,
603 linked: client.peerLink,
595 - ...(client.peerLink ? {} : { webOrigin: requestUrls(request).issuer }),
604 + ...(client.peerLink ? {} : { hostedAppUrl }),
605 },
606 capabilities: new Set<McpInvocationContext.McpCapability>([
607 "orchestration",
apps/server/src/mcp/McpInvocationContext.ts
+7 -8
@@ -12,7 +12,7 @@ import {
12 import * as Context from "effect/Context";
13 import * as Effect from "effect/Effect";
14 import * as Fiber from "effect/Fiber";
15 -import { formatThreadLink } from "@t3tools/shared/threadLinks";
15 +import { formatThreadLink, hostedThreadLink } from "@t3tools/shared/threadLinks";
16
17 const ALL_MCP_CAPABILITIES = [
18 "preview",
@@ -45,8 +45,8 @@ export interface McpClientCaller {
45 * another environment passing on the limits of the agent it calls for.
46 */
47 readonly narrowedTo?: ClientModes | undefined;
48 - /** The origin an outside client reached; its thread links open the web app there. */
49 - readonly webOrigin?: string | undefined;
48 + /** An outside client's thread links go through this hosted app, as Copy thread's do. */
49 + readonly hostedAppUrl?: string | undefined;
50 }
51
52 /**
@@ -135,16 +135,15 @@ export interface McpInvocationScope {
135
136 /**
137 * T3 Code renders `t3-thread://` links as thread chips. Other MCP clients cannot open them, so
138 - * they get a web URL on the origin they reached instead.
138 + * they get the hosted link Copy thread copies, which opens the thread in either app or a browser.
139 */
140 export const threadLinkFor = (
141 scope: Pick<McpInvocationScope, "environmentId" | "client">,
142 threadId: ThreadId,
143 ): string => {
144 - const origin = scope.client?.webOrigin;
145 - return origin === undefined
146 - ? formatThreadLink({ environmentId: scope.environmentId, threadId })
147 - : `${origin}/${encodeURIComponent(scope.environmentId)}/${encodeURIComponent(threadId)}`;
144 + const hostedAppUrl = scope.client?.hostedAppUrl;
145 + const ref = { environmentId: scope.environmentId, threadId };
146 + return hostedAppUrl === undefined ? formatThreadLink(ref) : hostedThreadLink(ref, hostedAppUrl);
147 };
148
149 export class McpInvocationContext extends Context.Service<
apps/server/src/mcp/toolkits/project/handlers.test.ts
+7 -7
@@ -50,7 +50,7 @@ const clientLaunchHarness = (input: {
50 readonly launched: Array<ThreadLaunch.ThreadLaunchInput>;
51 readonly workspaceRoot?: string;
52 readonly checkWorktreeBase?: ThreadLaunch.ThreadLaunchService["Service"]["checkWorktreeBase"];
53 - readonly webOrigin?: string;
53 + readonly hostedAppUrl?: string;
54 /** The orchestrator refuses the new thread's mode, as under a managed ceiling. */
55 readonly refusedByCeiling?: true;
56 }) => {
@@ -89,7 +89,7 @@ const clientLaunchHarness = (input: {
89 sessionId: "session-1",
90 label: "Claude Code",
91 access: input.runtimeModeCeiling,
92 - webOrigin: input.webOrigin,
92 + hostedAppUrl: input.hostedAppUrl,
93 },
94 issuedAt: 0,
95 capabilities: new Set(["orchestration" as const]),
@@ -187,18 +187,18 @@ it.effect(
187 readonly runtimeMode?: RuntimeMode;
188 readonly targeted?: false;
189 readonly overrideModel?: ModelSelection;
190 - readonly webOrigin?: string;
190 + readonly hostedAppUrl?: string;
191 readonly refusedByCeiling?: true;
192 },
193 ) {
194 - const { targeted, overrideModel, webOrigin, refusedByCeiling, ...input } = params;
194 + const { targeted, overrideModel, hostedAppUrl, refusedByCeiling, ...input } = params;
195 const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
196 const { projectId, modelSelection, dependencies } = clientLaunchHarness({
197 runtimeModeCeiling,
198 defaultRuntimeMode,
199 launched,
200 ...(overrideModel === undefined ? {} : { overrideModel }),
201 - ...(webOrigin === undefined ? {} : { webOrigin }),
201 + ...(hostedAppUrl === undefined ? {} : { hostedAppUrl }),
202 ...(refusedByCeiling === undefined ? {} : { refusedByCeiling }),
203 });
204 const toolkit = yield* ProjectToolkit.pipe(
@@ -228,11 +228,11 @@ it.effect(
228
229 const aboveCeiling = yield* launchWith("auto-accept-edits", "full-access", {
230 title: "Fix",
231 - webOrigin: "https://box.example.ts.net",
231 + hostedAppUrl: "https://t3.example.com",
232 });
233 expect(aboveCeiling.launched[0]?.runtimeMode).toBe("auto-accept-edits");
234 expect(aboveCeiling.result).toMatchObject({
235 - link: `https://box.example.ts.net/environment/${encodeURIComponent(aboveCeiling.launched[0]?.threadId ?? "")}`,
235 + link: `https://t3.example.com/threads/environment/${encodeURIComponent(aboveCeiling.launched[0]?.threadId ?? "")}`,
236 });
237
238 const requested = yield* launchWith("full-access", "approval-required", {
apps/web/src/components/ChatView.tsx
+2
@@ -5,6 +5,7 @@ import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits";
5 import { queuedRunEditBlockedReason } from "@t3tools/client-runtime/queued-run-edit";
6 import { ScrollToEndButton, WorkspaceFileDropOverlay } from "./chat/TimelineOverlays";
7 import { usePasteToFocusComposer } from "./chat/usePasteToFocusComposer";
8 +import { configuredHostedAppUrl } from "../hostedPairing";
9 import { announcedRun, isDetailBehindShell } from "./chat/threadActivityAnnouncement";
10 import {
11 deriveAvailableRevertTurnCounts,
@@ -2322,6 +2323,7 @@ export default function ChatView(props: ChatViewProps) {
2323 openPanelPullRequestUrl,
2324 pullRequests: activeThread?.pullRequests,
2325 linkedPullRequestUrl: linkedThreadPullRequest?.url ?? null,
2326 + hostedAppUrl: configuredHostedAppUrl(),
2327 });
2328 const copyActiveThreadReference = () => {
2329 if (activeThreadReferenceCopyTarget === null) return;
apps/web/src/components/CommandPalette.tsx
+2
@@ -106,6 +106,7 @@ import {
106 import { useClientSettings } from "../hooks/useSettings";
107 import { useStableCallback } from "../hooks/useStableCallback";
108 import { readLocalApi } from "../localApi";
109 +import { configuredHostedAppUrl } from "../hostedPairing";
110 import { desktopLocalBackendId } from "../connection/desktopLocal";
111 import { filesystemEnvironment, useFilesystemReadAccess } from "../state/filesystem";
112 import { projectEnvironment } from "../state/projects";
@@ -489,6 +490,7 @@ function OpenCommandPaletteDialog(props: {
490 pullRequests: activeThread?.pullRequests,
491 linkedPullRequestUrl:
492 activeThread?.linkedPullRequest?.url ?? activeThread?.branchPullRequest?.url ?? null,
493 + hostedAppUrl: configuredHostedAppUrl(),
494 });
495 const copyActiveThreadReference = async () => {
496 if (activeThreadReferenceCopyTarget === null) return;
apps/web/src/components/Sidebar.tsx
+4 -1
@@ -103,6 +103,7 @@ import { isModelPickerOpen } from "../modelPickerVisibility";
103 import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
104 import { isMacPlatform } from "~/lib/utils";
105 import { readLocalApi } from "../localApi";
106 +import { configuredHostedAppUrl } from "../hostedPairing";
107 import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore";
108 import {
109 pickableProjectGroups,
@@ -2809,7 +2810,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
2810 }
2811 return;
2812 case "copy-thread":
2812 - void copyThreadReference(threadChipCopyTarget(threadRef, thread.title));
2813 + void copyThreadReference(
2814 + threadChipCopyTarget(threadRef, thread.title, configuredHostedAppUrl()),
2815 + );
2816 return;
2817 case "copy-thread-id":
2818 copyThreadIdToClipboard(thread.id, { threadId: thread.id });
apps/web/src/components/chat/MarkdownThreadLink.tsx
+6 -2
@@ -1,13 +1,14 @@
1 import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2 import type { EnvironmentId } from "@t3tools/contracts";
3 import {
4 - formatThreadLink,
4 + formatHostedThreadLink,
5 guessThreadLinkRef,
6 percentDecodedThreadLinkId,
7 type ThreadLink,
8 unknownThreadLinkLabel,
9 } from "@t3tools/shared/threadLinks";
10
11 +import { configuredHostedAppUrl } from "../../hostedPairing";
12 import { useThreadRefs, useThreadShell } from "../../state/entities";
13 import { UnresolvedChip } from "../contextChipParts";
14 import { ThreadContextChip } from "../ThreadContextChip";
@@ -36,6 +37,9 @@ export function MarkdownThreadLink(props: {
37 const ref = { environmentId: thread.environmentId, threadId: thread.id };
38 const title = thread.title.trim() || props.label || "Untitled thread";
39 return (
39 - <ThreadContextChip record={{ ...ref, title }} copyMarkdown={formatThreadLink(ref, title)} />
40 + <ThreadContextChip
41 + record={{ ...ref, title }}
42 + copyMarkdown={formatHostedThreadLink(ref, title, configuredHostedAppUrl())}
43 + />
44 );
45 }
apps/web/src/components/composerInlineTokenPaste.test.ts new
+59
@@ -0,0 +1,59 @@
1 +import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference";
2 +import { type ComposerContextClipboardFragment, EnvironmentId, ThreadId } from "@t3tools/contracts";
3 +import {
4 + COMPOSER_CONTEXT_CLIPBOARD_MIME,
5 + encodeComposerContextFragment,
6 +} from "@t3tools/shared/composerContextClipboard";
7 +import { threadContextRecord } from "@t3tools/shared/composerContextReferences";
8 +import { describe, expect, it } from "vite-plus/test";
9 +
10 +import { importPastedComposerText } from "./composerInlineTokenPaste";
11 +
12 +const thread = {
13 + environmentId: EnvironmentId.make("env-1"),
14 + threadId: ThreadId.make("thread-1"),
15 +};
16 +const clipboard = (data: Record<string, string>) => ({
17 + getData: (type: string) => data[type] ?? "",
18 +});
19 +const chip = (title: string) =>
20 + `[${title}](t3-context://v1/thread/${threadContextRecord(thread, title).contextId})`;
21 +
22 +/** Imports every record it is offered, as the composer does for a thread its agent can read. */
23 +const importAll =
24 + (imported: Array<ComposerContextClipboardFragment>) =>
25 + (fragment: ComposerContextClipboardFragment) => {
26 + imported.push(fragment);
27 + return new Map(fragment.records.map((record) => [record.contextId, record.contextId]));
28 + };
29 +
30 +describe("importPastedComposerText", () => {
31 + it("pastes a copied thread link back as the chip it was copied from", () => {
32 + const target = threadChipCopyTarget(thread, "Fix the login flow");
33 + const imported: Array<ComposerContextClipboardFragment> = [];
34 + const text = importPastedComposerText(
35 + clipboard({
36 + "text/plain": `See ${target.value}`,
37 + [COMPOSER_CONTEXT_CLIPBOARD_MIME]: encodeComposerContextFragment(target.fragment!)!,
38 + }),
39 + importAll(imported),
40 + );
41 + expect(text).toBe(`See ${chip("Fix the login flow")}`);
42 + expect(imported.map((fragment) => fragment.records)).toEqual([target.fragment!.records]);
43 + });
44 +
45 + it("makes a chip of a v2 link pasted without T3's clipboard format", () => {
46 + const text = importPastedComposerText(
47 + clipboard({ "text/plain": "[Login](t3-thread://v2/env-1/thread-1)" }),
48 + importAll([]),
49 + );
50 + expect(text).toBe(chip("Login"));
51 + });
52 +
53 + it("keeps the link when the composer cannot take the thread", () => {
54 + const pasted = "https://app.t3.codes/threads/env-1/thread-1";
55 + expect(importPastedComposerText(clipboard({ "text/plain": pasted }), () => new Map())).toBe(
56 + pasted,
57 + );
58 + });
59 +});
apps/web/src/components/composerInlineTokenPaste.ts
+46 -19
@@ -1,5 +1,9 @@
1 import { ComposerContextId } from "@t3tools/contracts";
2 -import type { ComposerContextClipboardFragment } from "@t3tools/contracts";
2 +import type {
3 + ComposerContextClipboardFragment,
4 + ComposerContextRecord,
5 + ScopedThreadRef,
6 +} from "@t3tools/contracts";
7 import {
8 COMPOSER_CONTEXT_CLIPBOARD_MIME,
9 decodeComposerContextFragment,
@@ -9,7 +13,14 @@ import {
13 collectComposerContextReferences,
14 formatComposerContextReference,
15 replaceComposerContextReferences,
16 + threadLinkContextReferences,
17 } from "@t3tools/shared/composerContextReferences";
18 +
19 +import { readThreadShell } from "~/state/entities";
20 +
21 +const threadTitle = (ref: ScopedThreadRef) => readThreadShell(ref)?.title;
22 +
23 +/** Pasted thread links count as context too, so they become chips like a copied chip does. */
24 export function readPastedComposerContext(
25 clipboardData: Pick<DataTransfer, "getData">,
26 ): ComposerContextClipboardFragment | null {
@@ -17,11 +28,20 @@ export function readPastedComposerContext(
28 const decodedFragment =
29 decodeComposerContextFragment(clipboardData.getData(COMPOSER_CONTEXT_CLIPBOARD_MIME)) ??
30 decodeComposerContextClipboardHtml(clipboardData.getData("text/html"));
20 - if (decodedFragment === null) return null;
31 + const threads = threadLinkContextReferences(
32 + pastedText,
33 + decodedFragment?.records ?? [],
34 + threadTitle,
35 + );
36 + const source =
37 + decodedFragment?.source ??
38 + (threads.records[0] ? { environmentId: threads.records[0].environmentId } : null);
39 + if (source === null) return null;
40 const pastedIds = new Set<string>(
22 - collectComposerContextReferences(pastedText).map((occurrence) => occurrence.contextId),
41 + collectComposerContextReferences(threads.text).map((occurrence) => occurrence.contextId),
42 );
24 - for (const record of decodedFragment.records) {
43 + const records = new Map<string, ComposerContextRecord>();
44 + for (const record of [...(decodedFragment?.records ?? []), ...threads.records]) {
45 if (
46 record.kind === "preview-annotation" &&
47 !("payload" in record) &&
@@ -30,10 +50,12 @@ export function readPastedComposerContext(
50 ) {
51 pastedIds.add(record.screenshotContextId);
52 }
53 + records.set(record.contextId, record);
54 }
55 return {
35 - ...decodedFragment,
36 - records: decodedFragment.records.filter((record) => pastedIds.has(record.contextId)),
56 + version: 1,
57 + source,
58 + records: [...records.values()].filter((record) => pastedIds.has(record.contextId)),
59 };
60 }
61
@@ -47,18 +69,23 @@ export function importPastedComposerText(
69 const fragment = importContextFragment ? readPastedComposerContext(clipboardData) : null;
70 const rewrittenIds =
71 fragment && fragment.records.length > 0 ? importContextFragment!(fragment) : null;
50 - const text =
51 - rewrittenIds && rewrittenIds.size > 0
52 - ? replaceComposerContextReferences(pastedText, (occurrence) => {
53 - const nextId = rewrittenIds.get(occurrence.contextId);
54 - return nextId
55 - ? formatComposerContextReference({
56 - ...occurrence,
57 - contextId: ComposerContextId.make(nextId),
58 - kind: occurrence.kind === "element" ? "preview-annotation" : occurrence.kind,
59 - })
60 - : occurrence.source;
72 + if (!rewrittenIds || rewrittenIds.size === 0) return pastedText;
73 + const nextId = (contextId: string) => {
74 + const id = rewrittenIds.get(contextId);
75 + return id ? ComposerContextId.make(id) : undefined;
76 + };
77 + const text = replaceComposerContextReferences(pastedText, (occurrence) => {
78 + const contextId = nextId(occurrence.contextId);
79 + return contextId
80 + ? formatComposerContextReference({
81 + ...occurrence,
82 + contextId,
83 + kind: occurrence.kind === "element" ? "preview-annotation" : occurrence.kind,
84 })
62 - : pastedText;
63 - return text;
85 + : occurrence.source;
86 + });
87 + // A thread the import refused, on a machine this agent cannot read, stays the link it was.
88 + return threadLinkContextReferences(text, fragment?.records ?? [], threadTitle, (record) =>
89 + nextId(record.contextId),
90 + ).text;
91 }
apps/web/src/components/promptLinks/HostedPromptLinkLanding.tsx
+31 -10
@@ -23,19 +23,36 @@ const OPENER_STORAGE_KEY = "t3code:prompt-link-opener";
23 const Opener = Schema.NullOr(Schema.Literals(["app", "browser"]));
24
25 interface LinkSummary {
26 + readonly title: string;
27 + readonly description: string;
28 readonly prompt: LinkedPrompt | null;
29 readonly details: ReadonlyArray<string>;
30 }
31
32 +const PROMPT_HEADER = {
33 + title: "Open this prompt",
34 + description: "It opens as a draft. Nothing runs until you press Send.",
35 +};
36 +
37 function summarize(
38 appPath: string,
39 ): { ok: true; value: LinkSummary } | { ok: false; error: string } {
40 const url = new URL(appPath, window.location.origin);
41 if (url.pathname !== "/new") {
42 const prompt = parseThreadLinkPrompt(url.search);
36 - return prompt.ok
37 - ? { ok: true, value: { prompt: prompt.value, details: ["Opens one of your threads."] } }
38 - : prompt;
43 + if (!prompt.ok) return prompt;
44 + return {
45 + ok: true,
46 + value:
47 + prompt.value === null
48 + ? {
49 + title: "Open this thread",
50 + description: "It opens in T3 Code if you're connected to the machine it runs on.",
51 + prompt: null,
52 + details: [],
53 + }
54 + : { ...PROMPT_HEADER, prompt: prompt.value, details: ["Opens one of your threads."] },
55 + };
56 }
57 const link = parseNewThreadLink(url.search);
58 if (!link.ok) return link;
@@ -43,13 +60,18 @@ function summarize(
60 const { owner, name, number } = link.value.pullRequest;
61 return {
62 ok: true,
46 - value: { prompt: link.value.prompt, details: [`Pull request ${owner}/${name}#${number}`] },
63 + value: {
64 + ...PROMPT_HEADER,
65 + prompt: link.value.prompt,
66 + details: [`Pull request ${owner}/${name}#${number}`],
67 + },
68 };
69 }
70 const { repository, provider, model } = link.value;
71 return {
72 ok: true,
73 value: {
74 + ...PROMPT_HEADER,
75 prompt: link.value.prompt,
76 details: [
77 repository ? `Repository ${repository.owner}/${repository.name}` : "No project",
@@ -119,13 +141,10 @@ function HostedPromptLinkLanding({
141 );
142 }
143
122 - const { prompt, details } = summary.value;
144 + const { title, description, prompt, details } = summary.value;
145 return (
146 <StandalonePage>
125 - <StandalonePageHeader
126 - title="Open this prompt"
127 - description="It opens as a draft. Nothing runs until you press Send."
128 - />
147 + <StandalonePageHeader title={title} description={description} />
148 {prompt !== null && prompt.hiddenCharacters > 0 ? (
149 <Alert className="mt-5" variant="error">
150 <AlertTitle>This prompt had hidden characters, it may be malicious</AlertTitle>
@@ -140,7 +159,9 @@ function HostedPromptLinkLanding({
159 {prompt.text}
160 </pre>
161 ) : null}
143 - <p className="mt-3 text-xs text-muted-foreground">{details.join(" · ")}</p>
162 + {details.length > 0 ? (
163 + <p className="mt-3 text-xs text-muted-foreground">{details.join(" · ")}</p>
164 + ) : null}
165 <div className="mt-6 flex flex-wrap gap-2">
166 <Button render={<a href={deepLink} />} onClick={() => onChoose("app", remember)}>
167 {onPhone ? "Open in app" : "Open in desktop app"}
apps/web/src/hooks/useThreadActionMenu.ts
+4 -1
@@ -35,6 +35,7 @@ import {
35 } from "../state/entities";
36 import { usePrimaryEnvironmentId } from "../state/environments";
37 import { readLocalApi } from "../localApi";
38 +import { configuredHostedAppUrl } from "../hostedPairing";
39 import {
40 deriveLogicalProjectKeyFromSettings,
41 derivePhysicalProjectKey,
@@ -295,7 +296,9 @@ export function useThreadActionMenu(input: {
296 }
297 return;
298 case "copy-thread":
298 - void copyThreadReference(threadChipCopyTarget(threadRef, thread.title));
299 + void copyThreadReference(
300 + threadChipCopyTarget(threadRef, thread.title, configuredHostedAppUrl()),
301 + );
302 return;
303 case "copy-thread-id":
304 copyThreadIdToClipboard(thread.id, { threadId: thread.id });
apps/web/src/routeTree.gen.ts
+22
@@ -21,6 +21,7 @@ import { Route as ChatUsageRouteImport } from './routes/_chat.usage'
21 import { Route as ChatSettingsRouteImport } from './routes/_chat.settings'
22 import { Route as ChatPullRequestsRouteImport } from './routes/_chat.pull-requests'
23 import { Route as ChatNewRouteImport } from './routes/_chat.new'
24 +import { Route as ThreadsEnvironmentIdThreadIdRouteImport } from './routes/threads.$environmentId.$threadId'
25 import { Route as ChatSettingsWorktreesRouteImport } from './routes/_chat.settings.worktrees'
26 import { Route as ChatSettingsThreadsRouteImport } from './routes/_chat.settings.threads'
27 import { Route as ChatSettingsStorageRouteImport } from './routes/_chat.settings.storage'
@@ -109,6 +110,12 @@ const ChatNewRoute = ChatNewRouteImport.update({
110 path: '/new',
111 getParentRoute: () => ChatRoute,
112 } as any)
113 +const ThreadsEnvironmentIdThreadIdRoute =
114 + ThreadsEnvironmentIdThreadIdRouteImport.update({
115 + id: '/threads/$environmentId/$threadId',
116 + path: '/threads/$environmentId/$threadId',
117 + getParentRoute: () => rootRouteImport,
118 + } as any)
119 const ChatSettingsWorktreesRoute = ChatSettingsWorktreesRouteImport.update({
120 id: '/worktrees',
121 path: '/worktrees',
@@ -295,6 +302,7 @@ export interface FileRoutesByFullPath {
302 '/settings/storage': typeof ChatSettingsStorageRoute
303 '/settings/threads': typeof ChatSettingsThreadsRoute
304 '/settings/worktrees': typeof ChatSettingsWorktreesRoute
305 + '/threads/$environmentId/$threadId': typeof ThreadsEnvironmentIdThreadIdRoute
306 }
307 export interface FileRoutesByTo {
308 '/connect': typeof ConnectRoute
@@ -336,6 +344,7 @@ export interface FileRoutesByTo {
344 '/settings/storage': typeof ChatSettingsStorageRoute
345 '/settings/threads': typeof ChatSettingsThreadsRoute
346 '/settings/worktrees': typeof ChatSettingsWorktreesRoute
347 + '/threads/$environmentId/$threadId': typeof ThreadsEnvironmentIdThreadIdRoute
348 }
349 export interface FileRoutesById {
350 __root__: typeof rootRouteImport
@@ -379,6 +388,7 @@ export interface FileRoutesById {
388 '/_chat/settings/storage': typeof ChatSettingsStorageRoute
389 '/_chat/settings/threads': typeof ChatSettingsThreadsRoute
390 '/_chat/settings/worktrees': typeof ChatSettingsWorktreesRoute
391 + '/threads/$environmentId/$threadId': typeof ThreadsEnvironmentIdThreadIdRoute
392 }
393 export interface FileRouteTypes {
394 fileRoutesByFullPath: FileRoutesByFullPath
@@ -422,6 +432,7 @@ export interface FileRouteTypes {
432 | '/settings/storage'
433 | '/settings/threads'
434 | '/settings/worktrees'
435 + | '/threads/$environmentId/$threadId'
436 fileRoutesByTo: FileRoutesByTo
437 to:
438 | '/connect'
@@ -463,6 +474,7 @@ export interface FileRouteTypes {
474 | '/settings/storage'
475 | '/settings/threads'
476 | '/settings/worktrees'
477 + | '/threads/$environmentId/$threadId'
478 id:
479 | '__root__'
480 | '/_chat'
@@ -505,6 +517,7 @@ export interface FileRouteTypes {
517 | '/_chat/settings/storage'
518 | '/_chat/settings/threads'
519 | '/_chat/settings/worktrees'
520 + | '/threads/$environmentId/$threadId'
521 fileRoutesById: FileRoutesById
522 }
523 export interface RootRouteChildren {
@@ -515,6 +528,7 @@ export interface RootRouteChildren {
528 PairRoute: typeof PairRoute
529 WelcomeRoute: typeof WelcomeRoute
530 ProjectsProjectKeyRoute: typeof ProjectsProjectKeyRoute
531 + ThreadsEnvironmentIdThreadIdRoute: typeof ThreadsEnvironmentIdThreadIdRoute
532 }
533
534 declare module '@tanstack/react-router' {
@@ -603,6 +617,13 @@ declare module '@tanstack/react-router' {
617 preLoaderRoute: typeof ChatNewRouteImport
618 parentRoute: typeof ChatRoute
619 }
620 + '/threads/$environmentId/$threadId': {
621 + id: '/threads/$environmentId/$threadId'
622 + path: '/threads/$environmentId/$threadId'
623 + fullPath: '/threads/$environmentId/$threadId'
624 + preLoaderRoute: typeof ThreadsEnvironmentIdThreadIdRouteImport
625 + parentRoute: typeof rootRouteImport
626 + }
627 '/_chat/settings/worktrees': {
628 id: '/_chat/settings/worktrees'
629 path: '/worktrees'
@@ -894,6 +915,7 @@ const rootRouteChildren: RootRouteChildren = {
915 PairRoute: PairRoute,
916 WelcomeRoute: WelcomeRoute,
917 ProjectsProjectKeyRoute: ProjectsProjectKeyRoute,
918 + ThreadsEnvironmentIdThreadIdRoute: ThreadsEnvironmentIdThreadIdRoute,
919 }
920 export const routeTree = rootRouteImport
921 ._addFileChildren(rootRouteChildren)
apps/web/src/routes/threads.$environmentId.$threadId.tsx new
+9
@@ -0,0 +1,9 @@
1 +import { Navigate, createFileRoute } from "@tanstack/react-router";
2 +
3 +// A copied thread link. On the hosted app its chooser shows first; this opens the thread after it.
4 +export const Route = createFileRoute("/threads/$environmentId/$threadId")({
5 + component: function ThreadLinkRedirect() {
6 + const params = Route.useParams();
7 + return <Navigate to="/$environmentId/$threadId" params={params} search replace />;
8 + },
9 +});
docs/orchestration-v2/orchestrator-mcp-server.md
+3 -2
@@ -412,8 +412,9 @@ know renders as a label that opens nothing. Older `t3-thread://v1/<threadId>`
412 links name no environment: clients resolve them in the message's environment,
413 then by a unique match in another enabled environment. An outside OAuth client,
414 one that is not a linked environment, cannot render `t3-thread://` links, so it
415 -gets a web URL on the origin it reached, `<origin>/<environmentId>/<threadId>`,
416 -for threads in this environment.
415 +gets the link Copy thread copies, `https://app.t3.codes/threads/<environmentId>/<threadId>`
416 +on the server's `T3CODE_HOSTED_APP_URL`, for threads in this environment. The
417 +hosted app offers the desktop app, the mobile app, or itself.
418
419 List and read results report `snoozed` and `snoozedUntil`, and
420 `t3_thread_list` filters on `snoozed`. The server's `isSnoozed` follows the
docs/user/composer.md
+4 -3
@@ -304,14 +304,15 @@ the repository by text. Choose a result to insert it as a chip.
304 Another thread can be context too. Type `@` followed by part of its title to pick one from
305 the same server, or from a machine it links to while the Linked environments beta is on; those
306 show the machine's name. On web and desktop you can also drag a thread out of the sidebar and
307 -drop it on the composer; a multi-selection drops together. On any client, **Copy thread** puts a
308 -thread on the clipboard that pastes into a composer as its chip. The chip shows the thread's
307 +drop it on the composer; a multi-selection drops together. On any client, **Copy thread** copies a
308 +link to the thread that pastes into a composer as its chip. The chip shows the thread's
309 current title and opens it when selected. Your prompt only carries a reference: the agent reads the thread's
310 history on demand, so attaching a long thread costs nothing until the agent looks. Attaching a
311 thread does not change it, and the agent cannot send messages to it unless you ask.
312
313 A thread from a linked machine, picked, pasted or dropped, stays a reference that the agent reads
314 -on that machine. Dropping a thread from any other environment attaches a saved transcript file. The source
314 +on that machine. A pasted link to a thread on any other machine stays a link. Dropping a thread
315 +from any other environment attaches a saved transcript file. The source
316 environment must be connected and up to date. The transcript includes the visible history and
317 saved text context at the time of the drop; later messages and the contents of attached files
318 are not copied. The agent can read the saved transcript after the source disconnects. Normal
docs/user/prompt-links.md
+7
@@ -54,3 +54,10 @@ before it replaces it.
54 T3 Code removes characters you cannot see, such as zero-width and hidden tag characters, because
55 they can hide instructions for the agent. When a prompt had them, T3 Code warns you that it may be
56 malicious.
57 +
58 +## Share a thread
59 +
60 +**Copy thread** copies a link such as `https://app.t3.codes/threads/<environment>/<thread>`. Paste
61 +it anywhere, such as Slack, a GitHub comment, or your notes. Opening it asks where to open it, like
62 +a prompt link, then opens the thread. Only someone connected to the machine that runs the thread
63 +can see it. In T3 Code, a thread link in a message opens the thread in the app.
docs/user/thread-sidebar.md
+5 -3
@@ -230,9 +230,11 @@ palette.
230
231 Use **Settings → Keybindings** to find or customize shortcuts for searching files
232 and copying a thread reference. A copied reference uses the thread's pull request
233 -link when available, otherwise the thread itself, which pastes into a composer as
234 -a thread chip. To copy the thread even when it has a PR, choose **Copy → Thread**
235 -from its context menu, or **Copy thread** from its long-press menu on mobile.
233 +link when available, otherwise a link to the thread, which opens it from anywhere
234 +you paste it and pastes into a composer as a thread chip (see
235 +[sharing a thread](./prompt-links.md#share-a-thread)). To copy the thread even
236 +when it has a PR, choose **Copy → Thread** from its context menu, or **Copy
237 +thread** from its long-press menu on mobile.
238 **Thread ID** copies the bare ID for scripts and the `t3` CLI. See
239 [keybindings](./keybindings.md) for custom configuration.
240
packages/client-runtime/src/threadReference.test.ts
+14 -9
@@ -3,7 +3,7 @@ import {
3 decodeComposerContextFragment,
4 encodeComposerContextFragment,
5 } from "@t3tools/shared/composerContextClipboard";
6 -import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences";
6 +import { threadLinkContextReferences } from "@t3tools/shared/composerContextReferences";
7 import { describe, expect, it } from "vite-plus/test";
8
9 import { resolveThreadReferenceCopyTarget } from "./threadReference.ts";
@@ -98,13 +98,18 @@ describe("resolveThreadReferenceCopyTarget", () => {
98 }),
99 ],
100 });
101 - // A paste keeps only the records its plain text references.
102 - expect(collectComposerContextReferences(target!.value)).toEqual([
103 - expect.objectContaining({
104 - kind: "thread",
105 - contextId: pasted!.records[0]!.contextId,
106 - label: "Fix the login flow",
107 - }),
108 - ]);
101 + // The plain text opens the thread anywhere and pastes back as the copied record's chip.
102 + expect(target!.value).toBe("https://app.t3.codes/threads/env-1/thread-1");
103 + expect(threadLinkContextReferences(target!.value, pasted!.records, () => undefined)).toEqual({
104 + text: `[Fix the login flow](t3-context://v1/thread/${pasted!.records[0]!.contextId})`,
105 + records: pasted!.records,
106 + });
107 + });
108 +
109 + it("links through the build's hosted app", () => {
110 + expect(
111 + resolveThreadReferenceCopyTarget({ ...thread, hostedAppUrl: "https://preview.t3.codes" })
112 + ?.value,
113 + ).toBe("https://preview.t3.codes/threads/env-1/thread-1");
114 });
115 });
packages/client-runtime/src/threadReference.ts
+11 -8
@@ -3,16 +3,14 @@ import type {
3 ScopedThreadRef,
4 ThreadPullRequestLink,
5 } from "@t3tools/contracts";
6 -import {
7 - formatComposerContextReference,
8 - threadContextRecord,
9 -} from "@t3tools/shared/composerContextReferences";
6 +import { threadContextRecord } from "@t3tools/shared/composerContextReferences";
7 +import { hostedThreadLink } from "@t3tools/shared/threadLinks";
8
9 import { resolveThreadCurrentPullRequestLink } from "./threadPullRequests.ts";
10
11 export interface ThreadReferenceCopyTarget {
12 readonly kind: "pull-request" | "thread";
15 - /** The plain text: a PR URL, or a thread chip's reference link. */
13 + /** The plain text: a PR URL, or a link that opens the thread from anywhere. */
14 readonly value: string;
15 /** What a toast or palette row shows for the copy. */
16 readonly description: string;
@@ -23,15 +21,19 @@ export interface ThreadReferenceCopyTarget {
21 readonly failureTitle: string;
22 }
23
26 -/** A thread chip pastes into any composer whose agent reads that thread's machine. */
24 +/**
25 + * A link that opens the thread from anywhere, through `hostedAppUrl`, this build's hosted app. It
26 + * pastes back as a chip into any composer whose agent reads that thread's machine.
27 + */
28 export function threadChipCopyTarget(
29 threadRef: ScopedThreadRef,
30 title: string,
31 + hostedAppUrl?: string,
32 ): ThreadReferenceCopyTarget {
33 const record = threadContextRecord(threadRef, title);
34 return {
35 kind: "thread",
34 - value: formatComposerContextReference(record),
36 + value: hostedThreadLink(threadRef, hostedAppUrl),
37 description: record.title,
38 fragment: { version: 1, source: { environmentId: threadRef.environmentId }, records: [record] },
39 clipboardTarget: "thread",
@@ -47,6 +49,7 @@ export function resolveThreadReferenceCopyTarget(input: {
49 readonly openPanelPullRequestUrl?: string | null | undefined;
50 readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
51 readonly linkedPullRequestUrl?: string | null;
52 + readonly hostedAppUrl?: string;
53 }): ThreadReferenceCopyTarget | null {
54 if (input.openPanelPullRequestUrl === null) return null;
55 const pullRequestUrl =
@@ -62,5 +65,5 @@ export function resolveThreadReferenceCopyTarget(input: {
65 successTitle: "PR link copied",
66 failureTitle: "Failed to copy PR link",
67 }
65 - : threadChipCopyTarget(input.threadRef, input.title);
68 + : threadChipCopyTarget(input.threadRef, input.title, input.hostedAppUrl);
69 }
packages/shared/src/composerContextReferences.test.ts
+63
@@ -17,6 +17,7 @@ import {
17 stripAttachmentOnlyBootstrapPrompt,
18 threadContextRecord,
19 threadContextsOutsideEnvironment,
20 + threadLinkContextReferences,
21 toComposerContextId,
22 toKindScopedComposerContextId,
23 } from "./composerContextReferences.ts";
@@ -478,3 +479,65 @@ describe("threadContextRecord", () => {
479 ).toBe("thread_abc-123");
480 });
481 });
482 +
483 +describe("threadLinkContextReferences", () => {
484 + const thread = (environmentId: string, threadId: string) => ({
485 + environmentId: EnvironmentId.make(environmentId),
486 + threadId: ThreadId.make(threadId),
487 + });
488 + const reference = (environmentId: string, threadId: string, label: string) =>
489 + `[${label}](t3-context://v1/thread/${threadContextRecord(thread(environmentId, threadId), label).contextId})`;
490 +
491 + it("makes a chip of a copied link, a v2 link, and a labeled link, titled here", () => {
492 + const pasted = threadLinkContextReferences(
493 + [
494 + "https://app.t3.codes/threads/env-1/t1",
495 + "<t3-thread://v2/env-1/t2>",
496 + "[Written](https://app.t3.codes/threads/env-2/t3)",
497 + ].join(" "),
498 + [],
499 + ({ threadId }) => (threadId === "t3" ? undefined : `Title ${threadId}`),
500 + );
501 + expect(pasted.text).toBe(
502 + [
503 + reference("env-1", "t1", "Title t1"),
504 + reference("env-1", "t2", "Title t2"),
505 + reference("env-2", "t3", "Written"),
506 + ].join(" "),
507 + );
508 + expect(pasted.records).toEqual([
509 + threadContextRecord(thread("env-1", "t1"), "Title t1"),
510 + threadContextRecord(thread("env-1", "t2"), "Title t2"),
511 + threadContextRecord(thread("env-2", "t3"), "Written"),
512 + ]);
513 + });
514 +
515 + it("prefers the record the copy carried, and names an unknown thread plainly", () => {
516 + const copied = threadContextRecord(thread("env-1", "t1"), "Copied title");
517 + const pasted = threadLinkContextReferences(
518 + "https://app.t3.codes/threads/env-1/t1 https://app.t3.codes/threads/env-9/t9",
519 + [copied],
520 + () => "Here",
521 + );
522 + expect(pasted.records).toEqual([copied, threadContextRecord(thread("env-9", "t9"), "Here")]);
523 + expect(
524 + threadLinkContextReferences("https://app.t3.codes/threads/env-9/t9", [], () => undefined)
525 + .records,
526 + ).toEqual([threadContextRecord(thread("env-9", "t9"), "Thread")]);
527 + });
528 +
529 + it("keeps links it may not chip, v1 links, and links in code as written", () => {
530 + const text = [
531 + "https://app.t3.codes/threads/elsewhere/t1",
532 + "[Old](t3-thread://v1/t2)",
533 + "`https://app.t3.codes/threads/env-1/t3`",
534 + ].join(" ");
535 + const pasted = threadLinkContextReferences(
536 + text,
537 + [],
538 + () => "Title",
539 + () => undefined,
540 + );
541 + expect(pasted).toEqual({ text, records: [] });
542 + });
543 +});
packages/shared/src/composerContextReferences.ts
+41
@@ -10,6 +10,8 @@ import {
10 type ThreadContextRecord,
11 } from "@t3tools/contracts";
12
13 +import { replaceThreadLinks, threadLinkCandidates } from "./threadLinks.ts";
14 +
15 const CONTEXT_PROTOCOL = "t3-context:";
16 const COMPOSER_CONTEXT_HREF_PREFIX = `${CONTEXT_PROTOCOL}//v1/`;
17 const CONTEXT_KIND_PATTERN = /^[a-z][a-z0-9-]{0,39}$/;
@@ -93,6 +95,45 @@ export function threadContextRecord(ref: ScopedThreadRef, title: string): Thread
95 };
96 }
97
98 +/**
99 + * Turns pasted thread links into thread chip references. A record the copy carried names its
100 + * chip, else the thread's title here, read by key, or the link's own label. `accept` gives the
101 + * chip's id, or none to keep the link as written. A v1 link names no machine, so it stays a link.
102 + */
103 +export function threadLinkContextReferences(
104 + text: string,
105 + copied: ReadonlyArray<ComposerContextRecord>,
106 + title: (ref: ScopedThreadRef) => string | undefined,
107 + accept: (record: ThreadContextRecord) => ComposerContextId | undefined = (record) =>
108 + record.contextId,
109 +): { readonly text: string; readonly records: ReadonlyArray<ThreadContextRecord> } {
110 + const records = new Map<ComposerContextId, ThreadContextRecord>();
111 + const rewritten = replaceThreadLinks(text, (link, label) => {
112 + if (link.environmentId === null) return undefined;
113 + const candidates = threadLinkCandidates(link, link.environmentId);
114 + const record =
115 + copied.find(
116 + (candidate): candidate is ThreadContextRecord =>
117 + candidate.kind === "thread" &&
118 + "threadId" in candidate &&
119 + candidates.some(
120 + (ref) =>
121 + ref.environmentId === candidate.environmentId && ref.threadId === candidate.threadId,
122 + ),
123 + ) ??
124 + candidates.flatMap((ref) => {
125 + const known = title(ref);
126 + return known === undefined ? [] : [threadContextRecord(ref, known)];
127 + })[0] ??
128 + threadContextRecord(candidates[0]!, label?.trim() || "Thread");
129 + const contextId = accept(record);
130 + if (contextId === undefined) return undefined;
131 + records.set(record.contextId, record);
132 + return formatComposerContextReference({ ...record, contextId });
133 + });
134 + return { text: rewritten, records: [...records.values()] };
135 +}
136 +
137 export function formatComposerContextReference(reference: {
138 kind: ComposerContextKind;
139 contextId: ComposerContextId;
packages/shared/src/promptLinks.test.ts
+24
@@ -1,3 +1,4 @@
1 +import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2 import { describe, expect, it } from "vite-plus/test";
3
4 import {
@@ -5,9 +6,11 @@ import {
6 parseNewThreadLink,
7 parseThreadLinkPrompt,
8 promptLinkAppPath,
9 + promptLinkDeepLink,
10 sanitizeLinkedPrompt,
11 withoutPromptLinkParams,
12 } from "./promptLinks.ts";
13 +import { hostedThreadLink } from "./threadLinks.ts";
14
15 describe("sanitizeLinkedPrompt", () => {
16 it("removes characters a reader cannot see and counts them", () => {
@@ -105,12 +108,33 @@ describe("link round trips", () => {
108 );
109 });
110
111 + it("opens a copied thread link in the app at that thread", () => {
112 + const link = hostedThreadLink({
113 + environmentId: EnvironmentId.make("env-1"),
114 + threadId: ThreadId.make("mcp:1"),
115 + });
116 + const path = promptLinkAppPath(link);
117 + expect(path).toBe("/env-1/mcp%3A1");
118 + const deepLink = promptLinkDeepLink(path!);
119 + expect(deepLink).toBe("t3code://threads/env-1/mcp%3A1");
120 + expect(promptLinkAppPath(deepLink)).toBe(path);
121 + });
122 +
123 it("maps app scheme and hosted links to in-app paths, and nothing else", () => {
124 expect(promptLinkAppPath("t3code://new?prompt=hi")).toBe("/new?prompt=hi");
125 expect(promptLinkAppPath("t3code-dev://threads/env-1/thread-1")).toBe("/env-1/thread-1");
126 expect(promptLinkAppPath("https://app.t3.codes/env-1/thread-1?prompt=go")).toBe(
127 "/env-1/thread-1?prompt=go",
128 );
129 + expect(promptLinkAppPath("https://app.t3.codes/threads/env-1/thread-1")).toBe(
130 + "/env-1/thread-1",
131 + );
132 + expect(promptLinkAppPath("https://app.t3.codes/threads/env-1/thread-1?prompt=go")).toBe(
133 + "/env-1/thread-1?prompt=go",
134 + );
135 + // The web app's own thread route, reloaded, is no link.
136 + expect(promptLinkAppPath("https://app.t3.codes/env-1/thread-1")).toBeNull();
137 + expect(promptLinkAppPath("https://app.t3.codes/threads/env-1")).toBeNull();
138 expect(promptLinkAppPath("https://app.t3.codes/settings/general")).toBeNull();
139 expect(promptLinkAppPath("https://evil.test/new?prompt=hi")).toBeNull();
140 expect(promptLinkAppPath("t3code://app/index.html")).toBeNull();
packages/shared/src/promptLinks.ts
+6 -1
@@ -199,7 +199,12 @@ export function promptLinkAppPath(
199 }
200 if (!URL.canParse(hostedAppUrl) || url.origin !== new URL(hostedAppUrl).origin) return null;
201 if (url.pathname === "/new") return `/new${url.search}`;
202 - const thread = url.searchParams.has("prompt") ? THREAD_PATH.exec(url.pathname) : null;
202 + // The web app's own thread route is a link only with a prompt, so reloading a tab never asks.
203 + const thread = url.pathname.startsWith("/threads/")
204 + ? THREAD_PATH.exec(url.pathname.slice("/threads".length))
205 + : url.searchParams.has("prompt")
206 + ? THREAD_PATH.exec(url.pathname)
207 + : null;
208 return thread ? `/${thread[1]}/${thread[2]}${url.search}` : null;
209 }
210
packages/shared/src/threadLinks.test.ts
+63
@@ -2,8 +2,10 @@ import { describe, expect, it, vi } from "vite-plus/test";
2 import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
3
4 import {
5 + formatHostedThreadLink,
6 formatThreadLink,
7 guessThreadLinkRef,
8 + hostedThreadLink,
9 parseThreadLinkHref,
10 relabelThreadLinks,
11 threadLinkCandidates,
@@ -174,3 +176,64 @@ describe("thread links", () => {
176 expect(formatThreadLink(ref("e", "t1"), " ] ")).toBe("<t3-thread://v2/e/t1>");
177 });
178 });
179 +
180 +describe("hosted thread links", () => {
181 + it("escapes every id character a sentence or path could claim, and reads it back", () => {
182 + const thread = ref("env.1", "thread:delegated/mcp%3A1.");
183 + const link = hostedThreadLink(thread);
184 + expect(link).toBe("https://app.t3.codes/threads/env%2E1/thread%3Adelegated%2Fmcp%253A1%2E");
185 + expect(parseThreadLinkHref(link)).toEqual(thread);
186 + expect(hostedThreadLink(thread, "https://preview.t3.codes/")).toMatch(
187 + /^https:\/\/preview\.t3\.codes\/threads\//,
188 + );
189 + });
190 +
191 + it("reads only a bare thread path on the hosted app", () => {
192 + expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1/thread-1")).toEqual(
193 + ref("env-1", "thread-1"),
194 + );
195 + expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1/thread-1?prompt=go")).toBeNull();
196 + expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1/thread-1/extra")).toBeNull();
197 + expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1")).toBeNull();
198 + expect(parseThreadLinkHref("https://app.t3.codes/env-1/thread-1")).toBeNull();
199 + expect(parseThreadLinkHref("https://evil.test/threads/env-1/thread-1")).toBeNull();
200 + });
201 +
202 + it("writes a copied link a reader can follow, labeled when it has a title", () => {
203 + expect(formatHostedThreadLink(ref("e", "t1"), "Fix [ci]")).toBe(
204 + "[Fix ci](https://app.t3.codes/threads/e/t1)",
205 + );
206 + expect(formatHostedThreadLink(ref("e", "t1"), " ")).toBe("https://app.t3.codes/threads/e/t1");
207 + });
208 +
209 + it("titles hosted links in every Markdown form and writes them as v2 links", () => {
210 + const title = titlesIn({ there: { t1: "There" } });
211 + expect(
212 + relabelThreadLinks(
213 + [
214 + "See https://app.t3.codes/threads/there/t1.",
215 + "[old](https://app.t3.codes/threads/there/t1)",
216 + "<https://app.t3.codes/threads/there/t1>",
217 + "`https://app.t3.codes/threads/there/t1`",
218 + "https://app.t3.codes/threads/there/t1?prompt=go",
219 + ].join("\n"),
220 + local,
221 + title,
222 + ),
223 + ).toBe(
224 + [
225 + "See [There](t3-thread://v2/there/t1).",
226 + "[There](t3-thread://v2/there/t1)",
227 + "[There](t3-thread://v2/there/t1)",
228 + "`https://app.t3.codes/threads/there/t1`",
229 + "https://app.t3.codes/threads/there/t1?prompt=go",
230 + ].join("\n"),
231 + );
232 + expect(
233 + relabelThreadLinks("https://app.t3.codes/threads/there/t1", local, () => undefined),
234 + ).toBe("Thread on another machine");
235 + expect(threadLinkRefs("Open https://app.t3.codes/threads/there/t%3A1", local)).toEqual([
236 + ref("there", "t:1"),
237 + ]);
238 + });
239 +});
packages/shared/src/threadLinks.ts
+81 -20
@@ -2,12 +2,19 @@ import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contract
2 import * as Option from "effect/Option";
3 import * as Schema from "effect/Schema";
4
5 +import { DEFAULT_HOSTED_APP_URL } from "./connectAuth.ts";
6 +
7 export const THREAD_LINK_PROTOCOL = "t3-thread";
8 const V1_PREFIX = `${THREAD_LINK_PROTOCOL}://v1/`;
9 const V2_PREFIX = `${THREAD_LINK_PROTOCOL}://v2/`;
10 +const HOSTED_PREFIX = `${DEFAULT_HOSTED_APP_URL}/threads/`;
11 +const HOSTED_SEGMENT = "[A-Za-z0-9_%-]+";
12 +const HOSTED_LINK = `${HOSTED_PREFIX.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}${HOSTED_SEGMENT}/${HOSTED_SEGMENT}`;
13 // Code comes first in the alternation so a link written inside a code span or fence is skipped.
9 -const THREAD_LINK_OUTSIDE_CODE =
10 - /(?<fence>(`{3,}|~{3,})[\s\S]*?(?:\2|$))|(?<span>(`+)[^\n]*?\4)|\[(?<label>[^\]\n]*)\]\((?<href>t3-thread:\/\/v[12]\/[^\s)]+)\)|<(?<autolink>t3-thread:\/\/v[12]\/[^\s<>]+)>/g;
14 +const THREAD_LINK_OUTSIDE_CODE = new RegExp(
15 + String.raw`(?<fence>(\`{3,}|~{3,})[\s\S]*?(?:\2|$))|(?<span>(\`+)[^\n]*?\4)|\[(?<label>[^\]\n]*)\]\((?<href>t3-thread:\/\/v[12]\/[^\s)]+|${HOSTED_LINK})\)|<(?<autolink>t3-thread:\/\/v[12]\/[^\s<>]+|${HOSTED_LINK})>|(?<bare>${HOSTED_LINK})(?![\w%/?#-])`,
16 + "g",
17 +);
18
19 const decodeThreadId = Schema.decodeUnknownOption(ThreadId);
20 const decodeEnvironmentId = Schema.decodeUnknownOption(EnvironmentId);
@@ -18,8 +25,39 @@ export interface ThreadLink {
25 readonly threadId: ThreadId;
26 }
27
21 -/** The ids as written. Thread ids can hold percent escapes of their own, so they are not decoded. */
28 +// Escapes even URL-safe punctuation, so a sentence's closing period never reads as part of an id.
29 +const hostedSegment = (id: string) =>
30 + encodeURIComponent(id).replace(
31 + /[.!~*'()]/g,
32 + (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
33 + );
34 +
35 +/** Opens the thread from anywhere: the hosted app offers the desktop app, the mobile app, or itself. */
36 +export function hostedThreadLink(ref: ScopedThreadRef, origin = DEFAULT_HOSTED_APP_URL): string {
37 + const path = `/threads/${hostedSegment(ref.environmentId)}/${hostedSegment(ref.threadId)}`;
38 + return new URL(path, origin).toString();
39 +}
40 +
41 +const HOSTED_PATH = new RegExp(`^(${HOSTED_SEGMENT})/(${HOSTED_SEGMENT})$`);
42 +
43 +function parseHostedThreadLink(href: string): ThreadLink | null {
44 + const match = HOSTED_PATH.exec(href.slice(HOSTED_PREFIX.length));
45 + if (!match) return null;
46 + try {
47 + const environmentId = Option.getOrNull(decodeEnvironmentId(decodeURIComponent(match[1]!)));
48 + const threadId = Option.getOrNull(decodeThreadId(decodeURIComponent(match[2]!)));
49 + return environmentId === null || threadId === null ? null : { environmentId, threadId };
50 + } catch {
51 + return null;
52 + }
53 +}
54 +
55 +/**
56 + * The ids as written. Thread ids can hold percent escapes of their own, so they are not decoded,
57 + * except in a hosted link, which escapes them itself.
58 + */
59 export function parseThreadLinkHref(href: string): ThreadLink | null {
60 + if (href.startsWith(HOSTED_PREFIX)) return parseHostedThreadLink(href);
61 if (href.startsWith(V1_PREFIX)) {
62 const threadId = Option.getOrNull(decodeThreadId(href.slice(V1_PREFIX.length)));
63 return threadId === null ? null : { environmentId: null, threadId };
@@ -78,17 +116,31 @@ function threadLinkHref(link: ThreadLink): string {
116 : `${V2_PREFIX}${link.environmentId}/${link.threadId}`;
117 }
118
81 -/** Without a label, an autolink: clients show the thread's current title. */
82 -export function formatThreadLink(ref: ThreadLink, label?: string): string {
83 - const cleaned = label
119 +const linkLabel = (label: string | undefined) =>
120 + label
121 ?.replace(/[[\]\\\r\n]/g, " ")
122 .replace(/\s+/g, " ")
123 .trim();
124 +
125 +/** Without a label, an autolink: clients show the thread's current title. */
126 +export function formatThreadLink(ref: ThreadLink, label?: string): string {
127 + const cleaned = linkLabel(label);
128 return cleaned ? `[${cleaned}](${threadLinkHref(ref)})` : `<${threadLinkHref(ref)}>`;
129 }
130
131 +/** What a person copies out of T3 Code: a Markdown link that opens the thread anywhere. */
132 +export function formatHostedThreadLink(
133 + ref: ScopedThreadRef,
134 + label: string,
135 + origin?: string,
136 +): string {
137 + const href = hostedThreadLink(ref, origin);
138 + const cleaned = linkLabel(label);
139 + return cleaned ? `[${cleaned}](${href})` : href;
140 +}
141 +
142 export function hasThreadLinks(markdown: string): boolean {
91 - return markdown.includes(`${THREAD_LINK_PROTOCOL}://v`);
143 + return markdown.includes(`${THREAD_LINK_PROTOCOL}://v`) || markdown.includes(HOSTED_PREFIX);
144 }
145
146 /** Every thread the markdown's links can name, so their titles are keyed reads. */
@@ -100,7 +152,7 @@ export function threadLinkRefs(
152 // Hermes' matchAll yields matches without `groups`; exec keeps them.
153 const pattern = new RegExp(THREAD_LINK_OUTSIDE_CODE);
154 for (let match = pattern.exec(markdown); match !== null; match = pattern.exec(markdown)) {
103 - const href = match.groups?.href ?? match.groups?.autolink;
155 + const href = match.groups?.href ?? match.groups?.autolink ?? match.groups?.bare;
156 const link = href === undefined ? null : parseThreadLinkHref(href);
157 if (link === null) continue;
158 for (const ref of threadLinkCandidates(link, messageEnvironmentId)) {
@@ -119,22 +171,31 @@ export function unknownThreadLinkLabel(
171 : "Thread on another machine";
172 }
173
174 +/** Rewrites each link outside code `replace` answers for. `label` is a Markdown link's own text. */
175 +export function replaceThreadLinks(
176 + markdown: string,
177 + replace: (link: ThreadLink, label: string | undefined) => string | undefined,
178 +): string {
179 + if (!hasThreadLinks(markdown)) return markdown;
180 + return markdown.replace(THREAD_LINK_OUTSIDE_CODE, (source, ...args) => {
181 + const groups = args.at(-1) as Partial<Record<"href" | "autolink" | "bare" | "label", string>>;
182 + const href = groups.href ?? groups.autolink ?? groups.bare;
183 + const link = href === undefined ? null : parseThreadLinkHref(href);
184 + return (link && replace(link, groups.label)) ?? source;
185 + });
186 +}
187 +
188 /**
123 - * Writes each link with its thread's current title. A link `title` cannot resolve becomes plain
124 - * text, its written label or a neutral one, except a labeled v1 link, which may open elsewhere.
189 + * Writes each link with its thread's current title, a hosted link as a v2 link. A link `title`
190 + * cannot resolve becomes plain text, its written label or a neutral one, except a labeled v1
191 + * link, which may open elsewhere.
192 */
193 export function relabelThreadLinks(
194 markdown: string,
195 messageEnvironmentId: EnvironmentId,
196 title: (ref: ScopedThreadRef) => string | undefined,
197 ): string {
131 - if (!hasThreadLinks(markdown)) return markdown;
132 - return markdown.replace(THREAD_LINK_OUTSIDE_CODE, (source, ...args) => {
133 - const groups = args.at(-1) as { href?: string; autolink?: string; label?: string };
134 - const href = groups.href ?? groups.autolink;
135 - if (href === undefined) return source;
136 - const written = parseThreadLinkHref(href);
137 - if (written === null) return source;
198 + return replaceThreadLinks(markdown, (written, label) => {
199 const environmentId = written.environmentId ?? messageEnvironmentId;
200 const decoded = percentDecodedThreadLinkId(written.threadId);
201 const threadId =
@@ -145,12 +206,12 @@ export function relabelThreadLinks(
206 : written.threadId;
207 const current = title({ environmentId, threadId });
208 if (current === undefined) {
148 - if (groups.href !== undefined && written.environmentId === null) return source;
149 - return groups.label?.trim() || unknownThreadLinkLabel(written, messageEnvironmentId);
209 + if (label !== undefined && written.environmentId === null) return undefined;
210 + return label?.trim() || unknownThreadLinkLabel(written, messageEnvironmentId);
211 }
212 return formatThreadLink(
213 { environmentId: written.environmentId, threadId },
153 - current.trim() || groups.label || threadId,
214 + current.trim() || label || threadId,
215 );
216 });
217 }