TypeScript
feat(server,web,mobile,desktop): Copy thread copies a link that opens the thread (#26290)
Julius Marminge251369d31cfd
diff --git a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.kt b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.ktindex 1703a767020..fd48492a11c 100644--- a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.kt+++ b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.kt@@ -9,6 +9,10 @@ import org.json.JSONObjectimport org.json.JSONArrayinternal object T3ComposerClipboard {+ // Pasted thread links become chips in JS; packages/shared/src/threadLinks.ts parses them.+ fun hasThreadLink(text: String): Boolean =+ text.contains("t3-thread://v2/") || text.contains("https://app.t3.codes/threads/")+fun write(context: Context, text: String, fragment: String) {val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManagerval payload = try {diff --git a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.ktindex efa54e2ec37..6b0534fdacc 100644--- a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt+++ b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorView.kt@@ -735,11 +735,24 @@ internal class SelectionAwareEditText(private fun pasteContextOrImages(): Boolean {val payload = T3ComposerClipboard.read(context)- if (payload["html"]?.contains("data-t3-context-fragment=") == true) {- pasteContextListener?.invoke(payload)- return true+ return when {+ payload["html"]?.contains("data-t3-context-fragment=") == true -> pasteContext(payload)+ pasteImagesOrInterceptedText() -> true+ isSingleItemClip() && T3ComposerClipboard.hasThreadLink(payload["text"].orEmpty()) ->+ pasteContext(payload)+ else -> false}- return pasteImagesOrInterceptedText()+ }++ // read() sees only the first item; native paste keeps every item of a longer clip.+ private fun isSingleItemClip(): Boolean {+ val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager+ return clipboard?.primaryClip?.itemCount == 1+ }++ private fun pasteContext(payload: Map<String, String>): Boolean {+ pasteContextListener?.invoke(payload)+ return true}private fun pasteImagesOrInterceptedText(): Boolean {diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swiftindex 99504e6de89..e16582ce2b5 100644--- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift+++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift@@ -4,6 +4,11 @@ import UIKitenum T3ComposerClipboard {static let fragmentType = "app.t3.context-fragment"+ // Pasted thread links become chips in JS; packages/shared/src/threadLinks.ts parses them.+ static func hasThreadLink(_ text: String) -> Bool {+ text.contains("t3-thread://v2/") || text.contains("https://app.t3.codes/threads/")+ }+static func write(text: String, fragment: String) {var items: [String: Any] = ["public.utf8-plain-text": text]if let data = fragment.data(using: .utf8),diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swiftindex f54f75caf5f..188ab4a97b3 100644--- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift+++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift@@ -226,6 +226,12 @@ private final class ComposerTextView: UITextView {onPasteText?(text, selectedRange)return}+ // read() sees only the first item; native paste keeps every item of a longer pasteboard.+ if !bypassTextPasteInterception, pasteboard.numberOfItems == 1,+ T3ComposerClipboard.hasThreadLink(context["text", default: ""]) {+ onPasteContext?(context)+ return+ }super.paste(sender)}diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsxindex e411b6a2b63..682f2cdb6b2 100644--- a/apps/mobile/src/features/threads/ThreadFeed.tsx+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx@@ -61,7 +61,7 @@ import {} from "@t3tools/contracts";import { renderAssistantCitationsAsText } from "@t3tools/shared/assistantCitations";import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";-import { parseThreadLinkHref } from "@t3tools/shared/threadLinks";+import { hostedThreadLink, parseThreadLinkHref } from "@t3tools/shared/threadLinks";import { PROMPT_LINK_MAX_PROMPT_LENGTH } from "@t3tools/shared/promptLinks";import {parseComposerContextHref,@@ -3058,9 +3058,10 @@ export const ThreadFeed = memo(function ThreadFeed({else if (actionId === "copy-skill") copyTextWithHaptic(`$${skill.name}`);return;}- if (resolveLinkedThread(href)) {+ const thread = resolveLinkedThread(href);+ if (thread) {if (actionId === "open-thread") onMarkdownLinkPress(href);- else if (actionId === "copy-thread-link") copyTextWithHaptic(href);+ else if (actionId === "copy-thread-link") copyTextWithHaptic(hostedThreadLink(thread));return;}const target = resolveFileChipTarget(href, props.workspaceRoot);diff --git a/apps/mobile/src/lib/composerContextClipboard.test.ts b/apps/mobile/src/lib/composerContextClipboard.test.tsindex b3fea2e6ded..77305cce844 100644--- a/apps/mobile/src/lib/composerContextClipboard.test.ts+++ b/apps/mobile/src/lib/composerContextClipboard.test.ts@@ -42,6 +42,9 @@ vi.mock("../state/session", () => ({environmentSession: { preparedConnectionValueAtom: vi.fn() },}));vi.mock("../state/assets", () => ({ assetEnvironment: { createUrl: (value: unknown) => value } }));+vi.mock("../state/threads", () => ({+ environmentThreadShells: { threadShellAtom: (value: unknown) => value },+}));vi.mock("../state/use-composer-drafts", () => ({waitForComposerDraftsLoaded: async () => {},findLocalComposerClipboardAttachment: mocks.local,@@ -336,4 +339,34 @@ describe("mobile context clipboard imports", () => {collectComposerContextReferences(result!.text).map((reference) => reference.contextId),).toEqual(result!.context.records.map((record) => record.contextId));});++ it("pastes a thread link as a chip only where the destination's agent reads its machine", async () => {+ const text = [+ "https://app.t3.codes/threads/destination/local-thread",+ "<t3-thread://v2/source/foreign-thread>",+ ].join(" ");+ const result = await importComposerContextClipboard(+ { text, fragment: "", html: "" },+ 0,+ new AbortController().signal,+ 0,+ EnvironmentId.make("destination"),+ );+ const [record] = result!.context.records;+ expect(record).toMatchObject({+ kind: "thread",+ environmentId: "destination",+ threadId: "local-thread",+ });+ expect(result!.text).toBe(+ `[Thread](t3-context://v1/thread/${record!.contextId}) <t3-thread://v2/source/foreign-thread>`,+ );+ expect(+ await importComposerContextClipboard(+ { text: "plain text", fragment: "", html: "" },+ 0,+ new AbortController().signal,+ ),+ ).toBeNull();+ });});diff --git a/apps/mobile/src/lib/composerContextClipboard.ts b/apps/mobile/src/lib/composerContextClipboard.tsindex 971191456cc..8c5a31cdb7e 100644--- a/apps/mobile/src/lib/composerContextClipboard.ts+++ b/apps/mobile/src/lib/composerContextClipboard.ts@@ -13,13 +13,17 @@ import {decodeComposerContextFragment,encodeComposerContextFragment,} from "@t3tools/shared/composerContextClipboard";-import { threadContextsOutsideEnvironment } from "@t3tools/shared/composerContextReferences";+import {+ threadContextsOutsideEnvironment,+ threadLinkContextReferences,+} from "@t3tools/shared/composerContextReferences";import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";import * as Option from "effect/Option";import { appAtomRegistry } from "../state/atom-registry";import { assetEnvironment } from "../state/assets";import { environmentSession } from "../state/session";+import { environmentThreadShells } from "../state/threads";import { workspaceConnections } from "../state/workspace";import { downloadAttachmentForPreview } from "./attachmentDownload";import {@@ -71,11 +75,38 @@ export async function importComposerContextClipboard(/** The machines the destination links to, whose threads its agent can read too. */linkedEnvironments: ReadonlyMap<EnvironmentId, string> = new Map(),) {- const fragment =+ const copied =decodeComposerContextFragment(input.fragment) ?? decodeComposerContextClipboardHtml(input.html);- if (!fragment) return null;- const selected = referencedComposerContext(input.text, { version: 1, records: fragment.records });- const imported = reidentifyComposerContext(input.text, selected?.records ?? [], uuidv4);+ // A thread link becomes a chip only where this agent can read its machine; others stay links.+ const threads = threadLinkContextReferences(+ input.text,+ copied?.records ?? [],+ (ref) => appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref))?.title,+ (record) =>+ destinationEnvironmentId === undefined ||+ record.environmentId === destinationEnvironmentId ||+ linkedEnvironments.has(record.environmentId)+ ? record.contextId+ : undefined,+ );+ const source =+ copied?.source ??+ (threads.records[0] ? { environmentId: threads.records[0].environmentId } : null);+ if (!source) return null;+ const fragment = {+ source,+ records: [+ ...(copied?.records ?? []).filter((record) =>+ threads.records.every((thread) => thread.contextId !== record.contextId),+ ),+ ...threads.records,+ ],+ };+ const selected = referencedComposerContext(threads.text, {+ version: 1,+ records: fragment.records,+ });+ const imported = reidentifyComposerContext(threads.text, selected?.records ?? [], uuidv4);const skippedThreads =destinationEnvironmentId === undefined? []diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.tsindex 0fb7f10d2ba..3f4d7ff51f8 100644--- a/apps/server/src/auth/McpOAuth.ts+++ b/apps/server/src/auth/McpOAuth.ts@@ -17,6 +17,7 @@ import {mcpClientScopes,type RuntimeMode,} from "@t3tools/contracts";+import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";import { encodeOAuthScope } from "@t3tools/shared/oauthScope";import * as Clock from "effect/Clock";import * as Context from "effect/Context";@@ -30,6 +31,7 @@ import * as Ref from "effect/Ref";import * as Schema from "effect/Schema";import { HttpServerRequest } from "effect/http";+import { hostedAppUrlConfig } from "../cloud/publicConfig.ts";import * as ServerEnvironment from "../environment/ServerEnvironment.ts";import * as ServerSettings from "../serverSettings.ts";import * as McpHttpServer from "../mcp/McpHttpServer.ts";@@ -577,6 +579,13 @@ export const layerMcpClientAuthenticator = Layer.effect(const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;const environment = yield* ServerEnvironment.ServerEnvironment;const environmentId = yield* environment.getEnvironmentId;+ const hostedAppUrl = yield* hostedAppUrlConfig.pipe(+ Effect.catch((cause) =>+ Effect.logWarning("Outside MCP clients get app.t3.codes thread links", { cause }).pipe(+ Effect.as(DEFAULT_HOSTED_APP_URL),+ ),+ ),+ );return McpHttpServer.McpClientAuthenticator.of({authenticate: Effect.fn("McpHttpServer.McpClientAuthenticator.authenticate")(function (request) {@@ -592,7 +601,7 @@ export const layerMcpClientAuthenticator = Layer.effect(label: client.label,access: client.access,linked: client.peerLink,- ...(client.peerLink ? {} : { webOrigin: requestUrls(request).issuer }),+ ...(client.peerLink ? {} : { hostedAppUrl }),},capabilities: new Set<McpInvocationContext.McpCapability>(["orchestration",diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.tsindex 181ac3a9cfb..842d18ad9c8 100644--- a/apps/server/src/mcp/McpInvocationContext.ts+++ b/apps/server/src/mcp/McpInvocationContext.ts@@ -12,7 +12,7 @@ import {import * as Context from "effect/Context";import * as Effect from "effect/Effect";import * as Fiber from "effect/Fiber";-import { formatThreadLink } from "@t3tools/shared/threadLinks";+import { formatThreadLink, hostedThreadLink } from "@t3tools/shared/threadLinks";const ALL_MCP_CAPABILITIES = ["preview",@@ -45,8 +45,8 @@ export interface McpClientCaller {* another environment passing on the limits of the agent it calls for.*/readonly narrowedTo?: ClientModes | undefined;- /** The origin an outside client reached; its thread links open the web app there. */- readonly webOrigin?: string | undefined;+ /** An outside client's thread links go through this hosted app, as Copy thread's do. */+ readonly hostedAppUrl?: string | undefined;}/**@@ -135,16 +135,15 @@ export interface McpInvocationScope {/*** T3 Code renders `t3-thread://` links as thread chips. Other MCP clients cannot open them, so- * they get a web URL on the origin they reached instead.+ * they get the hosted link Copy thread copies, which opens the thread in either app or a browser.*/export const threadLinkFor = (scope: Pick<McpInvocationScope, "environmentId" | "client">,threadId: ThreadId,): string => {- const origin = scope.client?.webOrigin;- return origin === undefined- ? formatThreadLink({ environmentId: scope.environmentId, threadId })- : `${origin}/${encodeURIComponent(scope.environmentId)}/${encodeURIComponent(threadId)}`;+ const hostedAppUrl = scope.client?.hostedAppUrl;+ const ref = { environmentId: scope.environmentId, threadId };+ return hostedAppUrl === undefined ? formatThreadLink(ref) : hostedThreadLink(ref, hostedAppUrl);};export class McpInvocationContext extends Context.Service<diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.tsindex 8d7369bc85e..6721e894785 100644--- a/apps/server/src/mcp/toolkits/project/handlers.test.ts+++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts@@ -50,7 +50,7 @@ const clientLaunchHarness = (input: {readonly launched: Array<ThreadLaunch.ThreadLaunchInput>;readonly workspaceRoot?: string;readonly checkWorktreeBase?: ThreadLaunch.ThreadLaunchService["Service"]["checkWorktreeBase"];- readonly webOrigin?: string;+ readonly hostedAppUrl?: string;/** The orchestrator refuses the new thread's mode, as under a managed ceiling. */readonly refusedByCeiling?: true;}) => {@@ -89,7 +89,7 @@ const clientLaunchHarness = (input: {sessionId: "session-1",label: "Claude Code",access: input.runtimeModeCeiling,- webOrigin: input.webOrigin,+ hostedAppUrl: input.hostedAppUrl,},issuedAt: 0,capabilities: new Set(["orchestration" as const]),@@ -187,18 +187,18 @@ it.effect(readonly runtimeMode?: RuntimeMode;readonly targeted?: false;readonly overrideModel?: ModelSelection;- readonly webOrigin?: string;+ readonly hostedAppUrl?: string;readonly refusedByCeiling?: true;},) {- const { targeted, overrideModel, webOrigin, refusedByCeiling, ...input } = params;+ const { targeted, overrideModel, hostedAppUrl, refusedByCeiling, ...input } = params;const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];const { projectId, modelSelection, dependencies } = clientLaunchHarness({runtimeModeCeiling,defaultRuntimeMode,launched,...(overrideModel === undefined ? {} : { overrideModel }),- ...(webOrigin === undefined ? {} : { webOrigin }),+ ...(hostedAppUrl === undefined ? {} : { hostedAppUrl }),...(refusedByCeiling === undefined ? {} : { refusedByCeiling }),});const toolkit = yield* ProjectToolkit.pipe(@@ -228,11 +228,11 @@ it.effect(const aboveCeiling = yield* launchWith("auto-accept-edits", "full-access", {title: "Fix",- webOrigin: "https://box.example.ts.net",+ hostedAppUrl: "https://t3.example.com",});expect(aboveCeiling.launched[0]?.runtimeMode).toBe("auto-accept-edits");expect(aboveCeiling.result).toMatchObject({- link: `https://box.example.ts.net/environment/${encodeURIComponent(aboveCeiling.launched[0]?.threadId ?? "")}`,+ link: `https://t3.example.com/threads/environment/${encodeURIComponent(aboveCeiling.launched[0]?.threadId ?? "")}`,});const requested = yield* launchWith("full-access", "approval-required", {diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex a1c1c7bc91a..d1225065aee 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -5,6 +5,7 @@ import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits";import { queuedRunEditBlockedReason } from "@t3tools/client-runtime/queued-run-edit";import { ScrollToEndButton, WorkspaceFileDropOverlay } from "./chat/TimelineOverlays";import { usePasteToFocusComposer } from "./chat/usePasteToFocusComposer";+import { configuredHostedAppUrl } from "../hostedPairing";import { announcedRun, isDetailBehindShell } from "./chat/threadActivityAnnouncement";import {deriveAvailableRevertTurnCounts,@@ -2322,6 +2323,7 @@ export default function ChatView(props: ChatViewProps) {openPanelPullRequestUrl,pullRequests: activeThread?.pullRequests,linkedPullRequestUrl: linkedThreadPullRequest?.url ?? null,+ hostedAppUrl: configuredHostedAppUrl(),});const copyActiveThreadReference = () => {if (activeThreadReferenceCopyTarget === null) return;diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsxindex ddac4fc4d7c..f14a483d533 100644--- a/apps/web/src/components/CommandPalette.tsx+++ b/apps/web/src/components/CommandPalette.tsx@@ -106,6 +106,7 @@ import {import { useClientSettings } from "../hooks/useSettings";import { useStableCallback } from "../hooks/useStableCallback";import { readLocalApi } from "../localApi";+import { configuredHostedAppUrl } from "../hostedPairing";import { desktopLocalBackendId } from "../connection/desktopLocal";import { filesystemEnvironment, useFilesystemReadAccess } from "../state/filesystem";import { projectEnvironment } from "../state/projects";@@ -489,6 +490,7 @@ function OpenCommandPaletteDialog(props: {pullRequests: activeThread?.pullRequests,linkedPullRequestUrl:activeThread?.linkedPullRequest?.url ?? activeThread?.branchPullRequest?.url ?? null,+ hostedAppUrl: configuredHostedAppUrl(),});const copyActiveThreadReference = async () => {if (activeThreadReferenceCopyTarget === null) return;diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsxindex 868aa85cec6..18aa27709e4 100644--- a/apps/web/src/components/Sidebar.tsx+++ b/apps/web/src/components/Sidebar.tsx@@ -103,6 +103,7 @@ import { isModelPickerOpen } from "../modelPickerVisibility";import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";import { isMacPlatform } from "~/lib/utils";import { readLocalApi } from "../localApi";+import { configuredHostedAppUrl } from "../hostedPairing";import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore";import {pickableProjectGroups,@@ -2809,7 +2810,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve}return;case "copy-thread":- void copyThreadReference(threadChipCopyTarget(threadRef, thread.title));+ void copyThreadReference(+ threadChipCopyTarget(threadRef, thread.title, configuredHostedAppUrl()),+ );return;case "copy-thread-id":copyThreadIdToClipboard(thread.id, { threadId: thread.id });diff --git a/apps/web/src/components/chat/MarkdownThreadLink.tsx b/apps/web/src/components/chat/MarkdownThreadLink.tsxindex 68ab4cd569e..f3e95c026be 100644--- a/apps/web/src/components/chat/MarkdownThreadLink.tsx+++ b/apps/web/src/components/chat/MarkdownThreadLink.tsx@@ -1,13 +1,14 @@import { scopeThreadRef } from "@t3tools/client-runtime/environment";import type { EnvironmentId } from "@t3tools/contracts";import {- formatThreadLink,+ formatHostedThreadLink,guessThreadLinkRef,percentDecodedThreadLinkId,type ThreadLink,unknownThreadLinkLabel,} from "@t3tools/shared/threadLinks";+import { configuredHostedAppUrl } from "../../hostedPairing";import { useThreadRefs, useThreadShell } from "../../state/entities";import { UnresolvedChip } from "../contextChipParts";import { ThreadContextChip } from "../ThreadContextChip";@@ -36,6 +37,9 @@ export function MarkdownThreadLink(props: {const ref = { environmentId: thread.environmentId, threadId: thread.id };const title = thread.title.trim() || props.label || "Untitled thread";return (- <ThreadContextChip record={{ ...ref, title }} copyMarkdown={formatThreadLink(ref, title)} />+ <ThreadContextChip+ record={{ ...ref, title }}+ copyMarkdown={formatHostedThreadLink(ref, title, configuredHostedAppUrl())}+ />);}diff --git a/apps/web/src/components/composerInlineTokenPaste.test.ts b/apps/web/src/components/composerInlineTokenPaste.test.tsnew file mode 100644index 00000000000..1ab28a5b7ff--- /dev/null+++ b/apps/web/src/components/composerInlineTokenPaste.test.ts@@ -0,0 +1,59 @@+import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference";+import { type ComposerContextClipboardFragment, EnvironmentId, ThreadId } from "@t3tools/contracts";+import {+ COMPOSER_CONTEXT_CLIPBOARD_MIME,+ encodeComposerContextFragment,+} from "@t3tools/shared/composerContextClipboard";+import { threadContextRecord } from "@t3tools/shared/composerContextReferences";+import { describe, expect, it } from "vite-plus/test";++import { importPastedComposerText } from "./composerInlineTokenPaste";++const thread = {+ environmentId: EnvironmentId.make("env-1"),+ threadId: ThreadId.make("thread-1"),+};+const clipboard = (data: Record<string, string>) => ({+ getData: (type: string) => data[type] ?? "",+});+const chip = (title: string) =>+ `[${title}](t3-context://v1/thread/${threadContextRecord(thread, title).contextId})`;++/** Imports every record it is offered, as the composer does for a thread its agent can read. */+const importAll =+ (imported: Array<ComposerContextClipboardFragment>) =>+ (fragment: ComposerContextClipboardFragment) => {+ imported.push(fragment);+ return new Map(fragment.records.map((record) => [record.contextId, record.contextId]));+ };++describe("importPastedComposerText", () => {+ it("pastes a copied thread link back as the chip it was copied from", () => {+ const target = threadChipCopyTarget(thread, "Fix the login flow");+ const imported: Array<ComposerContextClipboardFragment> = [];+ const text = importPastedComposerText(+ clipboard({+ "text/plain": `See ${target.value}`,+ [COMPOSER_CONTEXT_CLIPBOARD_MIME]: encodeComposerContextFragment(target.fragment!)!,+ }),+ importAll(imported),+ );+ expect(text).toBe(`See ${chip("Fix the login flow")}`);+ expect(imported.map((fragment) => fragment.records)).toEqual([target.fragment!.records]);+ });++ it("makes a chip of a v2 link pasted without T3's clipboard format", () => {+ const text = importPastedComposerText(+ clipboard({ "text/plain": "[Login](t3-thread://v2/env-1/thread-1)" }),+ importAll([]),+ );+ expect(text).toBe(chip("Login"));+ });++ it("keeps the link when the composer cannot take the thread", () => {+ const pasted = "https://app.t3.codes/threads/env-1/thread-1";+ expect(importPastedComposerText(clipboard({ "text/plain": pasted }), () => new Map())).toBe(+ pasted,+ );+ });+});diff --git a/apps/web/src/components/composerInlineTokenPaste.ts b/apps/web/src/components/composerInlineTokenPaste.tsindex 32722ad6a95..0862f81ee83 100644--- a/apps/web/src/components/composerInlineTokenPaste.ts+++ b/apps/web/src/components/composerInlineTokenPaste.ts@@ -1,5 +1,9 @@import { ComposerContextId } from "@t3tools/contracts";-import type { ComposerContextClipboardFragment } from "@t3tools/contracts";+import type {+ ComposerContextClipboardFragment,+ ComposerContextRecord,+ ScopedThreadRef,+} from "@t3tools/contracts";import {COMPOSER_CONTEXT_CLIPBOARD_MIME,decodeComposerContextFragment,@@ -9,7 +13,14 @@ import {collectComposerContextReferences,formatComposerContextReference,replaceComposerContextReferences,+ threadLinkContextReferences,} from "@t3tools/shared/composerContextReferences";++import { readThreadShell } from "~/state/entities";++const threadTitle = (ref: ScopedThreadRef) => readThreadShell(ref)?.title;++/** Pasted thread links count as context too, so they become chips like a copied chip does. */export function readPastedComposerContext(clipboardData: Pick<DataTransfer, "getData">,): ComposerContextClipboardFragment | null {@@ -17,11 +28,20 @@ export function readPastedComposerContext(const decodedFragment =decodeComposerContextFragment(clipboardData.getData(COMPOSER_CONTEXT_CLIPBOARD_MIME)) ??decodeComposerContextClipboardHtml(clipboardData.getData("text/html"));- if (decodedFragment === null) return null;+ const threads = threadLinkContextReferences(+ pastedText,+ decodedFragment?.records ?? [],+ threadTitle,+ );+ const source =+ decodedFragment?.source ??+ (threads.records[0] ? { environmentId: threads.records[0].environmentId } : null);+ if (source === null) return null;const pastedIds = new Set<string>(- collectComposerContextReferences(pastedText).map((occurrence) => occurrence.contextId),+ collectComposerContextReferences(threads.text).map((occurrence) => occurrence.contextId),);- for (const record of decodedFragment.records) {+ const records = new Map<string, ComposerContextRecord>();+ for (const record of [...(decodedFragment?.records ?? []), ...threads.records]) {if (record.kind === "preview-annotation" &&!("payload" in record) &&@@ -30,10 +50,12 @@ export function readPastedComposerContext() {pastedIds.add(record.screenshotContextId);}+ records.set(record.contextId, record);}return {- ...decodedFragment,- records: decodedFragment.records.filter((record) => pastedIds.has(record.contextId)),+ version: 1,+ source,+ records: [...records.values()].filter((record) => pastedIds.has(record.contextId)),};}@@ -47,18 +69,23 @@ export function importPastedComposerText(const fragment = importContextFragment ? readPastedComposerContext(clipboardData) : null;const rewrittenIds =fragment && fragment.records.length > 0 ? importContextFragment!(fragment) : null;- const text =- rewrittenIds && rewrittenIds.size > 0- ? replaceComposerContextReferences(pastedText, (occurrence) => {- const nextId = rewrittenIds.get(occurrence.contextId);- return nextId- ? formatComposerContextReference({- ...occurrence,- contextId: ComposerContextId.make(nextId),- kind: occurrence.kind === "element" ? "preview-annotation" : occurrence.kind,- })- : occurrence.source;+ if (!rewrittenIds || rewrittenIds.size === 0) return pastedText;+ const nextId = (contextId: string) => {+ const id = rewrittenIds.get(contextId);+ return id ? ComposerContextId.make(id) : undefined;+ };+ const text = replaceComposerContextReferences(pastedText, (occurrence) => {+ const contextId = nextId(occurrence.contextId);+ return contextId+ ? formatComposerContextReference({+ ...occurrence,+ contextId,+ kind: occurrence.kind === "element" ? "preview-annotation" : occurrence.kind,})- : pastedText;- return text;+ : occurrence.source;+ });+ // A thread the import refused, on a machine this agent cannot read, stays the link it was.+ return threadLinkContextReferences(text, fragment?.records ?? [], threadTitle, (record) =>+ nextId(record.contextId),+ ).text;}diff --git a/apps/web/src/components/promptLinks/HostedPromptLinkLanding.tsx b/apps/web/src/components/promptLinks/HostedPromptLinkLanding.tsxindex 24facbea191..ca44345e177 100644--- a/apps/web/src/components/promptLinks/HostedPromptLinkLanding.tsx+++ b/apps/web/src/components/promptLinks/HostedPromptLinkLanding.tsx@@ -23,19 +23,36 @@ const OPENER_STORAGE_KEY = "t3code:prompt-link-opener";const Opener = Schema.NullOr(Schema.Literals(["app", "browser"]));interface LinkSummary {+ readonly title: string;+ readonly description: string;readonly prompt: LinkedPrompt | null;readonly details: ReadonlyArray<string>;}+const PROMPT_HEADER = {+ title: "Open this prompt",+ description: "It opens as a draft. Nothing runs until you press Send.",+};+function summarize(appPath: string,): { ok: true; value: LinkSummary } | { ok: false; error: string } {const url = new URL(appPath, window.location.origin);if (url.pathname !== "/new") {const prompt = parseThreadLinkPrompt(url.search);- return prompt.ok- ? { ok: true, value: { prompt: prompt.value, details: ["Opens one of your threads."] } }- : prompt;+ if (!prompt.ok) return prompt;+ return {+ ok: true,+ value:+ prompt.value === null+ ? {+ title: "Open this thread",+ description: "It opens in T3 Code if you're connected to the machine it runs on.",+ prompt: null,+ details: [],+ }+ : { ...PROMPT_HEADER, prompt: prompt.value, details: ["Opens one of your threads."] },+ };}const link = parseNewThreadLink(url.search);if (!link.ok) return link;@@ -43,13 +60,18 @@ function summarize(const { owner, name, number } = link.value.pullRequest;return {ok: true,- value: { prompt: link.value.prompt, details: [`Pull request ${owner}/${name}#${number}`] },+ value: {+ ...PROMPT_HEADER,+ prompt: link.value.prompt,+ details: [`Pull request ${owner}/${name}#${number}`],+ },};}const { repository, provider, model } = link.value;return {ok: true,value: {+ ...PROMPT_HEADER,prompt: link.value.prompt,details: [repository ? `Repository ${repository.owner}/${repository.name}` : "No project",@@ -119,13 +141,10 @@ function HostedPromptLinkLanding({);}- const { prompt, details } = summary.value;+ const { title, description, prompt, details } = summary.value;return (<StandalonePage>- <StandalonePageHeader- title="Open this prompt"- description="It opens as a draft. Nothing runs until you press Send."- />+ <StandalonePageHeader title={title} description={description} />{prompt !== null && prompt.hiddenCharacters > 0 ? (<Alert className="mt-5" variant="error"><AlertTitle>This prompt had hidden characters, it may be malicious</AlertTitle>@@ -140,7 +159,9 @@ function HostedPromptLinkLanding({{prompt.text}</pre>) : null}- <p className="mt-3 text-xs text-muted-foreground">{details.join(" · ")}</p>+ {details.length > 0 ? (+ <p className="mt-3 text-xs text-muted-foreground">{details.join(" · ")}</p>+ ) : null}<div className="mt-6 flex flex-wrap gap-2"><Button render={<a href={deepLink} />} onClick={() => onChoose("app", remember)}>{onPhone ? "Open in app" : "Open in desktop app"}diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.tsindex cddef6046cf..d22b1d9cf6c 100644--- a/apps/web/src/hooks/useThreadActionMenu.ts+++ b/apps/web/src/hooks/useThreadActionMenu.ts@@ -35,6 +35,7 @@ import {} from "../state/entities";import { usePrimaryEnvironmentId } from "../state/environments";import { readLocalApi } from "../localApi";+import { configuredHostedAppUrl } from "../hostedPairing";import {deriveLogicalProjectKeyFromSettings,derivePhysicalProjectKey,@@ -295,7 +296,9 @@ export function useThreadActionMenu(input: {}return;case "copy-thread":- void copyThreadReference(threadChipCopyTarget(threadRef, thread.title));+ void copyThreadReference(+ threadChipCopyTarget(threadRef, thread.title, configuredHostedAppUrl()),+ );return;case "copy-thread-id":copyThreadIdToClipboard(thread.id, { threadId: thread.id });diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.tsindex 0e26ab6edd8..33843126b2a 100644--- a/apps/web/src/routeTree.gen.ts+++ b/apps/web/src/routeTree.gen.ts@@ -21,6 +21,7 @@ import { Route as ChatUsageRouteImport } from './routes/_chat.usage'import { Route as ChatSettingsRouteImport } from './routes/_chat.settings'import { Route as ChatPullRequestsRouteImport } from './routes/_chat.pull-requests'import { Route as ChatNewRouteImport } from './routes/_chat.new'+import { Route as ThreadsEnvironmentIdThreadIdRouteImport } from './routes/threads.$environmentId.$threadId'import { Route as ChatSettingsWorktreesRouteImport } from './routes/_chat.settings.worktrees'import { Route as ChatSettingsThreadsRouteImport } from './routes/_chat.settings.threads'import { Route as ChatSettingsStorageRouteImport } from './routes/_chat.settings.storage'@@ -109,6 +110,12 @@ const ChatNewRoute = ChatNewRouteImport.update({path: '/new',getParentRoute: () => ChatRoute,} as any)+const ThreadsEnvironmentIdThreadIdRoute =+ ThreadsEnvironmentIdThreadIdRouteImport.update({+ id: '/threads/$environmentId/$threadId',+ path: '/threads/$environmentId/$threadId',+ getParentRoute: () => rootRouteImport,+ } as any)const ChatSettingsWorktreesRoute = ChatSettingsWorktreesRouteImport.update({id: '/worktrees',path: '/worktrees',@@ -295,6 +302,7 @@ export interface FileRoutesByFullPath {'/settings/storage': typeof ChatSettingsStorageRoute'/settings/threads': typeof ChatSettingsThreadsRoute'/settings/worktrees': typeof ChatSettingsWorktreesRoute+ '/threads/$environmentId/$threadId': typeof ThreadsEnvironmentIdThreadIdRoute}export interface FileRoutesByTo {'/connect': typeof ConnectRoute@@ -336,6 +344,7 @@ export interface FileRoutesByTo {'/settings/storage': typeof ChatSettingsStorageRoute'/settings/threads': typeof ChatSettingsThreadsRoute'/settings/worktrees': typeof ChatSettingsWorktreesRoute+ '/threads/$environmentId/$threadId': typeof ThreadsEnvironmentIdThreadIdRoute}export interface FileRoutesById {__root__: typeof rootRouteImport@@ -379,6 +388,7 @@ export interface FileRoutesById {'/_chat/settings/storage': typeof ChatSettingsStorageRoute'/_chat/settings/threads': typeof ChatSettingsThreadsRoute'/_chat/settings/worktrees': typeof ChatSettingsWorktreesRoute+ '/threads/$environmentId/$threadId': typeof ThreadsEnvironmentIdThreadIdRoute}export interface FileRouteTypes {fileRoutesByFullPath: FileRoutesByFullPath@@ -422,6 +432,7 @@ export interface FileRouteTypes {| '/settings/storage'| '/settings/threads'| '/settings/worktrees'+ | '/threads/$environmentId/$threadId'fileRoutesByTo: FileRoutesByToto:| '/connect'@@ -463,6 +474,7 @@ export interface FileRouteTypes {| '/settings/storage'| '/settings/threads'| '/settings/worktrees'+ | '/threads/$environmentId/$threadId'id:| '__root__'| '/_chat'@@ -505,6 +517,7 @@ export interface FileRouteTypes {| '/_chat/settings/storage'| '/_chat/settings/threads'| '/_chat/settings/worktrees'+ | '/threads/$environmentId/$threadId'fileRoutesById: FileRoutesById}export interface RootRouteChildren {@@ -515,6 +528,7 @@ export interface RootRouteChildren {PairRoute: typeof PairRouteWelcomeRoute: typeof WelcomeRouteProjectsProjectKeyRoute: typeof ProjectsProjectKeyRoute+ ThreadsEnvironmentIdThreadIdRoute: typeof ThreadsEnvironmentIdThreadIdRoute}declare module '@tanstack/react-router' {@@ -603,6 +617,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof ChatNewRouteImportparentRoute: typeof ChatRoute}+ '/threads/$environmentId/$threadId': {+ id: '/threads/$environmentId/$threadId'+ path: '/threads/$environmentId/$threadId'+ fullPath: '/threads/$environmentId/$threadId'+ preLoaderRoute: typeof ThreadsEnvironmentIdThreadIdRouteImport+ parentRoute: typeof rootRouteImport+ }'/_chat/settings/worktrees': {id: '/_chat/settings/worktrees'path: '/worktrees'@@ -894,6 +915,7 @@ const rootRouteChildren: RootRouteChildren = {PairRoute: PairRoute,WelcomeRoute: WelcomeRoute,ProjectsProjectKeyRoute: ProjectsProjectKeyRoute,+ ThreadsEnvironmentIdThreadIdRoute: ThreadsEnvironmentIdThreadIdRoute,}export const routeTree = rootRouteImport._addFileChildren(rootRouteChildren)diff --git a/apps/web/src/routes/threads.$environmentId.$threadId.tsx b/apps/web/src/routes/threads.$environmentId.$threadId.tsxnew file mode 100644index 00000000000..e3583b0737f--- /dev/null+++ b/apps/web/src/routes/threads.$environmentId.$threadId.tsx@@ -0,0 +1,9 @@+import { Navigate, createFileRoute } from "@tanstack/react-router";++// A copied thread link. On the hosted app its chooser shows first; this opens the thread after it.+export const Route = createFileRoute("/threads/$environmentId/$threadId")({+ component: function ThreadLinkRedirect() {+ const params = Route.useParams();+ return <Navigate to="/$environmentId/$threadId" params={params} search replace />;+ },+});diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.mdindex 41146da1ed4..2f6ba536370 100644--- a/docs/orchestration-v2/orchestrator-mcp-server.md+++ b/docs/orchestration-v2/orchestrator-mcp-server.md@@ -412,8 +412,9 @@ know renders as a label that opens nothing. Older `t3-thread://v1/<threadId>`links name no environment: clients resolve them in the message's environment,then by a unique match in another enabled environment. An outside OAuth client,one that is not a linked environment, cannot render `t3-thread://` links, so it-gets a web URL on the origin it reached, `<origin>/<environmentId>/<threadId>`,-for threads in this environment.+gets the link Copy thread copies, `https://app.t3.codes/threads/<environmentId>/<threadId>`+on the server's `T3CODE_HOSTED_APP_URL`, for threads in this environment. The+hosted app offers the desktop app, the mobile app, or itself.List and read results report `snoozed` and `snoozedUntil`, and`t3_thread_list` filters on `snoozed`. The server's `isSnoozed` follows thediff --git a/docs/user/composer.md b/docs/user/composer.mdindex 0008e15fce2..aa670e0b4da 100644--- a/docs/user/composer.md+++ b/docs/user/composer.md@@ -304,14 +304,15 @@ the repository by text. Choose a result to insert it as a chip.Another thread can be context too. Type `@` followed by part of its title to pick one fromthe same server, or from a machine it links to while the Linked environments beta is on; thoseshow the machine's name. On web and desktop you can also drag a thread out of the sidebar and-drop it on the composer; a multi-selection drops together. On any client, **Copy thread** puts a-thread on the clipboard that pastes into a composer as its chip. The chip shows the thread's+drop it on the composer; a multi-selection drops together. On any client, **Copy thread** copies a+link to the thread that pastes into a composer as its chip. The chip shows the thread'scurrent title and opens it when selected. Your prompt only carries a reference: the agent reads the thread'shistory on demand, so attaching a long thread costs nothing until the agent looks. Attaching athread does not change it, and the agent cannot send messages to it unless you ask.A thread from a linked machine, picked, pasted or dropped, stays a reference that the agent reads-on that machine. Dropping a thread from any other environment attaches a saved transcript file. The source+on that machine. A pasted link to a thread on any other machine stays a link. Dropping a thread+from any other environment attaches a saved transcript file. The sourceenvironment must be connected and up to date. The transcript includes the visible history andsaved text context at the time of the drop; later messages and the contents of attached filesare not copied. The agent can read the saved transcript after the source disconnects. Normaldiff --git a/docs/user/prompt-links.md b/docs/user/prompt-links.mdindex 656cf39232a..4553e33e508 100644--- a/docs/user/prompt-links.md+++ b/docs/user/prompt-links.md@@ -54,3 +54,10 @@ before it replaces it.T3 Code removes characters you cannot see, such as zero-width and hidden tag characters, becausethey can hide instructions for the agent. When a prompt had them, T3 Code warns you that it may bemalicious.++## Share a thread++**Copy thread** copies a link such as `https://app.t3.codes/threads/<environment>/<thread>`. Paste+it anywhere, such as Slack, a GitHub comment, or your notes. Opening it asks where to open it, like+a prompt link, then opens the thread. Only someone connected to the machine that runs the thread+can see it. In T3 Code, a thread link in a message opens the thread in the app.diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.mdindex 37f679725f8..6a3145d1751 100644--- a/docs/user/thread-sidebar.md+++ b/docs/user/thread-sidebar.md@@ -230,9 +230,11 @@ palette.Use **Settings → Keybindings** to find or customize shortcuts for searching filesand copying a thread reference. A copied reference uses the thread's pull request-link when available, otherwise the thread itself, which pastes into a composer as-a thread chip. To copy the thread even when it has a PR, choose **Copy → Thread**-from its context menu, or **Copy thread** from its long-press menu on mobile.+link when available, otherwise a link to the thread, which opens it from anywhere+you paste it and pastes into a composer as a thread chip (see+[sharing a thread](./prompt-links.md#share-a-thread)). To copy the thread even+when it has a PR, choose **Copy → Thread** from its context menu, or **Copy+thread** from its long-press menu on mobile.**Thread ID** copies the bare ID for scripts and the `t3` CLI. See[keybindings](./keybindings.md) for custom configuration.diff --git a/packages/client-runtime/src/threadReference.test.ts b/packages/client-runtime/src/threadReference.test.tsindex 9fa3245df57..88905f9cec5 100644--- a/packages/client-runtime/src/threadReference.test.ts+++ b/packages/client-runtime/src/threadReference.test.ts@@ -3,7 +3,7 @@ import {decodeComposerContextFragment,encodeComposerContextFragment,} from "@t3tools/shared/composerContextClipboard";-import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences";+import { threadLinkContextReferences } from "@t3tools/shared/composerContextReferences";import { describe, expect, it } from "vite-plus/test";import { resolveThreadReferenceCopyTarget } from "./threadReference.ts";@@ -98,13 +98,18 @@ describe("resolveThreadReferenceCopyTarget", () => {}),],});- // A paste keeps only the records its plain text references.- expect(collectComposerContextReferences(target!.value)).toEqual([- expect.objectContaining({- kind: "thread",- contextId: pasted!.records[0]!.contextId,- label: "Fix the login flow",- }),- ]);+ // The plain text opens the thread anywhere and pastes back as the copied record's chip.+ expect(target!.value).toBe("https://app.t3.codes/threads/env-1/thread-1");+ expect(threadLinkContextReferences(target!.value, pasted!.records, () => undefined)).toEqual({+ text: `[Fix the login flow](t3-context://v1/thread/${pasted!.records[0]!.contextId})`,+ records: pasted!.records,+ });+ });++ it("links through the build's hosted app", () => {+ expect(+ resolveThreadReferenceCopyTarget({ ...thread, hostedAppUrl: "https://preview.t3.codes" })+ ?.value,+ ).toBe("https://preview.t3.codes/threads/env-1/thread-1");});});diff --git a/packages/client-runtime/src/threadReference.ts b/packages/client-runtime/src/threadReference.tsindex 94f68202a62..17fa5df4589 100644--- a/packages/client-runtime/src/threadReference.ts+++ b/packages/client-runtime/src/threadReference.ts@@ -3,16 +3,14 @@ import type {ScopedThreadRef,ThreadPullRequestLink,} from "@t3tools/contracts";-import {- formatComposerContextReference,- threadContextRecord,-} from "@t3tools/shared/composerContextReferences";+import { threadContextRecord } from "@t3tools/shared/composerContextReferences";+import { hostedThreadLink } from "@t3tools/shared/threadLinks";import { resolveThreadCurrentPullRequestLink } from "./threadPullRequests.ts";export interface ThreadReferenceCopyTarget {readonly kind: "pull-request" | "thread";- /** The plain text: a PR URL, or a thread chip's reference link. */+ /** The plain text: a PR URL, or a link that opens the thread from anywhere. */readonly value: string;/** What a toast or palette row shows for the copy. */readonly description: string;@@ -23,15 +21,19 @@ export interface ThreadReferenceCopyTarget {readonly failureTitle: string;}-/** A thread chip pastes into any composer whose agent reads that thread's machine. */+/**+ * A link that opens the thread from anywhere, through `hostedAppUrl`, this build's hosted app. It+ * pastes back as a chip into any composer whose agent reads that thread's machine.+ */export function threadChipCopyTarget(threadRef: ScopedThreadRef,title: string,+ hostedAppUrl?: string,): ThreadReferenceCopyTarget {const record = threadContextRecord(threadRef, title);return {kind: "thread",- value: formatComposerContextReference(record),+ value: hostedThreadLink(threadRef, hostedAppUrl),description: record.title,fragment: { version: 1, source: { environmentId: threadRef.environmentId }, records: [record] },clipboardTarget: "thread",@@ -47,6 +49,7 @@ export function resolveThreadReferenceCopyTarget(input: {readonly openPanelPullRequestUrl?: string | null | undefined;readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;readonly linkedPullRequestUrl?: string | null;+ readonly hostedAppUrl?: string;}): ThreadReferenceCopyTarget | null {if (input.openPanelPullRequestUrl === null) return null;const pullRequestUrl =@@ -62,5 +65,5 @@ export function resolveThreadReferenceCopyTarget(input: {successTitle: "PR link copied",failureTitle: "Failed to copy PR link",}- : threadChipCopyTarget(input.threadRef, input.title);+ : threadChipCopyTarget(input.threadRef, input.title, input.hostedAppUrl);}diff --git a/packages/shared/src/composerContextReferences.test.ts b/packages/shared/src/composerContextReferences.test.tsindex a12eed6a839..6f27538f372 100644--- a/packages/shared/src/composerContextReferences.test.ts+++ b/packages/shared/src/composerContextReferences.test.ts@@ -17,6 +17,7 @@ import {stripAttachmentOnlyBootstrapPrompt,threadContextRecord,threadContextsOutsideEnvironment,+ threadLinkContextReferences,toComposerContextId,toKindScopedComposerContextId,} from "./composerContextReferences.ts";@@ -478,3 +479,65 @@ describe("threadContextRecord", () => {).toBe("thread_abc-123");});});++describe("threadLinkContextReferences", () => {+ const thread = (environmentId: string, threadId: string) => ({+ environmentId: EnvironmentId.make(environmentId),+ threadId: ThreadId.make(threadId),+ });+ const reference = (environmentId: string, threadId: string, label: string) =>+ `[${label}](t3-context://v1/thread/${threadContextRecord(thread(environmentId, threadId), label).contextId})`;++ it("makes a chip of a copied link, a v2 link, and a labeled link, titled here", () => {+ const pasted = threadLinkContextReferences(+ [+ "https://app.t3.codes/threads/env-1/t1",+ "<t3-thread://v2/env-1/t2>",+ "[Written](https://app.t3.codes/threads/env-2/t3)",+ ].join(" "),+ [],+ ({ threadId }) => (threadId === "t3" ? undefined : `Title ${threadId}`),+ );+ expect(pasted.text).toBe(+ [+ reference("env-1", "t1", "Title t1"),+ reference("env-1", "t2", "Title t2"),+ reference("env-2", "t3", "Written"),+ ].join(" "),+ );+ expect(pasted.records).toEqual([+ threadContextRecord(thread("env-1", "t1"), "Title t1"),+ threadContextRecord(thread("env-1", "t2"), "Title t2"),+ threadContextRecord(thread("env-2", "t3"), "Written"),+ ]);+ });++ it("prefers the record the copy carried, and names an unknown thread plainly", () => {+ const copied = threadContextRecord(thread("env-1", "t1"), "Copied title");+ const pasted = threadLinkContextReferences(+ "https://app.t3.codes/threads/env-1/t1 https://app.t3.codes/threads/env-9/t9",+ [copied],+ () => "Here",+ );+ expect(pasted.records).toEqual([copied, threadContextRecord(thread("env-9", "t9"), "Here")]);+ expect(+ threadLinkContextReferences("https://app.t3.codes/threads/env-9/t9", [], () => undefined)+ .records,+ ).toEqual([threadContextRecord(thread("env-9", "t9"), "Thread")]);+ });++ it("keeps links it may not chip, v1 links, and links in code as written", () => {+ const text = [+ "https://app.t3.codes/threads/elsewhere/t1",+ "[Old](t3-thread://v1/t2)",+ "`https://app.t3.codes/threads/env-1/t3`",+ ].join(" ");+ const pasted = threadLinkContextReferences(+ text,+ [],+ () => "Title",+ () => undefined,+ );+ expect(pasted).toEqual({ text, records: [] });+ });+});diff --git a/packages/shared/src/composerContextReferences.ts b/packages/shared/src/composerContextReferences.tsindex 33e89737961..a7aeb1373ae 100644--- a/packages/shared/src/composerContextReferences.ts+++ b/packages/shared/src/composerContextReferences.ts@@ -10,6 +10,8 @@ import {type ThreadContextRecord,} from "@t3tools/contracts";+import { replaceThreadLinks, threadLinkCandidates } from "./threadLinks.ts";+const CONTEXT_PROTOCOL = "t3-context:";const COMPOSER_CONTEXT_HREF_PREFIX = `${CONTEXT_PROTOCOL}//v1/`;const CONTEXT_KIND_PATTERN = /^[a-z][a-z0-9-]{0,39}$/;@@ -93,6 +95,45 @@ export function threadContextRecord(ref: ScopedThreadRef, title: string): Thread};}+/**+ * Turns pasted thread links into thread chip references. A record the copy carried names its+ * chip, else the thread's title here, read by key, or the link's own label. `accept` gives the+ * chip's id, or none to keep the link as written. A v1 link names no machine, so it stays a link.+ */+export function threadLinkContextReferences(+ text: string,+ copied: ReadonlyArray<ComposerContextRecord>,+ title: (ref: ScopedThreadRef) => string | undefined,+ accept: (record: ThreadContextRecord) => ComposerContextId | undefined = (record) =>+ record.contextId,+): { readonly text: string; readonly records: ReadonlyArray<ThreadContextRecord> } {+ const records = new Map<ComposerContextId, ThreadContextRecord>();+ const rewritten = replaceThreadLinks(text, (link, label) => {+ if (link.environmentId === null) return undefined;+ const candidates = threadLinkCandidates(link, link.environmentId);+ const record =+ copied.find(+ (candidate): candidate is ThreadContextRecord =>+ candidate.kind === "thread" &&+ "threadId" in candidate &&+ candidates.some(+ (ref) =>+ ref.environmentId === candidate.environmentId && ref.threadId === candidate.threadId,+ ),+ ) ??+ candidates.flatMap((ref) => {+ const known = title(ref);+ return known === undefined ? [] : [threadContextRecord(ref, known)];+ })[0] ??+ threadContextRecord(candidates[0]!, label?.trim() || "Thread");+ const contextId = accept(record);+ if (contextId === undefined) return undefined;+ records.set(record.contextId, record);+ return formatComposerContextReference({ ...record, contextId });+ });+ return { text: rewritten, records: [...records.values()] };+}+export function formatComposerContextReference(reference: {kind: ComposerContextKind;contextId: ComposerContextId;diff --git a/packages/shared/src/promptLinks.test.ts b/packages/shared/src/promptLinks.test.tsindex afc5644f9ac..65d18eba078 100644--- a/packages/shared/src/promptLinks.test.ts+++ b/packages/shared/src/promptLinks.test.ts@@ -1,3 +1,4 @@+import { EnvironmentId, ThreadId } from "@t3tools/contracts";import { describe, expect, it } from "vite-plus/test";import {@@ -5,9 +6,11 @@ import {parseNewThreadLink,parseThreadLinkPrompt,promptLinkAppPath,+ promptLinkDeepLink,sanitizeLinkedPrompt,withoutPromptLinkParams,} from "./promptLinks.ts";+import { hostedThreadLink } from "./threadLinks.ts";describe("sanitizeLinkedPrompt", () => {it("removes characters a reader cannot see and counts them", () => {@@ -105,12 +108,33 @@ describe("link round trips", () => {);});+ it("opens a copied thread link in the app at that thread", () => {+ const link = hostedThreadLink({+ environmentId: EnvironmentId.make("env-1"),+ threadId: ThreadId.make("mcp:1"),+ });+ const path = promptLinkAppPath(link);+ expect(path).toBe("/env-1/mcp%3A1");+ const deepLink = promptLinkDeepLink(path!);+ expect(deepLink).toBe("t3code://threads/env-1/mcp%3A1");+ expect(promptLinkAppPath(deepLink)).toBe(path);+ });+it("maps app scheme and hosted links to in-app paths, and nothing else", () => {expect(promptLinkAppPath("t3code://new?prompt=hi")).toBe("/new?prompt=hi");expect(promptLinkAppPath("t3code-dev://threads/env-1/thread-1")).toBe("/env-1/thread-1");expect(promptLinkAppPath("https://app.t3.codes/env-1/thread-1?prompt=go")).toBe("/env-1/thread-1?prompt=go",);+ expect(promptLinkAppPath("https://app.t3.codes/threads/env-1/thread-1")).toBe(+ "/env-1/thread-1",+ );+ expect(promptLinkAppPath("https://app.t3.codes/threads/env-1/thread-1?prompt=go")).toBe(+ "/env-1/thread-1?prompt=go",+ );+ // The web app's own thread route, reloaded, is no link.+ expect(promptLinkAppPath("https://app.t3.codes/env-1/thread-1")).toBeNull();+ expect(promptLinkAppPath("https://app.t3.codes/threads/env-1")).toBeNull();expect(promptLinkAppPath("https://app.t3.codes/settings/general")).toBeNull();expect(promptLinkAppPath("https://evil.test/new?prompt=hi")).toBeNull();expect(promptLinkAppPath("t3code://app/index.html")).toBeNull();diff --git a/packages/shared/src/promptLinks.ts b/packages/shared/src/promptLinks.tsindex adff0135bfc..223c0c4b9cf 100644--- a/packages/shared/src/promptLinks.ts+++ b/packages/shared/src/promptLinks.ts@@ -199,7 +199,12 @@ export function promptLinkAppPath(}if (!URL.canParse(hostedAppUrl) || url.origin !== new URL(hostedAppUrl).origin) return null;if (url.pathname === "/new") return `/new${url.search}`;- const thread = url.searchParams.has("prompt") ? THREAD_PATH.exec(url.pathname) : null;+ // The web app's own thread route is a link only with a prompt, so reloading a tab never asks.+ const thread = url.pathname.startsWith("/threads/")+ ? THREAD_PATH.exec(url.pathname.slice("/threads".length))+ : url.searchParams.has("prompt")+ ? THREAD_PATH.exec(url.pathname)+ : null;return thread ? `/${thread[1]}/${thread[2]}${url.search}` : null;}diff --git a/packages/shared/src/threadLinks.test.ts b/packages/shared/src/threadLinks.test.tsindex aa1c02fd4be..0c19f18163e 100644--- a/packages/shared/src/threadLinks.test.ts+++ b/packages/shared/src/threadLinks.test.ts@@ -2,8 +2,10 @@ import { describe, expect, it, vi } from "vite-plus/test";import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";import {+ formatHostedThreadLink,formatThreadLink,guessThreadLinkRef,+ hostedThreadLink,parseThreadLinkHref,relabelThreadLinks,threadLinkCandidates,@@ -174,3 +176,64 @@ describe("thread links", () => {expect(formatThreadLink(ref("e", "t1"), " ] ")).toBe("<t3-thread://v2/e/t1>");});});++describe("hosted thread links", () => {+ it("escapes every id character a sentence or path could claim, and reads it back", () => {+ const thread = ref("env.1", "thread:delegated/mcp%3A1.");+ const link = hostedThreadLink(thread);+ expect(link).toBe("https://app.t3.codes/threads/env%2E1/thread%3Adelegated%2Fmcp%253A1%2E");+ expect(parseThreadLinkHref(link)).toEqual(thread);+ expect(hostedThreadLink(thread, "https://preview.t3.codes/")).toMatch(+ /^https:\/\/preview\.t3\.codes\/threads\//,+ );+ });++ it("reads only a bare thread path on the hosted app", () => {+ expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1/thread-1")).toEqual(+ ref("env-1", "thread-1"),+ );+ expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1/thread-1?prompt=go")).toBeNull();+ expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1/thread-1/extra")).toBeNull();+ expect(parseThreadLinkHref("https://app.t3.codes/threads/env-1")).toBeNull();+ expect(parseThreadLinkHref("https://app.t3.codes/env-1/thread-1")).toBeNull();+ expect(parseThreadLinkHref("https://evil.test/threads/env-1/thread-1")).toBeNull();+ });++ it("writes a copied link a reader can follow, labeled when it has a title", () => {+ expect(formatHostedThreadLink(ref("e", "t1"), "Fix [ci]")).toBe(+ "[Fix ci](https://app.t3.codes/threads/e/t1)",+ );+ expect(formatHostedThreadLink(ref("e", "t1"), " ")).toBe("https://app.t3.codes/threads/e/t1");+ });++ it("titles hosted links in every Markdown form and writes them as v2 links", () => {+ const title = titlesIn({ there: { t1: "There" } });+ expect(+ relabelThreadLinks(+ [+ "See https://app.t3.codes/threads/there/t1.",+ "[old](https://app.t3.codes/threads/there/t1)",+ "<https://app.t3.codes/threads/there/t1>",+ "`https://app.t3.codes/threads/there/t1`",+ "https://app.t3.codes/threads/there/t1?prompt=go",+ ].join("\n"),+ local,+ title,+ ),+ ).toBe(+ [+ "See [There](t3-thread://v2/there/t1).",+ "[There](t3-thread://v2/there/t1)",+ "[There](t3-thread://v2/there/t1)",+ "`https://app.t3.codes/threads/there/t1`",+ "https://app.t3.codes/threads/there/t1?prompt=go",+ ].join("\n"),+ );+ expect(+ relabelThreadLinks("https://app.t3.codes/threads/there/t1", local, () => undefined),+ ).toBe("Thread on another machine");+ expect(threadLinkRefs("Open https://app.t3.codes/threads/there/t%3A1", local)).toEqual([+ ref("there", "t:1"),+ ]);+ });+});diff --git a/packages/shared/src/threadLinks.ts b/packages/shared/src/threadLinks.tsindex aceb87635c2..aba7d5f983a 100644--- a/packages/shared/src/threadLinks.ts+++ b/packages/shared/src/threadLinks.ts@@ -2,12 +2,19 @@ import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contractimport * as Option from "effect/Option";import * as Schema from "effect/Schema";+import { DEFAULT_HOSTED_APP_URL } from "./connectAuth.ts";+export const THREAD_LINK_PROTOCOL = "t3-thread";const V1_PREFIX = `${THREAD_LINK_PROTOCOL}://v1/`;const V2_PREFIX = `${THREAD_LINK_PROTOCOL}://v2/`;+const HOSTED_PREFIX = `${DEFAULT_HOSTED_APP_URL}/threads/`;+const HOSTED_SEGMENT = "[A-Za-z0-9_%-]+";+const HOSTED_LINK = `${HOSTED_PREFIX.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}${HOSTED_SEGMENT}/${HOSTED_SEGMENT}`;// Code comes first in the alternation so a link written inside a code span or fence is skipped.-const THREAD_LINK_OUTSIDE_CODE =- /(?<fence>(`{3,}|~{3,})[\s\S]*?(?:\2|$))|(?<span>(`+)[^\n]*?\4)|\[(?<label>[^\]\n]*)\]\((?<href>t3-thread:\/\/v[12]\/[^\s)]+)\)|<(?<autolink>t3-thread:\/\/v[12]\/[^\s<>]+)>/g;+const THREAD_LINK_OUTSIDE_CODE = new RegExp(+ 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%/?#-])`,+ "g",+);const decodeThreadId = Schema.decodeUnknownOption(ThreadId);const decodeEnvironmentId = Schema.decodeUnknownOption(EnvironmentId);@@ -18,8 +25,39 @@ export interface ThreadLink {readonly threadId: ThreadId;}-/** The ids as written. Thread ids can hold percent escapes of their own, so they are not decoded. */+// Escapes even URL-safe punctuation, so a sentence's closing period never reads as part of an id.+const hostedSegment = (id: string) =>+ encodeURIComponent(id).replace(+ /[.!~*'()]/g,+ (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,+ );++/** Opens the thread from anywhere: the hosted app offers the desktop app, the mobile app, or itself. */+export function hostedThreadLink(ref: ScopedThreadRef, origin = DEFAULT_HOSTED_APP_URL): string {+ const path = `/threads/${hostedSegment(ref.environmentId)}/${hostedSegment(ref.threadId)}`;+ return new URL(path, origin).toString();+}++const HOSTED_PATH = new RegExp(`^(${HOSTED_SEGMENT})/(${HOSTED_SEGMENT})$`);++function parseHostedThreadLink(href: string): ThreadLink | null {+ const match = HOSTED_PATH.exec(href.slice(HOSTED_PREFIX.length));+ if (!match) return null;+ try {+ const environmentId = Option.getOrNull(decodeEnvironmentId(decodeURIComponent(match[1]!)));+ const threadId = Option.getOrNull(decodeThreadId(decodeURIComponent(match[2]!)));+ return environmentId === null || threadId === null ? null : { environmentId, threadId };+ } catch {+ return null;+ }+}++/**+ * The ids as written. Thread ids can hold percent escapes of their own, so they are not decoded,+ * except in a hosted link, which escapes them itself.+ */export function parseThreadLinkHref(href: string): ThreadLink | null {+ if (href.startsWith(HOSTED_PREFIX)) return parseHostedThreadLink(href);if (href.startsWith(V1_PREFIX)) {const threadId = Option.getOrNull(decodeThreadId(href.slice(V1_PREFIX.length)));return threadId === null ? null : { environmentId: null, threadId };@@ -78,17 +116,31 @@ function threadLinkHref(link: ThreadLink): string {: `${V2_PREFIX}${link.environmentId}/${link.threadId}`;}-/** Without a label, an autolink: clients show the thread's current title. */-export function formatThreadLink(ref: ThreadLink, label?: string): string {- const cleaned = label+const linkLabel = (label: string | undefined) =>+ label?.replace(/[[\]\\\r\n]/g, " ").replace(/\s+/g, " ").trim();++/** Without a label, an autolink: clients show the thread's current title. */+export function formatThreadLink(ref: ThreadLink, label?: string): string {+ const cleaned = linkLabel(label);return cleaned ? `[${cleaned}](${threadLinkHref(ref)})` : `<${threadLinkHref(ref)}>`;}+/** What a person copies out of T3 Code: a Markdown link that opens the thread anywhere. */+export function formatHostedThreadLink(+ ref: ScopedThreadRef,+ label: string,+ origin?: string,+): string {+ const href = hostedThreadLink(ref, origin);+ const cleaned = linkLabel(label);+ return cleaned ? `[${cleaned}](${href})` : href;+}+export function hasThreadLinks(markdown: string): boolean {- return markdown.includes(`${THREAD_LINK_PROTOCOL}://v`);+ return markdown.includes(`${THREAD_LINK_PROTOCOL}://v`) || markdown.includes(HOSTED_PREFIX);}/** Every thread the markdown's links can name, so their titles are keyed reads. */@@ -100,7 +152,7 @@ export function threadLinkRefs(// Hermes' matchAll yields matches without `groups`; exec keeps them.const pattern = new RegExp(THREAD_LINK_OUTSIDE_CODE);for (let match = pattern.exec(markdown); match !== null; match = pattern.exec(markdown)) {- const href = match.groups?.href ?? match.groups?.autolink;+ const href = match.groups?.href ?? match.groups?.autolink ?? match.groups?.bare;const link = href === undefined ? null : parseThreadLinkHref(href);if (link === null) continue;for (const ref of threadLinkCandidates(link, messageEnvironmentId)) {@@ -119,22 +171,31 @@ export function unknownThreadLinkLabel(: "Thread on another machine";}+/** Rewrites each link outside code `replace` answers for. `label` is a Markdown link's own text. */+export function replaceThreadLinks(+ markdown: string,+ replace: (link: ThreadLink, label: string | undefined) => string | undefined,+): string {+ if (!hasThreadLinks(markdown)) return markdown;+ return markdown.replace(THREAD_LINK_OUTSIDE_CODE, (source, ...args) => {+ const groups = args.at(-1) as Partial<Record<"href" | "autolink" | "bare" | "label", string>>;+ const href = groups.href ?? groups.autolink ?? groups.bare;+ const link = href === undefined ? null : parseThreadLinkHref(href);+ return (link && replace(link, groups.label)) ?? source;+ });+}+/**- * Writes each link with its thread's current title. A link `title` cannot resolve becomes plain- * text, its written label or a neutral one, except a labeled v1 link, which may open elsewhere.+ * Writes each link with its thread's current title, a hosted link as a v2 link. A link `title`+ * cannot resolve becomes plain text, its written label or a neutral one, except a labeled v1+ * link, which may open elsewhere.*/export function relabelThreadLinks(markdown: string,messageEnvironmentId: EnvironmentId,title: (ref: ScopedThreadRef) => string | undefined,): string {- if (!hasThreadLinks(markdown)) return markdown;- return markdown.replace(THREAD_LINK_OUTSIDE_CODE, (source, ...args) => {- const groups = args.at(-1) as { href?: string; autolink?: string; label?: string };- const href = groups.href ?? groups.autolink;- if (href === undefined) return source;- const written = parseThreadLinkHref(href);- if (written === null) return source;+ return replaceThreadLinks(markdown, (written, label) => {const environmentId = written.environmentId ?? messageEnvironmentId;const decoded = percentDecodedThreadLinkId(written.threadId);const threadId =@@ -145,12 +206,12 @@ export function relabelThreadLinks(: written.threadId;const current = title({ environmentId, threadId });if (current === undefined) {- if (groups.href !== undefined && written.environmentId === null) return source;- return groups.label?.trim() || unknownThreadLinkLabel(written, messageEnvironmentId);+ if (label !== undefined && written.environmentId === null) return undefined;+ return label?.trim() || unknownThreadLinkLabel(written, messageEnvironmentId);}return formatThreadLink({ environmentId: written.environmentId, threadId },- current.trim() || groups.label || threadId,+ current.trim() || label || threadId,);});}