diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 6774731a73..664e4e4e26 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -22,6 +22,8 @@ import { PreviewSnapshotToolkit, PreviewStandardToolkit, } from "./toolkits/preview/tools.ts"; +import { ThreadReferenceToolkitHandlersLive } from "./toolkits/threadReference/handlers.ts"; +import { ThreadReferenceToolkit } from "./toolkits/threadReference/tools.ts"; const unauthorized = HttpServerResponse.jsonUnsafe( { @@ -208,10 +210,17 @@ export const PreviewToolkitRegistrationLive = Layer.mergeAll( PreviewSnapshotRegistrationLive, ); +export const ThreadReferenceToolkitRegistrationLive = McpServer.toolkit( + ThreadReferenceToolkit, +).pipe(Layer.provide(ThreadReferenceToolkitHandlersLive)); + const McpTransportLive = McpServer.layerHttp({ name: "T3 Code", version: packageJson.version, path: "/mcp", }).pipe(Layer.provide(McpAuthMiddlewareLive)); -export const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive)); +export const layer = Layer.mergeAll( + PreviewToolkitRegistrationLive, + ThreadReferenceToolkitRegistrationLive, +).pipe(Layer.provideMerge(McpTransportLive)); diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index b13bf2d312..d22f535356 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -7,7 +7,7 @@ import { import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; -export type McpCapability = "preview"; +export type McpCapability = "preview" | "thread-reference"; export interface McpInvocationScope { readonly environmentId: EnvironmentId; @@ -25,7 +25,7 @@ export class McpInvocationContext extends Context.Service< >()("t3/mcp/McpInvocationContext") {} export const requireMcpCapability = Effect.fn("mcp.requireCapability")(function* ( - capability: McpCapability, + capability: "preview", ) { const invocation = yield* McpInvocationContext; if (!invocation.capabilities.has(capability)) { diff --git a/apps/server/src/mcp/McpSessionRegistry.test.ts b/apps/server/src/mcp/McpSessionRegistry.test.ts index a91d98febd..341def2b9e 100644 --- a/apps/server/src/mcp/McpSessionRegistry.test.ts +++ b/apps/server/src/mcp/McpSessionRegistry.test.ts @@ -47,6 +47,7 @@ it.effect("stores only a token hash, resolves the bearer token, and revokes by t const resolved = yield* registry.resolve(token); expect(resolved?.threadId).toBe(threadId); + expect(resolved?.capabilities).toEqual(new Set(["preview", "thread-reference"])); yield* registry.revokeThread(threadId); expect(yield* registry.resolve(token)).toBeUndefined(); diff --git a/apps/server/src/mcp/McpSessionRegistry.ts b/apps/server/src/mcp/McpSessionRegistry.ts index 67c4f2f0ff..8ea2d03902 100644 --- a/apps/server/src/mcp/McpSessionRegistry.ts +++ b/apps/server/src/mcp/McpSessionRegistry.ts @@ -114,7 +114,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( threadId: ThreadId.make(request.threadId), providerSessionId, providerInstanceId: ProviderInstanceId.make(request.providerInstanceId), - capabilities: new Set(["preview"]), + capabilities: new Set(["preview", "thread-reference"]), issuedAt, expiresAt, }; diff --git a/apps/server/src/mcp/toolkits/threadReference/handlers.test.ts b/apps/server/src/mcp/toolkits/threadReference/handlers.test.ts new file mode 100644 index 0000000000..1072579080 --- /dev/null +++ b/apps/server/src/mcp/toolkits/threadReference/handlers.test.ts @@ -0,0 +1,107 @@ +import { expect, it } from "@effect/vitest"; +import { + MessageId, + ProjectId, + ProviderInstanceId, + ThreadId, + type OrchestrationMessage, + type OrchestrationThread, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import { McpSchema, McpServer } from "effect/unstable/ai"; + +import * as McpInvocationContext from "../../McpInvocationContext.ts"; +import { ProjectionSnapshotQuery } from "../../../orchestration/Services/ProjectionSnapshotQuery.ts"; +import { buildThreadReferencePage, ThreadReferenceToolkitHandlersLive } from "./handlers.ts"; +import { ThreadReferenceToolkit } from "./tools.ts"; + +const TestLayer = McpServer.toolkit(ThreadReferenceToolkit).pipe( + Layer.provide(ThreadReferenceToolkitHandlersLive), + Layer.provideMerge(McpServer.McpServer.layer), +); + +const makeMessage = (id: string, text: string): OrchestrationMessage => ({ + id: MessageId.make(id), + role: "user", + text, + turnId: null, + streaming: false, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", +}); + +const thread = { + id: ThreadId.make("thread-referenced"), + projectId: ProjectId.make("project-1"), + title: "Referenced work", + messages: [makeMessage("message-1", "abcdef"), makeMessage("message-2", "ghijkl")], +} as unknown as OrchestrationThread; + +it("paginates within a message without losing transcript text", () => { + const first = buildThreadReferencePage(thread, { + threadId: thread.id, + maxChars: 1_000, + }); + expect(first).toMatchObject({ nextCursor: null, totalMessages: 2 }); + + const longThread = { + ...thread, + messages: [makeMessage("message-long", "a".repeat(1_100))], + }; + const longFirst = buildThreadReferencePage(longThread, { + threadId: thread.id, + maxChars: 1_000, + }); + expect(longFirst).toMatchObject({ nextCursor: "0:1000" }); + if ("_tag" in longFirst) throw new Error("unexpected cursor error"); + const longSecond = buildThreadReferencePage(longThread, { + threadId: thread.id, + cursor: longFirst.nextCursor!, + maxChars: 1_000, + }); + if ("_tag" in longSecond) throw new Error("unexpected cursor error"); + expect(longFirst.messages[0]?.text.length).toBe(1_000); + expect(longSecond.messages[0]?.text.length).toBe(100); + expect(longSecond.nextCursor).toBeNull(); +}); + +it.effect("reads a referenced thread through the MCP toolkit", () => + Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const result = yield* server.callTool({ + name: "thread_read", + arguments: { threadId: thread.id }, + }); + expect(result.isError).toBe(false); + expect(result.structuredContent).toMatchObject({ + threadId: thread.id, + title: thread.title, + totalMessages: 2, + }); + }).pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, { + environmentId: "environment-1" as never, + threadId: ThreadId.make("thread-current"), + providerSessionId: "provider-session-1", + providerInstanceId: ProviderInstanceId.make("codex"), + capabilities: new Set(["thread-reference"] as const), + issuedAt: 1, + expiresAt: Number.MAX_SAFE_INTEGER, + }), + Effect.provideService(McpSchema.McpServerClient, { + clientId: 1, + initializePayload: { + protocolVersion: "2025-03-26", + capabilities: {}, + clientInfo: { name: "test", version: "1" }, + }, + getClient: Effect.die("unused"), + }), + Effect.provideService(ProjectionSnapshotQuery, { + getThreadDetailById: () => Effect.succeed(Option.some(thread)), + } as never), + Effect.provide(TestLayer), + ), +); diff --git a/apps/server/src/mcp/toolkits/threadReference/handlers.ts b/apps/server/src/mcp/toolkits/threadReference/handlers.ts new file mode 100644 index 0000000000..50c8738d40 --- /dev/null +++ b/apps/server/src/mcp/toolkits/threadReference/handlers.ts @@ -0,0 +1,122 @@ +import { + THREAD_REFERENCE_DEFAULT_MAX_CHARS, + ThreadReferenceInvalidCursorError, + ThreadReferenceNotFoundError, + type ThreadReferenceReadInput, + type ThreadReferenceReadResult, + type ThreadReferenceTranscriptMessage, + ThreadReferenceUnavailableError, + type OrchestrationThread, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import * as McpInvocationContext from "../../McpInvocationContext.ts"; +import { ProjectionSnapshotQuery } from "../../../orchestration/Services/ProjectionSnapshotQuery.ts"; +import { ThreadReferenceToolkit } from "./tools.ts"; + +interface TranscriptPosition { + readonly messageIndex: number; + readonly textOffset: number; +} + +function decodeCursor( + input: ThreadReferenceReadInput, + thread: OrchestrationThread, +): TranscriptPosition | null { + if (!input.cursor) return { messageIndex: 0, textOffset: 0 }; + const [messageIndexText, textOffsetText] = input.cursor.split(":"); + const messageIndex = Number(messageIndexText); + const textOffset = Number(textOffsetText); + const message = thread.messages[messageIndex]; + const validEndCursor = messageIndex === thread.messages.length && textOffset === 0; + if ( + !Number.isSafeInteger(messageIndex) || + !Number.isSafeInteger(textOffset) || + messageIndex < 0 || + textOffset < 0 || + (!validEndCursor && (!message || textOffset >= message.text.length)) + ) { + return null; + } + return { messageIndex, textOffset }; +} + +export function buildThreadReferencePage( + thread: OrchestrationThread, + input: ThreadReferenceReadInput, +): ThreadReferenceReadResult | ThreadReferenceInvalidCursorError { + const position = decodeCursor(input, thread); + if (!position) { + return new ThreadReferenceInvalidCursorError({ + threadId: input.threadId, + cursor: input.cursor ?? "", + }); + } + + const maxChars = input.maxChars ?? THREAD_REFERENCE_DEFAULT_MAX_CHARS; + const messages: ThreadReferenceTranscriptMessage[] = []; + let messageIndex = position.messageIndex; + let textOffset = position.textOffset; + let includedChars = 0; + + while (messageIndex < thread.messages.length && includedChars < maxChars) { + const message = thread.messages[messageIndex]; + if (!message) break; + const remainingChars = maxChars - includedChars; + const text = message.text.slice(textOffset, textOffset + remainingChars); + const textEnd = textOffset + text.length; + const textComplete = textEnd >= message.text.length; + messages.push({ + id: message.id, + role: message.role, + text, + textStart: textOffset, + textEnd, + textComplete, + attachments: [...(message.attachments ?? [])], + createdAt: message.createdAt, + }); + includedChars += text.length; + if (!textComplete) { + textOffset = textEnd; + break; + } + messageIndex += 1; + textOffset = 0; + } + + return { + threadId: thread.id, + projectId: thread.projectId, + title: thread.title, + messages, + totalMessages: thread.messages.length, + nextCursor: messageIndex < thread.messages.length ? `${messageIndex}:${textOffset}` : null, + }; +} + +const threadRead = Effect.fn("ThreadReferenceToolkit.threadRead")(function* ( + input: ThreadReferenceReadInput, +) { + const invocation = yield* McpInvocationContext.McpInvocationContext; + if (!invocation.capabilities.has("thread-reference")) { + return yield* new ThreadReferenceUnavailableError({ threadId: input.threadId }); + } + const snapshotQuery = yield* ProjectionSnapshotQuery; + const threadOption = yield* snapshotQuery + .getThreadDetailById(input.threadId) + .pipe(Effect.mapError(() => new ThreadReferenceUnavailableError({ threadId: input.threadId }))); + if (Option.isNone(threadOption)) { + return yield* new ThreadReferenceNotFoundError({ threadId: input.threadId }); + } + const page = buildThreadReferencePage(threadOption.value, input); + if ("_tag" in page) { + return yield* page; + } + return page; +}); + +export const ThreadReferenceToolkitHandlersLive = ThreadReferenceToolkit.toLayer({ + thread_read: threadRead, +}); diff --git a/apps/server/src/mcp/toolkits/threadReference/tools.ts b/apps/server/src/mcp/toolkits/threadReference/tools.ts new file mode 100644 index 0000000000..75d60338f3 --- /dev/null +++ b/apps/server/src/mcp/toolkits/threadReference/tools.ts @@ -0,0 +1,24 @@ +import { + ThreadReferenceReadError, + ThreadReferenceReadInput, + ThreadReferenceReadResult, +} from "@t3tools/contracts"; +import { Tool, Toolkit } from "effect/unstable/ai"; + +import * as McpInvocationContext from "../../McpInvocationContext.ts"; +import { ProjectionSnapshotQuery } from "../../../orchestration/Services/ProjectionSnapshotQuery.ts"; + +export const ThreadReadTool = Tool.make("thread_read", { + description: + "Read a T3 Code chat thread referenced by a t3-thread link in the user's message. Pass the threadId from that link. The transcript is paginated; when nextCursor is non-null, call thread_read again with that cursor to continue. Do not call this for unrelated threads that the user did not reference.", + parameters: ThreadReferenceReadInput, + success: ThreadReferenceReadResult, + failure: ThreadReferenceReadError, + dependencies: [McpInvocationContext.McpInvocationContext, ProjectionSnapshotQuery], +}) + .annotate(Tool.Title, "Read referenced chat thread") + .annotate(Tool.Readonly, true) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, true); + +export const ThreadReferenceToolkit = Toolkit.make(ThreadReadTool); diff --git a/apps/server/src/provider/CodexDeveloperInstructions.ts b/apps/server/src/provider/CodexDeveloperInstructions.ts index 35ffd1a475..1c54f4f541 100644 --- a/apps/server/src/provider/CodexDeveloperInstructions.ts +++ b/apps/server/src/provider/CodexDeveloperInstructions.ts @@ -11,6 +11,13 @@ For browser work, first call \`preview_status\`. If no automation-capable previe Do not switch to global browser skills, Chrome, Node REPL browser automation, standalone Playwright, or agent-browser merely because the preview is initially closed or a first call fails. Use an alternative browser system only when the T3 preview tools are absent, the user explicitly requests another browser, or \`preview_open\` returns an explicit unsupported/unavailable error. A failed T3 preview tool call should be inspected and retried with corrected arguments when the error is actionable. `; +const T3_CODE_THREAD_REFERENCE_INSTRUCTIONS = ` + +## T3 Code thread references + +The user may reference another chat with a \`t3-thread\` link. Do not treat the link as a web URL and do not assume its contents. Use the read-only \`thread_read\` tool from the \`t3-code\` MCP server with the referenced thread id. Follow \`nextCursor\` until you have read as much of the transcript as the task requires. +`; + export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `# Plan Mode (Conversational) You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions. @@ -132,6 +139,7 @@ Do not ask "should I proceed?" in the final output. The user can easily switch o Only produce at most one \`\` block per turn, and only when you are presenting a complete spec. ${T3_CODE_BROWSER_TOOL_INSTRUCTIONS} +${T3_CODE_THREAD_REFERENCE_INSTRUCTIONS} `; export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `# Collaboration Mode: Default @@ -146,6 +154,7 @@ The \`request_user_input\` tool is unavailable in Default mode. If you call it w In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message. ${T3_CODE_BROWSER_TOOL_INSTRUCTIONS} +${T3_CODE_THREAD_REFERENCE_INSTRUCTIONS} `; export interface CodexRuntimeInfo { diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts index 119fa36303..f48842a03a 100644 --- a/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts +++ b/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts @@ -274,6 +274,8 @@ describe("T3 browser developer instructions", () => { NodeAssert.match(instructions, /t3-code/); NodeAssert.match(instructions, /preview_status/); NodeAssert.match(instructions, /preview_open/); + NodeAssert.match(instructions, /thread_read/); + NodeAssert.match(instructions, /t3-thread/); NodeAssert.match(instructions, /Do not switch to global browser skills/); } }); diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index c85340c715..77040f9f43 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -7,9 +7,18 @@ import { GlobeIcon, Maximize2Icon, Minimize2Icon, + MessagesSquareIcon, WrapTextIcon, } from "lucide-react"; -import type { ScopedThreadRef, ServerProviderSkill } from "@t3tools/contracts"; +import { + EnvironmentId, + type ScopedThreadRef, + type ServerProviderSkill, + ThreadId, +} from "@t3tools/contracts"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { parseComposerThreadLink } from "@t3tools/shared/composerTrigger"; +import { useNavigate } from "@tanstack/react-router"; import { isAtomCommandInterrupted, squashAtomCommandFailure, @@ -83,6 +92,7 @@ import { openUrlInPreview, BrowserPreviewUnavailableError, } from "../browser/openFileInPreview"; +import { buildThreadRouteParams } from "../threadRoutes"; class CodeHighlightErrorBoundary extends React.Component< { fallback: ReactNode; children: ReactNode }, @@ -161,7 +171,7 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = { }, protocols: { ...defaultSchema.protocols, - href: [...(defaultSchema.protocols?.href ?? []), "file"], + href: [...(defaultSchema.protocols?.href ?? []), "file", "t3-thread"], }, } satisfies Parameters[0]; @@ -1258,6 +1268,7 @@ function ChatMarkdown({ lineBreaks = false, }: ChatMarkdownProps) { const { resolvedTheme } = useTheme(); + const navigate = useNavigate(); const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, { reportFailure: false, }); @@ -1292,6 +1303,7 @@ function ChatMarkdown({ return buildFileLinkParentSuffixByPath(filePaths); }, [markdownFileLinkMetaByHref]); const markdownUrlTransform = useCallback((href: string) => { + if (parseComposerThreadLink(href)) return href; return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href); }, []); // Re-emit highlighted content as markdown so copying out of the rendered @@ -1391,6 +1403,43 @@ function ChatMarkdown({ }, a({ node, href, children, ...props }) { const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : ""; + const threadReference = normalizedHref ? parseComposerThreadLink(normalizedHref) : null; + if (threadReference) { + const target = scopeThreadRef( + EnvironmentId.make(threadReference.environmentId), + ThreadId.make(threadReference.threadId), + ); + const link = ( + { + event.preventDefault(); + event.stopPropagation(); + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(target), + }); + }} + > + + ); + return ( + + + + Open referenced thread + + + ); + } const fileLinkMeta = normalizedHref ? markdownFileLinkMetaByHref.get(normalizedHref) : null; if (!fileLinkMeta) { const faviconHost = resolveExternalLinkHost(href); @@ -1543,6 +1592,7 @@ function ChatMarkdown({ fileLinkParentSuffixByPath, isStreaming, markdownFileLinkMetaByHref, + navigate, onTaskListChange, openInPreferredEditor, openExternalLinkInPreview, diff --git a/apps/web/src/components/ComposerPromptEditor.tsx b/apps/web/src/components/ComposerPromptEditor.tsx index 169126788a..8a1140b83b 100644 --- a/apps/web/src/components/ComposerPromptEditor.tsx +++ b/apps/web/src/components/ComposerPromptEditor.tsx @@ -6,7 +6,11 @@ import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin"; import { OnChangePlugin } from "@lexical/react/LexicalOnChangePlugin"; import { PlainTextPlugin } from "@lexical/react/LexicalPlainTextPlugin"; import { type ServerProviderSkill } from "@t3tools/contracts"; -import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger"; +import { + serializeComposerFileLink, + serializeComposerThreadLink, +} from "@t3tools/shared/composerTrigger"; +import { MessagesSquareIcon } from "lucide-react"; import { $applyNodeReplacement, $createRangeSelectionFromDom, @@ -119,6 +123,17 @@ type SerializedComposerSkillNode = Spread< SerializedLexicalNode >; +type SerializedComposerThreadNode = Spread< + { + environmentId: string; + threadId: string; + title: string; + type: "composer-thread"; + version: 1; + }, + SerializedLexicalNode +>; + type SerializedComposerTerminalContextNode = Spread< { context: TerminalContextDraft; @@ -360,6 +375,103 @@ function $createComposerSkillNode( return $applyNodeReplacement(new ComposerSkillNode(skillName, skillLabel, skillDescription)); } +function ComposerThreadDecorator(props: { title: string; threadId: string }) { + const chip = ( + + + ); + + return ( + + + + Thread reference ยท {props.threadId} + + + ); +} + +class ComposerThreadNode extends DecoratorNode { + __environmentId: string; + __threadId: string; + __title: string; + + static override getType(): string { + return "composer-thread"; + } + + static override clone(node: ComposerThreadNode): ComposerThreadNode { + return new ComposerThreadNode(node.__environmentId, node.__threadId, node.__title, node.__key); + } + + static override importJSON(serializedNode: SerializedComposerThreadNode): ComposerThreadNode { + return $createComposerThreadNode( + serializedNode.environmentId, + serializedNode.threadId, + serializedNode.title, + ).updateFromJSON(serializedNode); + } + + constructor(environmentId: string, threadId: string, title: string, key?: NodeKey) { + super(key); + this.__environmentId = environmentId; + this.__threadId = threadId; + this.__title = title; + } + + override exportJSON(): SerializedComposerThreadNode { + return { + ...super.exportJSON(), + environmentId: this.__environmentId, + threadId: this.__threadId, + title: this.__title, + type: "composer-thread", + version: 1, + }; + } + + override createDOM(): HTMLElement { + const dom = document.createElement("span"); + dom.className = "inline-flex align-middle leading-none"; + return dom; + } + + override updateDOM(): false { + return false; + } + + override getTextContent(): string { + return serializeComposerThreadLink({ + environmentId: this.__environmentId, + threadId: this.__threadId, + title: this.__title, + }); + } + + override isInline(): true { + return true; + } + + override decorate(): React.ReactElement { + return ; + } +} + +function $createComposerThreadNode( + environmentId: string, + threadId: string, + title: string, +): ComposerThreadNode { + return $applyNodeReplacement(new ComposerThreadNode(environmentId, threadId, title)); +} + function ComposerTerminalContextDecorator(props: { context: TerminalContextDraft }) { return ; } @@ -427,12 +539,14 @@ function $createComposerTerminalContextNode( type ComposerInlineTokenNode = | ComposerMentionNode | ComposerSkillNode + | ComposerThreadNode | ComposerTerminalContextNode; function isComposerInlineTokenNode(candidate: unknown): candidate is ComposerInlineTokenNode { return ( candidate instanceof ComposerMentionNode || candidate instanceof ComposerSkillNode || + candidate instanceof ComposerThreadNode || candidate instanceof ComposerTerminalContextNode ); } @@ -844,6 +958,12 @@ function $setComposerEditorPrompt( ); continue; } + if (segment.type === "thread") { + paragraph.append( + $createComposerThreadNode(segment.environmentId, segment.threadId, segment.title), + ); + continue; + } if (segment.type === "terminal-context") { if (segment.context) { paragraph.append($createComposerTerminalContextNode(segment.context)); @@ -1806,7 +1926,12 @@ export function ComposerPromptEditor({ () => ({ namespace: "t3tools-composer-editor", editable: true, - nodes: [ComposerMentionNode, ComposerSkillNode, ComposerTerminalContextNode], + nodes: [ + ComposerMentionNode, + ComposerSkillNode, + ComposerThreadNode, + ComposerTerminalContextNode, + ], editorState: () => { $setComposerEditorPrompt( initialValueRef.current, diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index f3346b4100..795fd3bff9 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -22,7 +22,10 @@ import { connectionStatusText, type EnvironmentConnectionPresentation, } from "@t3tools/client-runtime/connection"; -import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger"; +import { + serializeComposerFileLink, + serializeComposerThreadLink, +} from "@t3tools/shared/composerTrigger"; import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model"; import { memo, @@ -131,6 +134,8 @@ import { formatProviderSkillDisplayName } from "../../providerSkillPresentation" import { searchProviderSkills } from "../../providerSkillSearch"; import { useMediaQuery } from "../../hooks/useMediaQuery"; import type { ReviewCommentContext } from "../../reviewCommentContext"; +import { useThreadShells } from "../../state/entities"; +import { searchThreadReferences } from "../../threadReferenceSearch"; const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`; @@ -639,6 +644,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const composerPreviewAnnotations = composerDraft.previewAnnotations; const composerReviewComments = composerDraft.reviewComments; const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds; + const threadShells = useThreadShells(); const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt); const addComposerDraftImage = useComposerDraftStore((store) => store.addImage); @@ -1024,8 +1030,30 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }), ); } + if (composerTrigger.kind === "thread") { + const candidates = threadShells.filter( + (thread) => thread.environmentId === environmentId && thread.id !== routeThreadRef.threadId, + ); + return searchThreadReferences(candidates, composerTrigger.query).map((thread) => ({ + id: `thread:${thread.environmentId}:${thread.id}`, + type: "thread" as const, + environmentId: thread.environmentId, + threadId: thread.id, + title: thread.title, + label: thread.title, + description: thread.branch ?? `Thread ${thread.id}`, + })); + } return []; - }, [composerTrigger, selectedProvider, selectedProviderStatus, workspaceEntries.entries]); + }, [ + composerTrigger, + environmentId, + routeThreadRef.threadId, + selectedProvider, + selectedProviderStatus, + threadShells, + workspaceEntries.entries, + ]); const composerMenuOpen = Boolean(composerTrigger); const composerMenuSearchKey = composerTrigger @@ -1095,6 +1123,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (composerTriggerKind === "skill") { return "No skills found. Try / to browse provider commands."; } + if (composerTriggerKind === "thread") { + return "No matching threads in this environment."; + } return composerTriggerKind === "path" ? "No matching files or folders." : "No matching command."; @@ -1596,6 +1627,28 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) } return; } + if (item.type === "thread") { + const replacement = `${serializeComposerThreadLink({ + environmentId: item.environmentId, + threadId: item.threadId, + title: item.title, + })} `; + const replacementRangeEnd = extendReplacementRangeForTrailingSpace( + snapshot.value, + trigger.rangeEnd, + replacement, + ); + const applied = applyPromptReplacement( + trigger.rangeStart, + replacementRangeEnd, + replacement, + { expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) }, + ); + if (applied) { + setComposerHighlightedItemId(null); + } + return; + } if (item.type === "slash-command") { if (item.command === "model") { const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", { diff --git a/apps/web/src/components/chat/ComposerCommandMenu.tsx b/apps/web/src/components/chat/ComposerCommandMenu.tsx index 8354412ce1..250e4b4c9c 100644 --- a/apps/web/src/components/chat/ComposerCommandMenu.tsx +++ b/apps/web/src/components/chat/ComposerCommandMenu.tsx @@ -1,10 +1,12 @@ import { + type EnvironmentId, type ProjectEntry, type ProviderDriverKind, type ServerProviderSkill, type ServerProviderSlashCommand, + type ThreadId, } from "@t3tools/contracts"; -import { BotIcon } from "lucide-react"; +import { BotIcon, MessagesSquareIcon } from "lucide-react"; import { memo, useLayoutEffect, useMemo, useRef } from "react"; import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic"; @@ -51,6 +53,15 @@ export type ComposerCommandItem = skill: ServerProviderSkill; label: string; description: string; + } + | { + id: string; + type: "thread"; + environmentId: EnvironmentId; + threadId: ThreadId; + title: string; + label: string; + description: string; }; type ComposerCommandGroup = { @@ -86,6 +97,9 @@ function groupCommandItems( if (triggerKind === "skill") { return items.length > 0 ? [{ id: "skills", label: "Skills", items }] : []; } + if (triggerKind === "thread") { + return items.length > 0 ? [{ id: "threads", label: "Threads", items }] : []; + } if (triggerKind !== "slash-command" || !groupSlashCommandSections) { return [{ id: "default", label: null, items }]; } @@ -170,16 +184,20 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: { ) : (
- {props.triggerKind === "skill" ? ( + {props.triggerKind === "skill" || props.triggerKind === "thread" ? ( - Skills + {props.triggerKind === "thread" ? "Threads" : "Skills"}

{props.isLoading - ? "Searching workspace skills..." + ? props.triggerKind === "thread" + ? "Searching threads..." + : "Searching workspace skills..." : (props.emptyStateText ?? - "No skills found. Try / to browse provider commands.")} + (props.triggerKind === "thread" + ? "No matching threads." + : "No skills found. Try / to browse provider commands."))}

) : ( @@ -247,6 +265,9 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: { ) : null} + {props.item.type === "thread" ? ( + + ) : null} {props.item.label} diff --git a/apps/web/src/composer-editor-mentions.test.ts b/apps/web/src/composer-editor-mentions.test.ts index d79170769d..206558a041 100644 --- a/apps/web/src/composer-editor-mentions.test.ts +++ b/apps/web/src/composer-editor-mentions.test.ts @@ -71,6 +71,24 @@ describe("splitPromptIntoComposerSegments", () => { ).toEqual([{ type: "text", text: "Read [the docs](https://example.com/docs) first" }]); }); + it("splits T3 thread links into thread segments", () => { + expect( + splitPromptIntoComposerSegments( + "Continue from [Prior chat](t3-thread:///environment-1/thread-2) please", + ), + ).toEqual([ + { type: "text", text: "Continue from " }, + { + type: "thread", + environmentId: "environment-1", + threadId: "thread-2", + title: "Prior chat", + source: "[Prior chat](t3-thread:///environment-1/thread-2)", + }, + { type: "text", text: " please" }, + ]); + }); + it("decodes reserved path characters from generated links", () => { expect( splitPromptIntoComposerSegments( diff --git a/apps/web/src/composer-editor-mentions.ts b/apps/web/src/composer-editor-mentions.ts index 8b9a53808f..78fed07196 100644 --- a/apps/web/src/composer-editor-mentions.ts +++ b/apps/web/src/composer-editor-mentions.ts @@ -21,6 +21,13 @@ export type ComposerPromptSegment = type: "skill"; name: string; } + | { + type: "thread"; + environmentId: string; + threadId: string; + title: string; + source: string; + } | { type: "terminal-context"; context: TerminalContextDraft | null; @@ -147,6 +154,14 @@ function splitPromptTextIntoComposerSegments(text: string): ComposerPromptSegmen path: match.value, source: match.source, }); + } else if (match.type === "thread") { + segments.push({ + type: "thread", + environmentId: match.environmentId, + threadId: match.threadId, + title: match.title, + source: match.source, + }); } else { segments.push({ type: "skill", name: match.value }); } diff --git a/apps/web/src/composer-logic.test.ts b/apps/web/src/composer-logic.test.ts index 99ac6bba71..bb71dec343 100644 --- a/apps/web/src/composer-logic.test.ts +++ b/apps/web/src/composer-logic.test.ts @@ -106,6 +106,17 @@ describe("detectComposerTrigger", () => { }); }); + it("detects #thread trigger at cursor", () => { + const text = "Continue from #auth"; + + expect(detectComposerTrigger(text, text.length)).toEqual({ + kind: "thread", + query: "auth", + rangeStart: "Continue from ".length, + rangeEnd: text.length, + }); + }); + it("detects @path trigger in the middle of existing text", () => { // User typed @ between "inspect " and "in this sentence" const text = "Please inspect @in this sentence"; diff --git a/apps/web/src/composer-logic.ts b/apps/web/src/composer-logic.ts index 2d1d3aed3b..ee453f2e59 100644 --- a/apps/web/src/composer-logic.ts +++ b/apps/web/src/composer-logic.ts @@ -1,7 +1,7 @@ import { splitPromptIntoComposerSegments } from "./composer-editor-mentions"; import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "./lib/terminalContext"; -export type ComposerTriggerKind = "path" | "slash-command" | "skill"; +export type ComposerTriggerKind = "path" | "slash-command" | "skill" | "thread"; export type ComposerSlashCommand = "model" | "plan" | "default"; export interface ComposerTrigger { @@ -22,6 +22,7 @@ const isInlineTokenSegment = ( segment: | { type: "text"; text: string } | { type: "mention" } + | { type: "thread" } | { type: "skill" } | { type: "terminal-context" }, ): boolean => segment.type !== "text"; @@ -60,7 +61,7 @@ export function expandCollapsedComposerCursor(text: string, cursorInput: number) let expandedCursor = 0; for (const segment of segments) { - if (segment.type === "mention") { + if (segment.type === "mention" || segment.type === "thread") { const expandedLength = segment.source.length; if (remaining <= 1) { return expandedCursor + (remaining === 0 ? 0 : expandedLength); @@ -102,6 +103,7 @@ function collapsedSegmentLength( segment: | { type: "text"; text: string } | { type: "mention" } + | { type: "thread" } | { type: "skill" } | { type: "terminal-context" }, ): number { @@ -115,6 +117,7 @@ function clampCollapsedComposerCursorForSegments( segments: ReadonlyArray< | { type: "text"; text: string } | { type: "mention" } + | { type: "thread" } | { type: "skill" } | { type: "terminal-context" } >, @@ -148,7 +151,7 @@ export function collapseExpandedComposerCursor(text: string, cursorInput: number let collapsedCursor = 0; for (const segment of segments) { - if (segment.type === "mention") { + if (segment.type === "mention" || segment.type === "thread") { const expandedLength = segment.source.length; if (remaining === 0) { return collapsedCursor; @@ -250,6 +253,14 @@ export function detectComposerTrigger(text: string, cursorInput: number): Compos rangeEnd: cursor, }; } + if (token.startsWith("#")) { + return { + kind: "thread", + query: token.slice(1), + rangeStart: tokenStart, + rangeEnd: cursor, + }; + } if (!token.startsWith("@")) { return null; } diff --git a/apps/web/src/threadReferenceSearch.test.ts b/apps/web/src/threadReferenceSearch.test.ts new file mode 100644 index 0000000000..23904b9756 --- /dev/null +++ b/apps/web/src/threadReferenceSearch.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { searchThreadReferences } from "./threadReferenceSearch"; + +const thread = (id: string, title: string, updatedAt: string, branch: string | null = null) => + ({ id, title, updatedAt, branch }) as never; + +describe("searchThreadReferences", () => { + it("shows recently updated threads when the query is empty", () => { + const result = searchThreadReferences( + [ + thread("one", "Older", "2026-01-01T00:00:00.000Z"), + thread("two", "Newer", "2026-02-01T00:00:00.000Z"), + ], + "", + ); + + expect(result.map(({ id }) => id)).toEqual(["two", "one"]); + }); + + it("ranks title, branch, and id matches", () => { + const threads = [ + thread("thread-auth", "Authentication follow-up", "2026-01-01T00:00:00.000Z"), + thread("thread-two", "Unrelated", "2026-01-02T00:00:00.000Z", "feat/auth-flow"), + ]; + + expect(searchThreadReferences(threads, "auth").map(({ id }) => id)).toEqual([ + "thread-auth", + "thread-two", + ]); + }); +}); diff --git a/apps/web/src/threadReferenceSearch.ts b/apps/web/src/threadReferenceSearch.ts new file mode 100644 index 0000000000..a14db019da --- /dev/null +++ b/apps/web/src/threadReferenceSearch.ts @@ -0,0 +1,53 @@ +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import { + compareRankedSearchResults, + normalizeSearchQuery, + scoreQueryMatch, + type RankedSearchResult, +} from "@t3tools/shared/searchRanking"; + +const DEFAULT_THREAD_REFERENCE_LIMIT = 20; + +function scoreThread(thread: EnvironmentThreadShell, query: string): number | null { + const fields = [thread.title, thread.branch ?? "", thread.id]; + let best: number | null = null; + for (const field of fields) { + const score = scoreQueryMatch({ + value: field.toLowerCase(), + query, + exactBase: 0, + prefixBase: 10, + boundaryBase: 30, + includesBase: 50, + fuzzyBase: 100, + }); + if (score !== null && (best === null || score < best)) { + best = score; + } + } + return best; +} + +export function searchThreadReferences( + threads: ReadonlyArray, + queryInput: string, + limit = DEFAULT_THREAD_REFERENCE_LIMIT, +): EnvironmentThreadShell[] { + const query = normalizeSearchQuery(queryInput, { trimLeadingPattern: /^#/ }); + if (!query) { + return threads + .toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)) + .slice(0, limit); + } + + const ranked: RankedSearchResult[] = []; + for (const thread of threads) { + const score = scoreThread(thread, query); + if (score === null) continue; + ranked.push({ item: thread, score, tieBreaker: `${thread.title}:${thread.id}` }); + } + return ranked + .sort(compareRankedSearchResults) + .slice(0, limit) + .map(({ item }) => item); +} diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 43270efdec..4a86bab27c 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -25,4 +25,5 @@ export * from "./assets.ts"; export * from "./review.ts"; export * from "./preview.ts"; export * from "./previewAutomation.ts"; +export * from "./threadReference.ts"; export * from "./rpc.ts"; diff --git a/packages/contracts/src/threadReference.ts b/packages/contracts/src/threadReference.ts new file mode 100644 index 0000000000..3658e0027d --- /dev/null +++ b/packages/contracts/src/threadReference.ts @@ -0,0 +1,94 @@ +import * as Schema from "effect/Schema"; + +import { ChatAttachment, OrchestrationMessageRole } from "./orchestration.ts"; +import { + IsoDateTime, + MessageId, + NonNegativeInt, + ProjectId, + ThreadId, + TrimmedNonEmptyString, +} from "./baseSchemas.ts"; + +export const THREAD_REFERENCE_DEFAULT_MAX_CHARS = 40_000; +export const THREAD_REFERENCE_MAX_CHARS = 80_000; + +export const ThreadReferenceCursor = Schema.String.check( + Schema.isPattern(/^\d+:\d+$/, { + description: "Opaque transcript cursor returned by a previous thread_read call.", + }), +); +export type ThreadReferenceCursor = typeof ThreadReferenceCursor.Type; + +export const ThreadReferenceReadInput = Schema.Struct({ + threadId: ThreadId.annotate({ + description: "Thread id from a t3-thread reference in the user's message.", + }), + cursor: Schema.optional(ThreadReferenceCursor).annotate({ + description: "nextCursor from the previous page. Omit for the first page.", + }), + maxChars: Schema.optional( + Schema.Int.check(Schema.isGreaterThanOrEqualTo(1_000)) + .check(Schema.isLessThanOrEqualTo(THREAD_REFERENCE_MAX_CHARS)) + .annotate({ + description: `Maximum message-text characters to return. Defaults to ${THREAD_REFERENCE_DEFAULT_MAX_CHARS}; maximum ${THREAD_REFERENCE_MAX_CHARS}.`, + }), + ), +}); +export type ThreadReferenceReadInput = typeof ThreadReferenceReadInput.Type; + +export const ThreadReferenceTranscriptMessage = Schema.Struct({ + id: MessageId, + role: OrchestrationMessageRole, + text: Schema.String, + textStart: NonNegativeInt, + textEnd: NonNegativeInt, + textComplete: Schema.Boolean, + attachments: Schema.Array(ChatAttachment), + createdAt: IsoDateTime, +}); +export type ThreadReferenceTranscriptMessage = typeof ThreadReferenceTranscriptMessage.Type; + +export const ThreadReferenceReadResult = Schema.Struct({ + threadId: ThreadId, + projectId: ProjectId, + title: TrimmedNonEmptyString, + messages: Schema.Array(ThreadReferenceTranscriptMessage), + totalMessages: NonNegativeInt, + nextCursor: Schema.NullOr(ThreadReferenceCursor), +}); +export type ThreadReferenceReadResult = typeof ThreadReferenceReadResult.Type; + +export class ThreadReferenceNotFoundError extends Schema.TaggedErrorClass()( + "ThreadReferenceNotFoundError", + { threadId: ThreadId }, +) { + override get message(): string { + return `Referenced thread '${this.threadId}' was not found.`; + } +} + +export class ThreadReferenceInvalidCursorError extends Schema.TaggedErrorClass()( + "ThreadReferenceInvalidCursorError", + { threadId: ThreadId, cursor: Schema.String }, +) { + override get message(): string { + return `Cursor '${this.cursor}' is invalid for referenced thread '${this.threadId}'.`; + } +} + +export class ThreadReferenceUnavailableError extends Schema.TaggedErrorClass()( + "ThreadReferenceUnavailableError", + { threadId: ThreadId }, +) { + override get message(): string { + return `Referenced thread '${this.threadId}' could not be read.`; + } +} + +export const ThreadReferenceReadError = Schema.Union([ + ThreadReferenceNotFoundError, + ThreadReferenceInvalidCursorError, + ThreadReferenceUnavailableError, +]); +export type ThreadReferenceReadError = typeof ThreadReferenceReadError.Type; diff --git a/packages/shared/src/composerInlineTokens.test.ts b/packages/shared/src/composerInlineTokens.test.ts index f99d0b6654..e6804a132d 100644 --- a/packages/shared/src/composerInlineTokens.test.ts +++ b/packages/shared/src/composerInlineTokens.test.ts @@ -3,8 +3,9 @@ import { describe, expect, it } from "vite-plus/test"; import { collectComposerInlineTokens } from "./composerInlineTokens.ts"; describe("collectComposerInlineTokens", () => { - it("collects file links, mentions, and skills with source ranges", () => { - const text = "Use $ui and inspect [Chat.tsx](src/Chat.tsx) with @AGENTS.md please"; + it("collects file links, mentions, skills, and thread references with source ranges", () => { + const text = + "Use $ui and inspect [Chat.tsx](src/Chat.tsx) with @AGENTS.md then [Prior chat](t3-thread:///env-1/thread-2) please"; expect(collectComposerInlineTokens(text)).toEqual([ { @@ -28,6 +29,16 @@ describe("collectComposerInlineTokens", () => { start: 50, end: 60, }, + { + type: "thread", + environmentId: "env-1", + threadId: "thread-2", + title: "Prior chat", + value: "Prior chat", + source: "[Prior chat](t3-thread:///env-1/thread-2)", + start: 66, + end: 107, + }, ]); }); @@ -81,4 +92,8 @@ describe("collectComposerInlineTokens", () => { it("ignores normal web links", () => { expect(collectComposerInlineTokens("Read [docs](https://example.com) first")).toEqual([]); }); + + it("ignores malformed thread links", () => { + expect(collectComposerInlineTokens("Read [chat](t3-thread:///missing) first")).toEqual([]); + }); }); diff --git a/packages/shared/src/composerInlineTokens.ts b/packages/shared/src/composerInlineTokens.ts index aa5e67d6fc..7cd180c414 100644 --- a/packages/shared/src/composerInlineTokens.ts +++ b/packages/shared/src/composerInlineTokens.ts @@ -1,3 +1,5 @@ +import { parseComposerThreadLink } from "./composerTrigger.ts"; + export type ComposerInlineToken = | { readonly type: "mention"; @@ -12,6 +14,16 @@ export type ComposerInlineToken = readonly source: string; readonly start: number; readonly end: number; + } + | { + readonly type: "thread"; + readonly environmentId: string; + readonly threadId: string; + readonly title: string; + readonly value: string; + readonly source: string; + readonly start: number; + readonly end: number; }; export interface CollectComposerInlineTokensOptions { @@ -21,9 +33,38 @@ export interface CollectComposerInlineTokensOptions { const SKILL_TOKEN_REGEX = /(^|\s)\$([a-zA-Z][a-zA-Z0-9:_-]*)(?=\s)/g; const MENTION_TOKEN_REGEX = /(^|\s)@(?:"((?:\\.|[^"\\])*)"|([^\s@"]+))(?=\s)/g; const FILE_LINK_TOKEN_REGEX = /(^|\s)\[((?:\\.|[^\]\\])*)\]\(([^)\s]+)\)(?=\s)/g; +const THREAD_LINK_TOKEN_REGEX = /(^|\s)\[((?:\\.|[^\]\\])*)\]\((t3-thread:\/\/\/[^)\s]+)\)(?=\s)/g; const URI_SCHEME_REGEX = /^[A-Za-z][A-Za-z0-9+.-]*:/; const WINDOWS_DRIVE_PATH_REGEX = /^[A-Za-z]:[\\/]/; +function collectThreadTokens(text: string): ComposerInlineToken[] { + const matches: ComposerInlineToken[] = []; + + for (const match of text.matchAll(THREAD_LINK_TOKEN_REGEX)) { + const fullMatch = match[0]; + const prefix = match[1] ?? ""; + const title = (match[2] ?? "").replace(/\\(.)/g, "$1"); + const destination = match[3] ?? ""; + const reference = parseComposerThreadLink(destination); + if (reference && title) { + const start = (match.index ?? 0) + prefix.length; + const end = start + fullMatch.length - prefix.length; + matches.push({ + type: "thread", + environmentId: reference.environmentId, + threadId: reference.threadId, + title, + value: title, + source: text.slice(start, end), + start, + end, + }); + } + } + + return matches; +} + function collectMentionTokens(text: string): ComposerInlineToken[] { const matches: ComposerInlineToken[] = []; @@ -81,7 +122,7 @@ export function collectComposerInlineTokens( text: string, options: CollectComposerInlineTokensOptions = {}, ): ReadonlyArray { - const matches = collectMentionTokens(text); + const matches = [...collectMentionTokens(text), ...collectThreadTokens(text)]; for (const match of text.matchAll(SKILL_TOKEN_REGEX)) { const fullMatch = match[0]; diff --git a/packages/shared/src/composerTrigger.ts b/packages/shared/src/composerTrigger.ts index dcbdc78493..fe9f6ef1b3 100644 --- a/packages/shared/src/composerTrigger.ts +++ b/packages/shared/src/composerTrigger.ts @@ -1,4 +1,4 @@ -export type ComposerTriggerKind = "path" | "slash-command" | "slash-model" | "skill"; +export type ComposerTriggerKind = "path" | "slash-command" | "slash-model" | "skill" | "thread"; export type ComposerSlashCommand = "model" | "plan" | "default"; export interface ComposerTrigger { @@ -35,6 +35,42 @@ function encodeMarkdownLinkDestination(path: string): string { .replaceAll("\\", "%5C"); } +export interface ComposerThreadReference { + readonly environmentId: string; + readonly threadId: string; + readonly title: string; +} + +export const COMPOSER_THREAD_REFERENCE_SCHEME = "t3-thread:"; + +export function parseComposerThreadLink( + destination: string, +): Pick | null { + try { + const url = new URL(destination); + const segments = url.pathname.split("/").filter(Boolean).map(decodeURIComponent); + const [environmentId, threadId] = segments; + if ( + url.protocol !== COMPOSER_THREAD_REFERENCE_SCHEME || + !environmentId || + !threadId || + segments.length !== 2 + ) { + return null; + } + return { environmentId, threadId }; + } catch { + return null; + } +} + +export function serializeComposerThreadLink(reference: ComposerThreadReference): string { + const label = escapeMarkdownLinkLabel(reference.title); + const environmentId = encodeURIComponent(reference.environmentId); + const threadId = encodeURIComponent(reference.threadId); + return `[${label}](${COMPOSER_THREAD_REFERENCE_SCHEME}///${environmentId}/${threadId})`; +} + export function serializeComposerFileLink(path: string): string { const label = escapeMarkdownLinkLabel(composerFileLinkBasename(path)); return `[${label}](${encodeMarkdownLinkDestination(path)})`; @@ -112,6 +148,14 @@ export function detectComposerTrigger( rangeEnd: cursor, }; } + if (token.startsWith("#")) { + return { + kind: "thread", + query: token.slice(1), + rangeStart: tokenStart, + rangeEnd: cursor, + }; + } if (!token.startsWith("@")) { return null; }