Skip to content

Commit adc20b3

Browse files
fix(server,web,mobile): agents get the thread link format where they need it
In a real run the agent invented `t3://thread/<url-encoded id>`, which rendered as a dead link. The thread tools now state the exact format, and say not to URL-encode the id. Clients also accept a percent-encoded id when the id as written names no thread, since agents encode anyway. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 98a70c3 commit adc20b3

6 files changed

Lines changed: 55 additions & 13 deletions

File tree

‎apps/server/src/mcp/toolkits/orchestrator/tools.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ export const CreateThreadsTool = Tool.make("create_threads", {
178178

179179
const ThreadListTool = Tool.make("t3_thread_list", {
180180
description:
181-
"List T3 threads in a project, newest first. Omit projectId for the calling thread's project. Filter by durable run status, title, or settled state (settled=true lists threads the user or auto-settlement moved out of the active list), or snoozed state, and paginate with the returned cursor. A snoozed thread wakes early when it asks for something, fails, or completes.",
181+
"List T3 threads in a project, newest first. Omit projectId for the calling thread's project. Filter by durable run status, title, or settled state (settled=true lists threads the user or auto-settlement moved out of the active list), or snoozed state, and paginate with the returned cursor. A snoozed thread wakes early when it asks for something, fails, or completes. To link a thread for the user, write `[title](t3-thread://v1/<threadId>)` with the threadId exactly as returned, not URL-encoded; T3 Code shows the thread's current title.",
182182
parameters: OrchestratorMcpThreadListInput,
183183
success: OrchestratorMcpThreadListResult,
184184
failure: OrchestratorMcpFailure,
@@ -192,7 +192,7 @@ const ThreadListTool = Tool.make("t3_thread_list", {
192192

193193
const ThreadReadTool = Tool.make("t3_thread_read", {
194194
description:
195-
"Read durable state and a paginated timeline from any T3 thread in this environment. The default messages view returns user messages, assistant messages, and proposed plans; activity returns all summarized timeline items. Reading an untruncated terminal assistant result from this parent thread's direct app-owned child acknowledges that child's automatic completion delivery. Continue with afterPosition=nextPosition. Recover long item text with itemId and textOffset=nextTextOffset until nextTextOffset is null; offsets count UTF-16 code units. The thread also reports its snooze state.",
195+
"Read durable state and a paginated timeline from any T3 thread in this environment. The default messages view returns user messages, assistant messages, and proposed plans; activity returns all summarized timeline items. Reading an untruncated terminal assistant result from this parent thread's direct app-owned child acknowledges that child's automatic completion delivery. Continue with afterPosition=nextPosition. Recover long item text with itemId and textOffset=nextTextOffset until nextTextOffset is null; offsets count UTF-16 code units. The thread also reports its snooze state. To link a thread for the user, write `[title](t3-thread://v1/<threadId>)` with the threadId exactly as returned, not URL-encoded; T3 Code shows the thread's current title.",
196196
parameters: OrchestratorMcpThreadReadInput,
197197
success: OrchestratorMcpThreadReadResult,
198198
failure: OrchestratorMcpFailure,

‎apps/server/src/mcp/toolkits/project/tools.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ const ProjectCloneTool = Tool.make("t3_project_clone", {
103103
const ThreadLaunchTool = Tool.make("t3_thread_launch", {
104104
...shared,
105105
description:
106-
'Create an ordinary TOP-LEVEL thread with an explicit workspace binding before its agent starts. Use this when the user requests independent work, a new thread, or a PR stack in its own worktree; use delegate_task for child subagents. Set workspaceStrategy to {type:"worktree",baseRef:"parent-branch",branch:"new-branch",startFromOrigin:false} for a new worktree based on local commits, or {type:"existing_worktree",worktreePath:"/absolute/path",branch:"existing-branch"} to use an existing checkout. For upstream commits, set startFromOrigin:true. Omitted workspaceStrategy means the project root, NOT the caller\'s worktree. Omit projectId/modelSelection/modes to inherit those settings from the calling thread; a caller outside a T3 thread must pass projectId and gets the project\'s default model. Set scratch:true instead of projectId for a thread without a project: it runs in a fresh folder of its own, outside any repository. Put the task in message. Do not ask the agent to create its own worktree via shell: that does not update the thread binding. Each call creates a new launch with no retry key; retain threadId and use t3_thread_read/t3_thread_wait to follow preparation. After errors or lost responses, inspect t3_thread_list before retrying. Attachments must be pending uploads. The new thread may not run with broader runtime or interaction modes than the caller: the calling T3 thread\'s own modes, or the permission mode an outside agent was approved with.',
106+
'Create an ordinary TOP-LEVEL thread with an explicit workspace binding before its agent starts. Use this when the user requests independent work, a new thread, or a PR stack in its own worktree; use delegate_task for child subagents. Set workspaceStrategy to {type:"worktree",baseRef:"parent-branch",branch:"new-branch",startFromOrigin:false} for a new worktree based on local commits, or {type:"existing_worktree",worktreePath:"/absolute/path",branch:"existing-branch"} to use an existing checkout. For upstream commits, set startFromOrigin:true. Omitted workspaceStrategy means the project root, NOT the caller\'s worktree. Omit projectId/modelSelection/modes to inherit those settings from the calling thread; a caller outside a T3 thread must pass projectId and gets the project\'s default model. Set scratch:true instead of projectId for a thread without a project: it runs in a fresh folder of its own, outside any repository. Put the task in message. Do not ask the agent to create its own worktree via shell: that does not update the thread binding. Each call creates a new launch with no retry key; retain threadId and use t3_thread_read/t3_thread_wait to follow preparation. To link a thread for the user, write `[title](t3-thread://v1/<threadId>)` with the threadId exactly as returned, not URL-encoded; T3 Code shows the thread\'s current title. After errors or lost responses, inspect t3_thread_list before retrying. Attachments must be pending uploads. The new thread may not run with broader runtime or interaction modes than the caller: the calling T3 thread\'s own modes, or the permission mode an outside agent was approved with.',
107107
parameters: Schema.Struct({
108108
projectId: Schema.optional(ProjectId),
109109
scratch: Schema.optional(

‎apps/server/src/provider/T3OrchestrationInstructions.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ The \`t3-code\` MCP server provides app-owned orchestration. Treat these concept
1111
- For every T3 delegated review round, call \`delegate_task\` again. Include the original brief, prior findings, responses, and unresolved objections in each new task prompt. Track each round by its own \`taskId\`. Use a distinct \`clientRequestId\` per round, stable across retries of that round. Do not use \`t3_thread_send\` on \`childThreadId\` to continue a delegated review.
1212
- \`schedule_task\` creates persistent recurring work in the app scheduler. Pass \`schedule\` as a structured object, never as JSON text: \`{"type":"interval","everyMs":3600000}\` for an interval, or \`{"type":"fixed_time","timeOfDay":"09:00","weekdays":[1,2,3,4,5]}\` for a wall-clock schedule, or \`{"type":"webhook"}\` to run on each request to the returned \`webhookUrl\` (the run sees the request only through \`{{body.path}}\`-style placeholders in the prompt). By default runs return to the current thread, which suits orchestrating: each trigger arrives here and you delegate or dedupe; set \`bindToCurrentThread=false\` only when the user wants a fresh thread for every run. After scheduling a timer, report the returned cadence and next run time; for a webhook, report its \`webhookUrl\`, or say T3 Connect remote access is needed if it is missing.
1313
- When you need a secret from the user (a token, API key, or webhook signing secret), call \`request_secret\` so they enter it privately, then pass the returned \`secretRef\` to the tool that needs it, e.g. \`signature.secretRef\` on a webhook task for a sender that signs requests such as GitHub. A \`secretRef\` works once. Never ask for a secret in chat, never invent one, and never repeat one.
14-
- To mention another thread to the user, link it as \`[title](t3-thread://v1/<threadId>)\` with its exact \`threadId\`. T3 Code opens the thread in the app and shows its current title.
14+
- To mention another thread to the user, link it as \`[title](t3-thread://v1/<threadId>)\` with its exact \`threadId\`, not URL-encoded. T3 Code opens the thread in the app and shows its current title.
1515
1616
### Choose the workspace before starting a new thread
1717

‎apps/web/src/components/chat/MarkdownThreadLink.tsx‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
22
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
3-
import { formatThreadLink } from "@t3tools/shared/threadLinks";
3+
import { formatThreadLink, percentDecodedThreadLinkId } from "@t3tools/shared/threadLinks";
44
import { Link } from "@tanstack/react-router";
55
import { MessageSquareTextIcon } from "lucide-react";
66

@@ -18,17 +18,23 @@ export function MarkdownThreadLink(props: {
1818
readonly threadId: ThreadId;
1919
readonly label: string;
2020
}) {
21-
const thread = useThreadShell(scopeThreadRef(props.environmentId, props.threadId));
21+
const decodedId = percentDecodedThreadLinkId(props.threadId);
22+
const written = useThreadShell(scopeThreadRef(props.environmentId, props.threadId));
23+
const decoded = useThreadShell(
24+
written === null && decodedId !== null ? scopeThreadRef(props.environmentId, decodedId) : null,
25+
);
26+
const thread = written ?? decoded;
27+
const threadId = thread?.id ?? props.threadId;
2228
const project = useProject(
2329
thread === null ? null : scopeProjectRef(props.environmentId, thread.projectId),
2430
);
2531
const title = thread?.title.trim() || props.label;
2632
return (
2733
<Link
2834
to="/$environmentId/$threadId"
29-
params={{ environmentId: props.environmentId, threadId: props.threadId }}
35+
params={{ environmentId: props.environmentId, threadId }}
3036
title={project?.title}
31-
data-markdown-copy={formatThreadLink(props.threadId, title)}
37+
data-markdown-copy={formatThreadLink(threadId, title)}
3238
>
3339
<span
3440
className="ms-[0.25em] me-[0.2em] inline-flex size-[14px] [vertical-align:-0.125em]"

‎packages/shared/src/threadLinks.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,21 @@ describe("thread links", () => {
1616
expect(parseThreadLinkHref("t3-thread://v1/ ")).toBeNull();
1717
});
1818

19+
it("resolves a percent-encoded id when the id as written names no thread", () => {
20+
const titles = new Map([
21+
["thread:project:1", "Decoded"],
22+
["provider%3A1", "Literal escape"],
23+
]);
24+
expect(
25+
relabelThreadLinks(
26+
"[a](t3-thread://v1/thread%3Aproject%3A1) [b](t3-thread://v1/provider%3A1)",
27+
(threadId) => titles.get(threadId),
28+
),
29+
).toBe(
30+
"[Decoded](t3-thread://v1/thread:project:1) [Literal escape](t3-thread://v1/provider%3A1)",
31+
);
32+
});
33+
1934
it("leaves links inside code spans and fences as written", () => {
2035
const markdown = [
2136
"Live [old](t3-thread://v1/t1), literal `[old](t3-thread://v1/t1)`.",

‎packages/shared/src/threadLinks.ts‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,25 @@ const THREAD_LINK_OUTSIDE_CODE =
1515

1616
const decodeThreadId = Schema.decodeUnknownOption(ThreadId);
1717

18-
/** The id is taken verbatim: thread ids can hold percent escapes of their own. */
18+
/** The id as written. Thread ids can hold percent escapes of their own, so it is not decoded. */
1919
export function parseThreadLinkHref(href: string): ThreadId | null {
2020
if (!href.startsWith(THREAD_LINK_HREF_PREFIX)) return null;
2121
return Option.getOrNull(decodeThreadId(href.slice(THREAD_LINK_HREF_PREFIX.length)));
2222
}
2323

24+
/**
25+
* Agents often percent-encode the id anyway. When the id as written names no thread, clients try
26+
* this decoded form. Null when decoding changes nothing or fails.
27+
*/
28+
export function percentDecodedThreadLinkId(threadId: ThreadId): ThreadId | null {
29+
try {
30+
const decoded = decodeURIComponent(threadId);
31+
return decoded === threadId ? null : Option.getOrNull(decodeThreadId(decoded));
32+
} catch {
33+
return null;
34+
}
35+
}
36+
2437
/** A thread link whose label survives Markdown: no brackets, backslashes, or line breaks. */
2538
export function formatThreadLink(threadId: string, label: string): string {
2639
const cleaned = label
@@ -34,7 +47,10 @@ export function hasThreadLinks(markdown: string): boolean {
3447
return markdown.includes(`](${THREAD_LINK_HREF_PREFIX}`);
3548
}
3649

37-
/** Relabels each thread link with `title(threadId)`; a link it returns nothing for keeps its label. */
50+
/**
51+
* Relabels each thread link with `title(threadId)`, pointing it at the thread that title came from.
52+
* A link it returns nothing for keeps its label.
53+
*/
3854
export function relabelThreadLinks(
3955
markdown: string,
4056
title: (threadId: ThreadId) => string | undefined,
@@ -43,8 +59,13 @@ export function relabelThreadLinks(
4359
return markdown.replace(THREAD_LINK_OUTSIDE_CODE, (source, ...args) => {
4460
const href = (args.at(-1) as { href?: string }).href;
4561
if (href === undefined) return source;
46-
const threadId = parseThreadLinkHref(href);
47-
const label = threadId === null ? undefined : title(threadId)?.trim();
48-
return threadId !== null && label ? formatThreadLink(threadId, label) : source;
62+
const written = parseThreadLinkHref(href);
63+
if (written === null) return source;
64+
const decoded = percentDecodedThreadLinkId(written);
65+
for (const threadId of decoded === null ? [written] : [written, decoded]) {
66+
const label = title(threadId)?.trim();
67+
if (label) return formatThreadLink(threadId, label);
68+
}
69+
return source;
4970
});
5071
}

0 commit comments

Comments
 (0)