Skip to content
TypeScript

feat(web,mobile): Copy thread copies a chip that works on linked machines (#26202)

Julius Marminge0affd28db295
diff --git a/apps/mobile/modules/t3-native-controls/ios/T3KeyboardCommandsModule.swift b/apps/mobile/modules/t3-native-controls/ios/T3KeyboardCommandsModule.swift
index 2d92537bf43..549331a56be 100644
--- a/apps/mobile/modules/t3-native-controls/ios/T3KeyboardCommandsModule.swift
+++ b/apps/mobile/modules/t3-native-controls/ios/T3KeyboardCommandsModule.swift
@@ -53,7 +53,7 @@ public final class T3KeyboardCommandsView: ExpoView {
input: "c",
modifiers: [.command, .shift],
action: #selector(copyThreadReference),
- title: "Copy PR Link or Thread ID"
+ title: "Copy PR Link or Thread"
),
enabledCommand("toggleSidebar", input: "\\", modifiers: .command, action: #selector(handleToggleSidebar), title: "Toggle Sidebar"),
enabledCommand("cycleHost", input: "h", modifiers: [.command, .shift], action: #selector(cycleHost), title: "Next Machine"),
diff --git a/apps/mobile/src/features/keyboard/CommandPalette.tsx b/apps/mobile/src/features/keyboard/CommandPalette.tsx
index 3194d880532..2c26104a636 100644
--- a/apps/mobile/src/features/keyboard/CommandPalette.tsx
+++ b/apps/mobile/src/features/keyboard/CommandPalette.tsx
@@ -393,7 +393,7 @@ export function CommandPalette(props: {
["files", "Go to file", ["open", "files", "browse", "search"]],
["terminal", "Open terminal", ["shell", "console"]],
["review", "Review changes", ["diff", "git", "pull request"]],
- ["copyThreadReference", "Copy PR link or thread ID", ["reference", "clipboard"]],
+ ["copyThreadReference", "Copy PR link or thread", ["reference", "clipboard"]],
] as const;
actions.push(
...threadActions.map(([command, title, searchTerms]) => ({
diff --git a/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx b/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx
index 8cd9e215e0f..135715f0649 100644
--- a/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx
+++ b/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx
@@ -14,7 +14,7 @@ import {
type ReactNode,
} from "react";
-import { tryCopyTextWithHaptic } from "../../lib/copyTextWithHaptic";
+import { copyThreadReference } from "../../lib/copyThreadReference";
import {
firstWorkspaceDetailOpen,
workspaceHasColumns,
@@ -62,7 +62,8 @@ export function HardwareKeyboardCommandProvider({
activeThreadRef === null
? null
: resolveThreadReferenceCopyTarget({
- threadId: activeThread?.id ?? activeThreadRef.threadId,
+ threadRef: activeThreadRef,
+ title: activeThread?.title ?? "",
pullRequests: activeThread?.pullRequests,
linkedPullRequestUrl:
(activeThread?.linkedPullRequest ?? activeThread?.branchPullRequest)?.url ?? null,
@@ -134,16 +135,14 @@ export function HardwareKeyboardCommandProvider({
if (command === "copyThreadReference") {
if (copyTarget === null) return;
const requestId = ++copyRequestIdRef.current;
- void tryCopyTextWithHaptic(copyTarget.value, {
- target: copyTarget.clipboardTarget,
- }).then((didCopy) => {
+ void copyThreadReference(copyTarget).then((didCopy) => {
if (requestId !== copyRequestIdRef.current) return;
showCopyFeedback(
didCopy
? {
phase: "success",
label: copyTarget.successTitle,
- description: copyTarget.value,
+ description: copyTarget.description,
}
: {
phase: "error",
diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx
index 8935877d28b..d120665f298 100644
--- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx
+++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx
@@ -27,6 +27,7 @@ import {
} from "@t3tools/client-runtime/state/models";
import { AuthOrchestrationOperateScope, type EnvironmentMachineKind } from "@t3tools/contracts";
import { canSnooze } from "@t3tools/client-runtime/state/thread-settled";
+import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference";
import type { MenuAction } from "@react-native-menu/menu";
import { memo, useCallback, useMemo, useState, type ComponentProps } from "react";
import { Pressable, useWindowDimensions, View } from "react-native";
@@ -42,6 +43,7 @@ import { ProviderIcon, ProviderInstanceIcon } from "../../components/ProviderIco
import { useNowAfter } from "../../lib/clock";
import { cn } from "../../lib/cn";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
+import { copyThreadReference } from "../../lib/copyThreadReference";
import { useUniwindTheme } from "../../lib/useUniwindTheme";
import { useEnvironmentScope } from "../../state/session";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
@@ -918,6 +920,15 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "rename") handleRename();
if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
+ if (nativeEvent.event === "copy-thread") {
+ const target = threadChipCopyTarget(
+ { environmentId: thread.environmentId, threadId: thread.id },
+ thread.title,
+ );
+ void copyThreadReference(target).then((didCopy) => {
+ if (!didCopy) Dialog.alert(target.failureTitle, "Try copying this thread again.");
+ });
+ }
if (nativeEvent.event === "copy-thread-id") {
copyTextWithHaptic(thread.id, { target: "thread-id" });
}
@@ -1406,6 +1417,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
},
]
: []),
+ { id: "copy-thread", title: "Copy thread", image: "text.bubble" },
{ id: "copy-thread-id", title: "Copy thread ID", image: "doc.on.doc" },
...(snoozedRow
? snoozedMenuActions
diff --git a/apps/mobile/src/features/threads/use-composer-command-menu.ts b/apps/mobile/src/features/threads/use-composer-command-menu.ts
index 28ee640fa6e..72987599f48 100644
--- a/apps/mobile/src/features/threads/use-composer-command-menu.ts
+++ b/apps/mobile/src/features/threads/use-composer-command-menu.ts
@@ -18,12 +18,11 @@ const EMPTY_THREAD_SHELLS: ReadonlyArray<EnvironmentThreadShell> = [];
const EMPTY_ENVIRONMENTS: ReadonlyArray<ComposerEnvironmentCandidate> = [];
const NO_LINKED_ENVIRONMENTS: ReadonlyMap<EnvironmentId, string> = new Map();
import { COMPOSER_CONTEXT_MAX_RECORDS } from "@t3tools/contracts";
-import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences";
import {
- environmentComposerContext,
- pullRequestComposerContext,
- threadComposerContext,
-} from "../../lib/composerContext";
+ formatComposerContextReference,
+ threadContextRecord,
+} from "@t3tools/shared/composerContextReferences";
+import { environmentComposerContext, pullRequestComposerContext } from "../../lib/composerContext";
import { uuidv4 } from "../../lib/uuid";
import {
getComposerDraftSnapshot,
@@ -528,7 +527,7 @@ export function useComposerCommandMenu({
candidate.id === item.thread.threadId,
);
if (!shell) return;
- const record = threadComposerContext(item.thread, shell.title);
+ const record = threadContextRecord(item.thread, shell.title);
const existing = getComposerDraftSnapshot(ownerKey).context?.records ?? [];
const alreadyAttached = existing.some((entry) => entry.contextId === record.contextId);
if (!alreadyAttached && existing.length >= COMPOSER_CONTEXT_MAX_RECORDS) {
diff --git a/apps/mobile/src/lib/composerContext.test.ts b/apps/mobile/src/lib/composerContext.test.ts
index 7c8da73d0f8..66a96905bca 100644
--- a/apps/mobile/src/lib/composerContext.test.ts
+++ b/apps/mobile/src/lib/composerContext.test.ts
@@ -4,8 +4,6 @@ import {
ProjectId,
ProviderInstanceId,
ComposerContextId,
- EnvironmentId,
- ThreadId,
type OrchestrationMessageContext,
type ServerProviderSkill,
} from "@t3tools/contracts";
@@ -28,7 +26,6 @@ import {
uploadedComposerContext,
serializeComposerMessageForServer,
pullRequestComposerContext,
- threadComposerContext,
} from "./composerContext";
const terminal = {
@@ -397,20 +394,3 @@ describe("host context compatibility", () => {
expect(context.records).toEqual([terminal, review, pr]);
});
});
-
-describe("threadComposerContext", () => {
- it("mints a schema-valid, stable id for agent-spawned thread ids", () => {
- const environmentId = EnvironmentId.make("env-1");
- const ref = {
- environmentId,
- threadId: ThreadId.make(`thread:mcp:${encodeURIComponent("3f2b:delegate")}:review:0`),
- };
- const contextId = threadComposerContext(ref, "Review").contextId;
-
- expect(() => ComposerContextId.make(contextId)).not.toThrow();
- expect(threadComposerContext(ref, "Renamed").contextId).toBe(contextId);
- expect(
- threadComposerContext({ environmentId, threadId: ThreadId.make("abc-123") }, "t").contextId,
- ).toBe("thread_abc-123");
- });
-});
diff --git a/apps/mobile/src/lib/composerContext.ts b/apps/mobile/src/lib/composerContext.ts
index 34b4e3fcdcd..822c7f7b421 100644
--- a/apps/mobile/src/lib/composerContext.ts
+++ b/apps/mobile/src/lib/composerContext.ts
@@ -11,9 +11,7 @@ import {
OrchestrationMessageContext,
type PullRequestContextMetadata,
type ReviewCommentContextRecord,
- type ScopedThreadRef,
type ServerProviderSkill,
- type ThreadContextRecord,
type EnvironmentContextRecord,
type EnvironmentId,
} from "@t3tools/contracts";
@@ -25,7 +23,6 @@ import {
isImageReferencesOnly,
replaceComposerContextReferences,
sanitizeComposerContextLabel,
- toKindScopedComposerContextId,
} from "@t3tools/shared/composerContextReferences";
import {
collectComposerInlineTokens,
@@ -103,20 +100,6 @@ export function createComposerContextHistory() {
};
}
-/** Same identity as web: one record per thread, so re-attaching reuses the chip. */
-export function threadComposerContext(ref: ScopedThreadRef, title: string): ThreadContextRecord {
- const label = sanitizeComposerContextLabel(title, "thread");
- return {
- version: 1,
- kind: "thread",
- contextId: toKindScopedComposerContextId("thread", ref.threadId),
- label,
- environmentId: ref.environmentId,
- threadId: ref.threadId,
- title: label,
- };
-}
-
/** Same identity as web: one record per machine, so mentioning it again reuses the chip. */
export function environmentComposerContext(
environmentId: EnvironmentId,
diff --git a/apps/mobile/src/lib/copyThreadReference.ts b/apps/mobile/src/lib/copyThreadReference.ts
new file mode 100644
index 00000000000..f3921fb2605
--- /dev/null
+++ b/apps/mobile/src/lib/copyThreadReference.ts
@@ -0,0 +1,19 @@
+import type { ThreadReferenceCopyTarget } from "@t3tools/client-runtime/thread-reference";
+import * as Haptics from "expo-haptics";
+
+import { writeComposerContextClipboard } from "./composerContextClipboard";
+import { tryCopyTextWithHaptic } from "./copyTextWithHaptic";
+
+/** Resolves false, after logging why, when the clipboard write fails. */
+export async function copyThreadReference(target: ThreadReferenceCopyTarget): Promise<boolean> {
+ if (!target.fragment)
+ return tryCopyTextWithHaptic(target.value, { target: target.clipboardTarget });
+ try {
+ await writeComposerContextClipboard(target.value, target.fragment);
+ } catch (error) {
+ console.error(`Failed to copy ${target.clipboardTarget} to the clipboard.`, error);
+ return false;
+ }
+ void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light).catch(() => {});
+ return true;
+}
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 69409e5e4da..c9ce40121de 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -140,7 +140,7 @@ import { useWorkspaceMutationRefresh } from "../hooks/useWorkspaceMutationRefres
import { DEFAULT_INTERACTION_MODE, type ChatMessage } from "../types";
import { buildThreadRouteParams } from "../threadRoutes";
import { useTheme } from "../hooks/useTheme";
-import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
+import { copyThreadReference } from "../lib/copyThreadReference";
import { subscribeSnapShotComposerFocus } from "../lib/desktopSnapShot";
import { useMediaQuery } from "../hooks/useMediaQuery";
import { FileMetadataThreadProvider } from "../hooks/FileMetadataThreadProvider";
@@ -179,7 +179,7 @@ import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
import { shortcutLabelForCommand } from "../keybindings";
import { cn } from "~/lib/utils";
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
-import { stackedThreadToast, toastManager } from "./ui/toast";
+import { toastManager } from "./ui/toast";
import { projectScriptIdFromCommand } from "~/projectScripts";
import { newMessageId } from "~/lib/utils";
import {
@@ -2288,37 +2288,18 @@ export default function ChatView(props: ChatViewProps) {
]);
const openPanelPullRequestUrl = useOpenPanelPullRequestUrl(activeThreadRef);
const activeThreadReferenceCopyTarget =
- activeThreadId === null || !isServerThread
+ activeThreadRef === null || !isServerThread
? null
: resolveThreadReferenceCopyTarget({
- threadId: activeThreadId,
+ threadRef: activeThreadRef,
+ title: activeThread?.title ?? "",
openPanelPullRequestUrl,
pullRequests: activeThread?.pullRequests,
linkedPullRequestUrl: linkedThreadPullRequest?.url ?? null,
});
const copyActiveThreadReference = () => {
- const target = activeThreadReferenceCopyTarget;
- if (target === null) return;
- void writeTextToClipboard(target.value, target.clipboardTarget).then(
- (didCopy) => {
- if (!didCopy) return;
- toastManager.add({
- type: "success",
- title: target.successTitle,
- description: target.value,
- });
- },
- (error) => {
- console.error(error);
- toastManager.add(
- stackedThreadToast({
- type: "error",
- title: target.failureTitle,
- description: error instanceof Error ? error.message : "An error occurred.",
- }),
- );
- },
- );
+ if (activeThreadReferenceCopyTarget === null) return;
+ void copyThreadReference(activeThreadReferenceCopyTarget);
};
const pullRequestPanelTarget = activeThread
? threadPullRequestPanelTarget({
diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx
index c55f8924233..378a3e3d058 100644
--- a/apps/web/src/components/CommandPalette.tsx
+++ b/apps/web/src/components/CommandPalette.tsx
@@ -88,7 +88,7 @@ import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal";
import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraps";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { useOpenPanelPullRequestUrl } from "../hooks/useOpenPanelPullRequestUrl";
-import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
+import { copyThreadReference } from "../lib/copyThreadReference";
import {
composerPromptLink,
copyPromptLink,
@@ -446,33 +446,16 @@ function OpenCommandPaletteDialog(props: {
referenceThreadRef === null || (pathname === "/pull-requests" && !openPanelPullRequestUrl)
? null
: resolveThreadReferenceCopyTarget({
- threadId: referenceThreadRef.threadId,
+ threadRef: referenceThreadRef,
+ title: activeThread?.title ?? "",
openPanelPullRequestUrl,
pullRequests: activeThread?.pullRequests,
linkedPullRequestUrl:
activeThread?.linkedPullRequest?.url ?? activeThread?.branchPullRequest?.url ?? null,
});
const copyActiveThreadReference = async () => {
- const target = activeThreadReferenceCopyTarget;
- if (target === null) return;
- try {
- const didCopy = await writeTextToClipboard(target.value, target.clipboardTarget);
- if (!didCopy) return;
- toastManager.add({
- type: "success",
- title: target.successTitle,
- description: target.value,
- });
- } catch (error) {
- console.error(error);
- toastManager.add(
- stackedThreadToast({
- type: "error",
- title: target.failureTitle,
- description: error instanceof Error ? error.message : "An error occurred.",
- }),
- );
- }
+ if (activeThreadReferenceCopyTarget === null) return;
+ await copyThreadReference(activeThreadReferenceCopyTarget);
};
const threads = useThreadShells();
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
@@ -1299,10 +1282,10 @@ function OpenCommandPaletteDialog(props: {
searchTerms:
activeThreadReferenceCopyTarget.kind === "pull-request"
? ["copy", "pull request", "link", "reference"]
- : ["copy", "thread id", "reference"],
+ : ["copy", "thread", "thread id", "reference"],
title:
- activeThreadReferenceCopyTarget.kind === "pull-request" ? "Copy PR link" : "Copy thread ID",
- description: activeThreadReferenceCopyTarget.value,
+ activeThreadReferenceCopyTarget.kind === "pull-request" ? "Copy PR link" : "Copy thread",
+ description: activeThreadReferenceCopyTarget.description,
icon: <LinkIcon className={ITEM_ICON_CLASS} />,
shortcutCommand: "thread.copyReference",
run: copyActiveThreadReference,
diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsx
index 6d54fe2b7b9..ea41576fc62 100644
--- a/apps/web/src/components/LegacySidebar.tsx
+++ b/apps/web/src/components/LegacySidebar.tsx
@@ -141,6 +141,8 @@ import { readUnloadedThreadCount } from "../state/olderSettledShelf";
import { useEnvironment, useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
import { buildThreadRouteParams, resolveActiveThreadRouteRef } from "../threadRoutes";
import { stackedThreadToast, toastManager } from "./ui/toast";
+import { copyThreadReference } from "../lib/copyThreadReference";
+import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference";
import { RelativeTime } from "./RelativeTime";
import { Kbd } from "./ui/kbd";
import {
@@ -2182,6 +2184,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
: []),
{ id: "mark-unread", label: "Mark unread" },
{ id: "copy-path", label: "Copy Path" },
+ { id: "copy-thread", label: "Copy Thread" },
{ id: "copy-thread-id", label: "Copy Thread ID" },
{ id: "project-settings", label: "Project settings" },
{
@@ -2253,6 +2256,10 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
copyPathToClipboard(threadWorkspacePath, { path: threadWorkspacePath });
return;
}
+ if (clicked === "copy-thread") {
+ void copyThreadReference(threadChipCopyTarget(threadRef, thread.title));
+ return;
+ }
if (clicked === "copy-thread-id") {
copyThreadIdToClipboard(thread.id, { threadId: thread.id });
return;
diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx
index 97b74aad621..2677c16f259 100644
--- a/apps/web/src/components/Sidebar.tsx
+++ b/apps/web/src/components/Sidebar.tsx
@@ -214,6 +214,8 @@ import {
useActiveRowReveal,
} from "./sidebar/routeReveal";
import { stackedThreadToast, toastManager } from "./ui/toast";
+import { copyThreadReference } from "../lib/copyThreadReference";
+import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference";
import { Button } from "./ui/button";
import {
Combobox,
@@ -2587,6 +2589,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
copyBranchToClipboard(thread.branch, { branch: thread.branch });
}
return;
+ case "copy-thread":
+ void copyThreadReference(threadChipCopyTarget(threadRef, thread.title));
+ return;
case "copy-thread-id":
copyThreadIdToClipboard(thread.id, { threadId: thread.id });
return;
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx
index 9e70a44fb64..21e91237480 100644
--- a/apps/web/src/components/chat/ChatComposer.tsx
+++ b/apps/web/src/components/chat/ChatComposer.tsx
@@ -134,7 +134,10 @@ import {
type TerminalContextDraft,
type TerminalContextSelection,
} from "../../lib/terminalContext";
-import { toKindScopedComposerContextId } from "@t3tools/shared/composerContextReferences";
+import {
+ threadContextRecord,
+ toKindScopedComposerContextId,
+} from "@t3tools/shared/composerContextReferences";
import {
shouldUseCompactComposerPrimaryActions,
shouldUseCompactComposerFooter,
@@ -168,7 +171,6 @@ import {
reviewCommentContextRecord,
terminalContextReference,
terminalContextRecord,
- threadContextRecord,
threadContextReference,
environmentContextRecord,
environmentContextReference,
diff --git a/apps/web/src/components/chat/composerSend.logic.test.ts b/apps/web/src/components/chat/composerSend.logic.test.ts
index 062fbc22eb6..13e36ea5659 100644
--- a/apps/web/src/components/chat/composerSend.logic.test.ts
+++ b/apps/web/src/components/chat/composerSend.logic.test.ts
@@ -2,7 +2,8 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { describe, expect, it } from "vite-plus/test";
import { formatInlineContextReference } from "../../lib/composerContextReferences";
-import { threadContextRecord, threadContextReference } from "../../lib/composerContextRecords";
+import { threadContextReference } from "../../lib/composerContextRecords";
+import { threadContextRecord } from "@t3tools/shared/composerContextReferences";
import {
approvalRedirectNotice,
loadBalancingSendWarning,
diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts
index 4dfa86f471a..457fe3fed31 100644
--- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts
+++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts
@@ -362,7 +362,7 @@ export function commandLabel(command: KeybindingCommand): string {
if (command === "composer.sendAndNewThread") return "Composer: Send and Start New Thread";
if (command === "thread.steerQueuedMessage") return "Queue: Send First Queued Message";
if (command === "thread.editQueuedMessage") return "Queue: Edit Last Queued Message";
- if (command === "thread.copyReference") return "Pull Request: Copy Link or Thread ID";
+ if (command === "thread.copyReference") return "Pull Request: Copy Link or Thread";
const usageMetric = METRIC_OPTIONS.find((option) => option.command === command);
if (usageMetric) return `Usage: ${usageMetric.label}`;
const usagePeriod = WINDOW_OPTIONS.find((option) => option.command === command);
diff --git a/apps/web/src/components/threadActionMenu.logic.ts b/apps/web/src/components/threadActionMenu.logic.ts
index eab2dafd91f..23d057b8be7 100644
--- a/apps/web/src/components/threadActionMenu.logic.ts
+++ b/apps/web/src/components/threadActionMenu.logic.ts
@@ -22,6 +22,7 @@ export type ThreadActionMenuId =
| "copy"
| "copy-path"
| "copy-branch"
+ | "copy-thread"
| "copy-thread-id"
| "archive"
| "delete";
@@ -101,6 +102,7 @@ export function threadActionRequiresOperate(action: ThreadActionMenuId): boolean
"copy",
"copy-path",
"copy-branch",
+ "copy-thread",
"copy-thread-id",
].includes(action);
}
@@ -208,6 +210,7 @@ export function buildThreadActionMenuItems(
...(state.branch
? [{ id: "copy-branch" as const, label: "Branch", icon: "git-branch" }]
: []),
+ { id: "copy-thread", label: "Thread", icon: "message-square" },
{ id: "copy-thread-id", label: "Thread ID", icon: "hash" },
],
},
diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts
index f1551a3a147..57d2991f9b1 100644
--- a/apps/web/src/composerDraftStore.test.ts
+++ b/apps/web/src/composerDraftStore.test.ts
@@ -99,8 +99,8 @@ import {
buildMessageContext,
environmentContextRecord,
terminalContextReference,
- threadContextRecord,
} from "./lib/composerContextRecords";
+import { threadContextRecord } from "@t3tools/shared/composerContextReferences";
import {
copiedComposerAttachmentFile,
rememberCopiedComposerAttachments,
diff --git a/apps/web/src/contextMenuFallback.ts b/apps/web/src/contextMenuFallback.ts
index 2b1442310e2..ecae6bf7c5d 100644
--- a/apps/web/src/contextMenuFallback.ts
+++ b/apps/web/src/contextMenuFallback.ts
@@ -65,6 +65,14 @@ const ICON_PATHS: Record<string, ReadonlyArray<{ tag: string; attrs: Record<stri
},
{ tag: "path", attrs: { d: "m22 10-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 10" } },
],
+ "message-square": [
+ {
+ tag: "path",
+ attrs: {
+ d: "M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",
+ },
+ },
+ ],
"message-square-plus": [
{
tag: "path",
diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.ts
index 0804fc007e1..e03885b2ec2 100644
--- a/apps/web/src/hooks/useThreadActionMenu.ts
+++ b/apps/web/src/hooks/useThreadActionMenu.ts
@@ -22,6 +22,8 @@ import {
type ThreadActionMenuId,
} from "../components/threadActionMenu.logic";
import { stackedThreadToast, toastManager } from "../components/ui/toast";
+import { copyThreadReference } from "../lib/copyThreadReference";
+import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference";
import { threadEnvironment } from "../state/threads";
import { useOrchestrationCommand } from "../state/use-orchestration-command";
import { readEnvironmentScope } from "../state/session";
@@ -269,6 +271,9 @@ export function useThreadActionMenu(input: {
copyBranchToClipboard(thread.branch, { branch: thread.branch });
}
return;
+ case "copy-thread":
+ void copyThreadReference(threadChipCopyTarget(threadRef, thread.title));
+ return;
case "copy-thread-id":
copyThreadIdToClipboard(thread.id, { threadId: thread.id });
return;
diff --git a/apps/web/src/lib/composerContextRecords.ts b/apps/web/src/lib/composerContextRecords.ts
index a595168637c..c3970bba978 100644
--- a/apps/web/src/lib/composerContextRecords.ts
+++ b/apps/web/src/lib/composerContextRecords.ts
@@ -19,7 +19,6 @@ import type {
PreviewAnnotationContextRecord,
PreviewAnnotationPayload,
ReviewCommentContextRecord,
- ScopedThreadRef,
TerminalContextRecord,
ThreadContextRecord,
ThreadId,
@@ -154,27 +153,10 @@ export function previewAnnotationContextReference(
};
}
-function threadContextId(threadId: ThreadId): ComposerContextId {
- return toKindScopedComposerContextId("thread", threadId);
-}
-
export function threadContextReference(record: ThreadContextRecord): ComposerContextReference {
return { kind: "thread", contextId: record.contextId, label: record.label };
}
-export function threadContextRecord(ref: ScopedThreadRef, title: string): ThreadContextRecord {
- const label = sanitizeComposerContextLabel(title, "thread");
- return {
- version: 1,
- kind: "thread",
- contextId: threadContextId(ref.threadId),
- label,
- environmentId: ref.environmentId,
- threadId: ref.threadId,
- title: label,
- };
-}
-
/** One record per machine: mentioning the same machine twice reuses the chip. */
export function environmentContextReference(
record: EnvironmentContextRecord,
diff --git a/apps/web/src/lib/copyThreadReference.ts b/apps/web/src/lib/copyThreadReference.ts
new file mode 100644
index 00000000000..bbfa3b73a2c
--- /dev/null
+++ b/apps/web/src/lib/copyThreadReference.ts
@@ -0,0 +1,34 @@
+import type { ThreadReferenceCopyTarget } from "@t3tools/client-runtime/thread-reference";
+import {
+ COMPOSER_CONTEXT_CLIPBOARD_MIME,
+ encodeComposerContextFragment,
+} from "@t3tools/shared/composerContextClipboard";
+
+import { stackedThreadToast, toastManager } from "../components/ui/toast";
+import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
+
+export async function copyThreadReference(target: ThreadReferenceCopyTarget): Promise<void> {
+ const fragment = target.fragment ? encodeComposerContextFragment(target.fragment) : null;
+ try {
+ const didCopy = await writeTextToClipboard(
+ target.value,
+ target.clipboardTarget,
+ fragment ? { [COMPOSER_CONTEXT_CLIPBOARD_MIME]: fragment } : undefined,
+ );
+ if (!didCopy) return;
+ toastManager.add({
+ type: "success",
+ title: target.successTitle,
+ description: target.description,
+ });
+ } catch (error) {
+ console.error(error);
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: target.failureTitle,
+ description: error instanceof Error ? error.message : "An error occurred.",
+ }),
+ );
+ }
+}
diff --git a/apps/web/src/pendingUserInput.test.ts b/apps/web/src/pendingUserInput.test.ts
index 2fbbca8b707..abc247caef6 100644
--- a/apps/web/src/pendingUserInput.test.ts
+++ b/apps/web/src/pendingUserInput.test.ts
@@ -1,7 +1,8 @@
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { formatInlineContextReference } from "./lib/composerContextReferences";
-import { threadContextRecord, threadContextReference } from "./lib/composerContextRecords";
+import { threadContextReference } from "./lib/composerContextRecords";
+import { threadContextRecord } from "@t3tools/shared/composerContextReferences";
import {
buildPendingUserInputAnswers,
diff --git a/docs/user/composer.md b/docs/user/composer.md
index f263ad90284..e0d1f541851 100644
--- a/docs/user/composer.md
+++ b/docs/user/composer.md
@@ -283,8 +283,9 @@ 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 from
the same server, or from a machine it links to while the Linked environments beta is on; those
show 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. The chip shows the thread's current title and
-opens it when selected. Your prompt only carries a reference: the agent reads the thread's
+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
+current title and opens it when selected. Your prompt only carries a reference: the agent reads the thread's
history on demand, so attaching a long thread costs nothing until the agent looks. Attaching a
thread does not change it, and the agent cannot send messages to it unless you ask.
diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md
index 7478d90aa9b..7c885d68bcf 100644
--- a/docs/user/keybindings.md
+++ b/docs/user/keybindings.md
@@ -48,8 +48,10 @@ in Settings.
With a PR open in the right panel or on the Pull requests page, use `mod+shift+c`
to copy its URL and `mod+shift+k` to copy its number with a `#` prefix.
-Both shortcuts can be changed in Settings. Search for “Copy Link or Thread ID”
+Both shortcuts can be changed in Settings. Search for “Copy Link or Thread”
or “Copy Number”. They copy the selected PR and leave terminal input alone.
+Without a PR, `mod+shift+c` copies the thread itself, which pastes into a
+composer as a thread chip.
## Find in a diff
diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md
index 8e785fad236..cad539b309b 100644
--- a/docs/user/thread-sidebar.md
+++ b/docs/user/thread-sidebar.md
@@ -210,8 +210,11 @@ palette.
Use **Settings → Keybindings** to find or customize shortcuts for searching files
and copying a thread reference. A copied reference uses the thread's pull request
-link when available, otherwise its thread ID. See [keybindings](./keybindings.md)
-for custom configuration.
+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.
+**Thread ID** copies the bare ID for scripts and the `t3` CLI. See
+[keybindings](./keybindings.md) for custom configuration.
## Inspect agent work
diff --git a/packages/client-runtime/src/threadReference.test.ts b/packages/client-runtime/src/threadReference.test.ts
index cf6cb8a0fac..9fa3245df57 100644
--- a/packages/client-runtime/src/threadReference.test.ts
+++ b/packages/client-runtime/src/threadReference.test.ts
@@ -1,8 +1,18 @@
-import type { ThreadPullRequestLink } from "@t3tools/contracts";
+import { EnvironmentId, ThreadId, type ThreadPullRequestLink } from "@t3tools/contracts";
+import {
+ decodeComposerContextFragment,
+ encodeComposerContextFragment,
+} from "@t3tools/shared/composerContextClipboard";
+import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences";
import { describe, expect, it } from "vite-plus/test";
import { resolveThreadReferenceCopyTarget } from "./threadReference.ts";
+const thread = {
+ threadRef: { environmentId: EnvironmentId.make("env-1"), threadId: ThreadId.make("thread-1") },
+ title: "Fix the login flow",
+};
+
const crossRepositoryPullRequest: ThreadPullRequestLink = {
host: "github.com",
repository: "other/repo",
@@ -18,7 +28,7 @@ describe("resolveThreadReferenceCopyTarget", () => {
it("does not copy another reference while the open panel URL is unavailable", () => {
expect(
resolveThreadReferenceCopyTarget({
- threadId: "thread-1",
+ ...thread,
openPanelPullRequestUrl: null,
pullRequests: [crossRepositoryPullRequest],
linkedPullRequestUrl: "https://github.com/t3/pr/12",
@@ -29,7 +39,7 @@ describe("resolveThreadReferenceCopyTarget", () => {
it("prefers the open panel pull request over the thread pull request", () => {
expect(
resolveThreadReferenceCopyTarget({
- threadId: "thread-1",
+ ...thread,
openPanelPullRequestUrl: "https://github.com/t3/pr/14",
pullRequests: [crossRepositoryPullRequest],
linkedPullRequestUrl: "https://github.com/t3/pr/12",
@@ -46,7 +56,7 @@ describe("resolveThreadReferenceCopyTarget", () => {
(linkedPullRequestUrl) => {
expect(
resolveThreadReferenceCopyTarget({
- threadId: "thread-1",
+ ...thread,
pullRequests: [crossRepositoryPullRequest],
linkedPullRequestUrl,
}),
@@ -60,10 +70,41 @@ describe("resolveThreadReferenceCopyTarget", () => {
it("uses the fallback URL when native links are dismissed", () => {
expect(
resolveThreadReferenceCopyTarget({
- threadId: "thread-1",
+ ...thread,
pullRequests: [{ ...crossRepositoryPullRequest, source: "stack-dismissed" }],
linkedPullRequestUrl: "https://github.com/t3/pr/12",
}),
).toMatchObject({ kind: "pull-request", value: "https://github.com/t3/pr/12" });
});
+
+ it("copies a thread chip that pastes back as the same thread on its machine", () => {
+ const target = resolveThreadReferenceCopyTarget({ ...thread, linkedPullRequestUrl: null });
+
+ expect(target).toMatchObject({
+ kind: "thread",
+ description: "Fix the login flow",
+ successTitle: "Thread copied",
+ });
+ const pasted = decodeComposerContextFragment(encodeComposerContextFragment(target!.fragment!));
+ expect(pasted).toEqual({
+ version: 1,
+ source: { environmentId: "env-1" },
+ records: [
+ expect.objectContaining({
+ kind: "thread",
+ environmentId: "env-1",
+ threadId: "thread-1",
+ title: "Fix the login flow",
+ }),
+ ],
+ });
+ // 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",
+ }),
+ ]);
+ });
});
diff --git a/packages/client-runtime/src/threadReference.ts b/packages/client-runtime/src/threadReference.ts
index c537397900d..94f68202a62 100644
--- a/packages/client-runtime/src/threadReference.ts
+++ b/packages/client-runtime/src/threadReference.ts
@@ -1,17 +1,48 @@
-import type { ThreadPullRequestLink } from "@t3tools/contracts";
+import type {
+ ComposerContextClipboardFragment,
+ ScopedThreadRef,
+ ThreadPullRequestLink,
+} from "@t3tools/contracts";
+import {
+ formatComposerContextReference,
+ threadContextRecord,
+} from "@t3tools/shared/composerContextReferences";
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. */
readonly value: string;
+ /** What a toast or palette row shows for the copy. */
+ readonly description: string;
+ /** T3's clipboard format, which pastes a thread back into a composer as a chip. */
+ readonly fragment?: ComposerContextClipboardFragment;
readonly clipboardTarget: string;
readonly successTitle: string;
readonly failureTitle: string;
}
+/** A thread chip pastes into any composer whose agent reads that thread's machine. */
+export function threadChipCopyTarget(
+ threadRef: ScopedThreadRef,
+ title: string,
+): ThreadReferenceCopyTarget {
+ const record = threadContextRecord(threadRef, title);
+ return {
+ kind: "thread",
+ value: formatComposerContextReference(record),
+ description: record.title,
+ fragment: { version: 1, source: { environmentId: threadRef.environmentId }, records: [record] },
+ clipboardTarget: "thread",
+ successTitle: "Thread copied",
+ failureTitle: "Failed to copy thread",
+ };
+}
+
export function resolveThreadReferenceCopyTarget(input: {
- readonly threadId: string;
+ readonly threadRef: ScopedThreadRef;
+ readonly title: string;
/** Undefined means no PR panel; null means its URL is not available yet. */
readonly openPanelPullRequestUrl?: string | null | undefined;
readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
@@ -26,15 +57,10 @@ export function resolveThreadReferenceCopyTarget(input: {
? {
kind: "pull-request",
value: pullRequestUrl,
+ description: pullRequestUrl,
clipboardTarget: "pull request link",
successTitle: "PR link copied",
failureTitle: "Failed to copy PR link",
}
- : {
- kind: "thread",
- value: input.threadId,
- clipboardTarget: "thread ID",
- successTitle: "Thread ID copied",
- failureTitle: "Failed to copy thread ID",
- };
+ : threadChipCopyTarget(input.threadRef, input.title);
}
diff --git a/packages/shared/src/composerContextReferences.test.ts b/packages/shared/src/composerContextReferences.test.ts
index 5ff4470eca8..7212a1b64a9 100644
--- a/packages/shared/src/composerContextReferences.test.ts
+++ b/packages/shared/src/composerContextReferences.test.ts
@@ -1,5 +1,5 @@
import {
- type ComposerContextId,
+ ComposerContextId,
type ComposerContextRecord,
EnvironmentId,
ThreadId,
@@ -12,6 +12,7 @@ import {
isImageReferencesOnly,
parseComposerContextHref,
projectComposerContextForProvider,
+ threadContextRecord,
threadContextsOutsideEnvironment,
toComposerContextId,
toKindScopedComposerContextId,
@@ -382,3 +383,26 @@ describe("toComposerContextId", () => {
expect(first.length).toBeLessThanOrEqual(128);
});
});
+
+describe("threadContextRecord", () => {
+ it("mints a schema-valid id that survives a rename, for agent-spawned thread ids too", () => {
+ const environmentId = EnvironmentId.make("env-1");
+ const ref = {
+ environmentId,
+ threadId: ThreadId.make(`thread:mcp:${encodeURIComponent("3f2b:delegate")}:review:0`),
+ };
+ const record = threadContextRecord(ref, "Review [draft]\nnotes");
+
+ expect(() => ComposerContextId.make(record.contextId)).not.toThrow();
+ expect(threadContextRecord(ref, "Renamed").contextId).toBe(record.contextId);
+ expect(record).toMatchObject({
+ environmentId,
+ threadId: ref.threadId,
+ label: "Review draft notes",
+ title: "Review draft notes",
+ });
+ expect(
+ threadContextRecord({ environmentId, threadId: ThreadId.make("abc-123") }, "").contextId,
+ ).toBe("thread_abc-123");
+ });
+});
diff --git a/packages/shared/src/composerContextReferences.ts b/packages/shared/src/composerContextReferences.ts
index e895859cbd8..e1b25bc094a 100644
--- a/packages/shared/src/composerContextReferences.ts
+++ b/packages/shared/src/composerContextReferences.ts
@@ -6,6 +6,7 @@ import {
type ElementContextDetails,
type EnvironmentId,
type KnownComposerContextRecord,
+ type ScopedThreadRef,
type ThreadContextRecord,
} from "@t3tools/contracts";
@@ -74,6 +75,20 @@ export function sanitizeComposerContextLabel(label: string, kind: ComposerContex
return cleaned.length > 0 ? cleaned : kind;
}
+/** One record per thread, so re-attaching a renamed thread reuses its chip. */
+export function threadContextRecord(ref: ScopedThreadRef, title: string): ThreadContextRecord {
+ const label = sanitizeComposerContextLabel(title, "thread");
+ return {
+ version: 1,
+ kind: "thread",
+ contextId: toKindScopedComposerContextId("thread", ref.threadId),
+ label,
+ environmentId: ref.environmentId,
+ threadId: ref.threadId,
+ title: label,
+ };
+}
+
export function formatComposerContextReference(reference: {
kind: ComposerContextKind;
contextId: ComposerContextId;