@devries-cameron20 / t3code Mirror · read-only / commits / f991781872
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 21:00 UTC

fix(server,web,mobile): messages from a linked environment name the thread that sent them (#34721)

Co-authored-by: Happy Campr <happycampr@Locals-MacBook-Pro.local> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Etan Heyman committed Nov 12, 2026 at 07:04 UTC f991781872748d16e9d4a173e8b045616c717d57
25 files changed +432 -42
apps/mobile/src/features/threads/ThreadFeed.tsx
+21 -6
@@ -246,6 +246,7 @@ import {
246 useQuietThreadShell,
247 useThreadChipIcons,
248 } from "../../state/entities";
249 +import { useEnvironmentPresentation } from "../../state/presentation";
250 import { useThreadSelection } from "../../state/use-thread-selection";
251 import { useEnvironmentQuery } from "../../state/query";
252 import { serverEnvironment } from "../../state/server";
@@ -1333,6 +1334,8 @@ function useMarkdownStyles(): MarkdownStyleSets {
1334 function AgentMessageFoldHeader(props: {
1335 readonly environmentId: EnvironmentId;
1336 readonly senderThreadId?: ThreadId;
1337 + /** A linked environment's sender title, for when this client cannot reach it. */
1338 + readonly senderTitle?: string;
1339 readonly summary: string;
1340 readonly expanded: boolean;
1341 readonly onToggle: () => void;
@@ -1341,7 +1344,7 @@ function AgentMessageFoldHeader(props: {
1344 const senderShell = useQuietThreadShell(
1345 props.senderThreadId ? scopeThreadRef(props.environmentId, props.senderThreadId) : null,
1346 );
1344 - const label = senderShell?.title.trim() || "Agent";
1347 + const label = senderShell?.title.trim() || props.senderTitle?.trim() || "Agent";
1348 return (
1349 <Pressable
1350 accessibilityRole="button"
@@ -1384,8 +1387,12 @@ function AgentMessageFoldHeader(props: {
1387 function OpenSenderThreadButton(props: {
1388 readonly environmentId: EnvironmentId;
1389 readonly senderThreadId: ThreadId;
1390 + /** In a linked environment, shown only when this client is connected to it. */
1391 + readonly linked?: boolean;
1392 }) {
1393 const openLinkedThread = useOpenLinkedThread();
1394 + const linkedEnvironment = useEnvironmentPresentation(props.linked ? props.environmentId : null);
1395 + if (props.linked && linkedEnvironment.presentation === null) return null;
1396 return (
1397 <Pressable
1398 accessibilityRole="link"
@@ -1916,6 +1923,12 @@ function renderFeedEntry(
1923 if (isUser) {
1924 const enterAnimated = isFreshTimestamp(message.createdAt);
1925 const foldRowId = presentation.attribution === "agent" ? `agent:${message.id}` : null;
1926 + // A linked environment's agent sent it from a thread there.
1927 + const senderRef =
1928 + message.linkedSender ??
1929 + (message.senderThreadId
1930 + ? scopeThreadRef(props.environmentId, message.senderThreadId)
1931 + : null);
1932 const foldExpanded = foldRowId !== null && (props.expandedWorkRows[foldRowId] ?? false);
1933 const bubbleBodyVisible = foldRowId === null || foldExpanded;
1934 const intentBadge = props.userMessageGrouping.continuesSteer
@@ -2036,8 +2049,9 @@ function renderFeedEntry(
2049 {presentation.attribution === "guest" ? <GuestBubbleTint /> : null}
2050 {foldRowId !== null ? (
2051 <AgentMessageFoldHeader
2039 - environmentId={props.environmentId}
2040 - senderThreadId={message.senderThreadId}
2052 + environmentId={senderRef?.environmentId ?? props.environmentId}
2053 + senderThreadId={senderRef?.threadId}
2054 + {...(message.linkedSender ? { senderTitle: message.linkedSender.title } : {})}
2055 summary={
2056 replaceComposerContextReferences(presentation.text, (ref) => ref.label)
2057 .split(/\r?\n/)
@@ -2144,10 +2158,11 @@ function renderFeedEntry(
2158 ) : null}
2159 {bubbleBodyVisible ? (
2160 <View className="mt-1 flex-row items-center justify-end gap-1 pr-0.5">
2147 - {foldRowId !== null && message.senderThreadId ? (
2161 + {foldRowId !== null && senderRef ? (
2162 <OpenSenderThreadButton
2149 - environmentId={props.environmentId}
2150 - senderThreadId={message.senderThreadId}
2163 + environmentId={senderRef.environmentId}
2164 + senderThreadId={senderRef.threadId}
2165 + linked={message.linkedSender !== undefined}
2166 />
2167 ) : null}
2168 {intentBadge ? (
apps/mobile/src/features/threads/ThreadQueueControl.tsx
+4 -2
@@ -70,8 +70,10 @@ function QueuedRunSender(props: {
70 }) {
71 const { attribution, scheduledTaskId } = resolveUserMessagePresentation(props.message);
72 const senderThreadId = attribution === "agent" ? props.message.senderThreadId : undefined;
73 + // A linked environment's agent sent it from a thread there.
74 + const linkedSender = attribution === "agent" ? props.message.linkedSender : undefined;
75 const senderShell = useQuietThreadShell(
74 - senderThreadId ? scopeThreadRef(props.environmentId, senderThreadId) : null,
76 + linkedSender ?? (senderThreadId ? scopeThreadRef(props.environmentId, senderThreadId) : null),
77 );
78 const tasks = useEnvironmentQuery(
79 scheduledTaskId
@@ -88,7 +90,7 @@ function QueuedRunSender(props: {
90 : attribution === "agent"
91 ? {
92 icon: "bubble.left.and.bubble.right" as const,
91 - label: senderShell?.title.trim() || "Agent",
93 + label: senderShell?.title.trim() || linkedSender?.title.trim() || "Agent",
94 }
95 : attribution === "t3code"
96 ? { icon: null, label: "Sent by T3 Code" }
apps/mobile/src/lib/filePreview.test.ts
+3
@@ -182,6 +182,9 @@ vi.mock("../state/entities", () => ({
182 vi.mock("../state/use-thread-selection", () => ({
183 useThreadSelection: () => ({ selectedThread: null }),
184 }));
185 +vi.mock("../state/presentation", () => ({
186 + useEnvironmentPresentation: () => ({ isReady: true, presentation: null }),
187 +}));
188 vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() }));
189 vi.mock("../state/use-atom-command", () => ({}));
190 vi.mock("../state/v2-item-support", () => ({}));
apps/mobile/src/lib/threadActivity.ts
+2
@@ -140,6 +140,7 @@ export interface ThreadFeedMessage {
140 readonly creationSource?: OrchestrationV2CreationSource;
141 readonly scheduledTaskId?: ScheduledTaskId;
142 readonly senderThreadId?: ThreadId;
143 + readonly linkedSender?: import("@t3tools/contracts").OrchestrationV2LinkedSender;
144 readonly idleCompaction?: import("@t3tools/contracts").OrchestrationV2IdleCompaction;
145 readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
146 readonly sourceThreadId: ThreadId;
@@ -2387,6 +2388,7 @@ export function buildThreadFeed(
2388 creationSource: item.creationSource,
2389 ...(item.scheduledTaskId ? { scheduledTaskId: item.scheduledTaskId } : {}),
2390 ...(item.senderThreadId ? { senderThreadId: item.senderThreadId } : {}),
2391 + ...(item.linkedSender ? { linkedSender: item.linkedSender } : {}),
2392 ...(item.idleCompaction ? { idleCompaction: item.idleCompaction } : {}),
2393 }
2394 : {}),
apps/server/src/mcp/McpHttpServer.ts
+30 -1
@@ -21,6 +21,7 @@ import {
21 ProviderInteractionMode,
22 type RunId,
23 RuntimeMode,
24 + OrchestrationV2LinkedSender,
25 ThreadId,
26 } from "@t3tools/contracts";
27
@@ -190,6 +191,34 @@ const withModeLimit = (
191 : { ...invocation, client: { ...invocation.client, narrowedTo: limit.value } };
192 };
193
194 +const decodeSenderThread = Schema.decodeUnknownOption(OrchestrationV2LinkedSender);
195 +
196 +/** Records the thread a linked environment calls for; a malformed header only loses the name. */
197 +const withSenderThread = (
198 + invocation: McpInvocationContext.McpInvocationScope,
199 + request: HttpServerRequest.HttpServerRequest,
200 +): McpInvocationContext.McpInvocationScope => {
201 + const header = request.headers[McpInvocationContext.SENDER_THREAD_HEADER];
202 + if (header === undefined || invocation.client?.linked !== true) return invocation;
203 + const [environmentId, threadId, title, ...rest] = header.trim().split("/");
204 + if (environmentId === undefined || threadId === undefined || title === undefined)
205 + return invocation;
206 + if (rest.length > 0) return invocation;
207 + let decoded: Option.Option<OrchestrationV2LinkedSender>;
208 + try {
209 + decoded = decodeSenderThread({
210 + environmentId: decodeURIComponent(environmentId),
211 + threadId: decodeURIComponent(threadId),
212 + title: decodeURIComponent(title),
213 + });
214 + } catch {
215 + return invocation;
216 + }
217 + return Option.isNone(decoded)
218 + ? invocation
219 + : { ...invocation, client: { ...invocation.client, senderThread: decoded.value } };
220 +};
221 +
222 // The Linked environments beta is off here: links wait until it is on again.
223 const linkedEnvironmentsOff = HttpServerResponse.jsonUnsafe(
224 {
@@ -235,7 +264,7 @@ const makeMcpAuthMiddleware = Effect.gen(function* () {
264 offerOAuth: Option.isSome(clients) && !looksLikeProviderToken(token),
265 });
266 }
238 - const asked = withModeLimit(invocation, request);
267 + const asked = withModeLimit(withSenderThread(invocation, request), request);
268 if (asked === undefined) return invalidModeLimit;
269 const limited = McpInvocationContext.withRuntimeModeCeiling(asked, runtimeModeCeiling);
270 const linkedEnvironments = yield* linksEnabled;
apps/server/src/mcp/McpInvocationContext.ts
+10
@@ -6,6 +6,7 @@ import {
6 PreviewAutomationUnavailableError,
7 type ProviderInstanceId,
8 type ProviderInteractionMode,
9 + type OrchestrationV2LinkedSender,
10 type RuntimeMode,
11 type ThreadId,
12 } from "@t3tools/contracts";
@@ -45,6 +46,8 @@ export interface McpClientCaller {
46 * another environment passing on the limits of the agent it calls for.
47 */
48 readonly narrowedTo?: ClientModes | undefined;
49 + /** A linked environment's thread this request is made for (`T3-Sender-Thread`). */
50 + readonly senderThread?: OrchestrationV2LinkedSender | undefined;
51 /** An outside client's thread links go through this hosted app, as Copy thread's do. */
52 readonly hostedAppUrl?: string | undefined;
53 }
@@ -57,6 +60,13 @@ export interface McpClientCaller {
60 */
61 export const MODE_LIMIT_HEADER = "t3-mode-limit";
62
63 +/**
64 + * `T3-Sender-Thread: <environmentId>/<threadId>/<title>`, each URI-encoded: the
65 + * thread another environment makes a request for, so what it sends here can name
66 + * it. Read only from a linked client.
67 + */
68 +export const SENDER_THREAD_HEADER = "t3-sender-thread";
69 +
70 export interface ClientModes {
71 readonly runtimeMode: RuntimeMode;
72 readonly interactionMode: ProviderInteractionMode;
apps/server/src/mcp/OrchestratorMcpService.test.ts
+49
@@ -3813,6 +3813,55 @@ describe("OrchestratorMcpService thread lookup", () => {
3813 }),
3814 );
3815
3816 + it.effect("records the linked environment's thread that sent a message", () =>
3817 + Effect.gen(function* () {
3818 + const target = liveThreadShell(ThreadId.make("thread:target"));
3819 + const sender = {
3820 + environmentId: EnvironmentId.make("environment:a"),
3821 + threadId: ThreadId.make("thread:orc"),
3822 + title: "orc lead",
3823 + };
3824 + const linked = (senderThread?: typeof sender): McpInvocationScope => ({
3825 + ...client,
3826 + client: {
3827 + sessionId: "link-a",
3828 + label: "A",
3829 + access: "full-access",
3830 + linked: true,
3831 + ...(senderThread === undefined ? {} : { senderThread }),
3832 + },
3833 + });
3834 + const sendAs = (scope: McpInvocationScope) =>
3835 + Effect.gen(function* () {
3836 + const inputs: Array<ThreadManagementService.ThreadManagementSendInput> = [];
3837 + const sent = yield* Ref.make(0);
3838 + yield* Effect.gen(function* () {
3839 + const mcp = yield* OrchestratorMcpService.OrchestratorMcpService;
3840 + yield* mcp.sendToThread(scope, { threadId: target.id, message: "hello" });
3841 + }).pipe(
3842 + Effect.provide(
3843 + service([target], sent, {
3844 + getProjectThreadRecords: () => Effect.succeed(idleThreadProjection(target)),
3845 + sendToThread: (input) => {
3846 + inputs.push(input);
3847 + return Effect.succeed({
3848 + run: { id: RunId.make("run:sent"), status: "running" },
3849 + delivery: "started",
3850 + } as never);
3851 + },
3852 + }),
3853 + ),
3854 + );
3855 + return inputs[0];
3856 + });
3857 +
3858 + const fromLink = yield* sendAs(linked(sender));
3859 + assert.deepStrictEqual(fromLink?.linkedSender, sender);
3860 + assert.isUndefined(fromLink?.senderThreadId);
3861 + assert.isUndefined((yield* sendAs(linked()))?.linkedSender);
3862 + }),
3863 + );
3864 +
3865 it.effect("refuses waiting without orchestration capability before reading the target", () =>
3866 Effect.gen(function* () {
3867 const sent = yield* Ref.make(0);
apps/server/src/mcp/OrchestratorMcpService.ts
+4
@@ -3147,6 +3147,10 @@ const make = Effect.gen(function* () {
3147 }),
3148 threadId: input.threadId,
3149 ...(parent === undefined ? {} : { senderThreadId: parent.thread.id }),
3150 + // A linked environment's agent has no thread here; the link names it.
3151 + ...(parent === undefined && scope.client?.senderThread !== undefined
3152 + ? { linkedSender: scope.client.senderThread }
3153 + : {}),
3154 messageId,
3155 text: input.message,
3156 attachments: [],
apps/server/src/orchestration-v2/EffectWorker.ts
+3
@@ -346,6 +346,9 @@ export const layerExecutor: Layer.Layer<
346 ...(message.senderThreadId === undefined
347 ? {}
348 : { senderThreadId: message.senderThreadId }),
349 + ...(message.linkedSender === undefined
350 + ? {}
351 + : { linkedSender: message.linkedSender }),
352 })
353 .pipe(
354 // A disabled instance cannot retry this completed turn; its result stands.
apps/server/src/orchestration-v2/Orchestrator.ts
+15
@@ -2643,6 +2643,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2643 ...(queuedMessage.senderThreadId === undefined
2644 ? {}
2645 : { senderThreadId: queuedMessage.senderThreadId }),
2646 + ...(queuedMessage.linkedSender === undefined
2647 + ? {}
2648 + : { linkedSender: queuedMessage.linkedSender }),
2649 ...(queuedMessage.idleCompaction === undefined
2650 ? {}
2651 : { idleCompaction: queuedMessage.idleCompaction }),
@@ -5460,6 +5463,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
5463 readonly creationSource: OrchestrationV2ConversationMessage["creationSource"];
5464 readonly scheduledTaskId?: OrchestrationV2ConversationMessage["scheduledTaskId"];
5465 readonly senderThreadId?: OrchestrationV2ConversationMessage["senderThreadId"];
5466 + readonly linkedSender?: OrchestrationV2ConversationMessage["linkedSender"];
5467 readonly idleCompaction?: OrchestrationV2ConversationMessage["idleCompaction"];
5468 readonly delegatedCompletion?: OrchestrationV2ConversationMessage["delegatedCompletion"];
5469 readonly notification?: OrchestrationV2ConversationMessage["notification"];
@@ -5604,6 +5608,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
5608 ? {}
5609 : { scheduledTaskId: input.scheduledTaskId }),
5610 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
5611 + ...(input.linkedSender === undefined ? {} : { linkedSender: input.linkedSender }),
5612 ...(input.idleCompaction === undefined ? {} : { idleCompaction: input.idleCompaction }),
5613 id: input.messageId,
5614 threadId: input.command.threadId,
@@ -5624,6 +5629,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
5629 ? {}
5630 : { scheduledTaskId: input.scheduledTaskId }),
5631 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
5632 + ...(input.linkedSender === undefined ? {} : { linkedSender: input.linkedSender }),
5633 ...(input.idleCompaction === undefined ? {} : { idleCompaction: input.idleCompaction }),
5634 id: idAllocator.derive.userTurnItem({ messageId: input.messageId }),
5635 threadId: input.command.threadId,
@@ -6786,6 +6792,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6792 ? {}
6793 : { scheduledTaskId: command.scheduledTaskId }),
6794 ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
6795 + ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }),
6796 ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
6797 forceRestart: dispatchMode.type === "restart_active",
6798 });
@@ -7076,6 +7083,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7083 ? {}
7084 : { scheduledTaskId: command.scheduledTaskId }),
7085 ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
7086 + ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }),
7087 ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
7088 id: command.messageId,
7089 threadId: command.threadId,
@@ -7483,6 +7491,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7491 ? {}
7492 : { scheduledTaskId: command.scheduledTaskId }),
7493 ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
7494 + ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }),
7495 ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
7496 id: command.messageId,
7497 threadId: command.threadId,
@@ -7505,6 +7514,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7514 ? {}
7515 : { scheduledTaskId: command.scheduledTaskId }),
7516 ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
7517 + ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }),
7518 ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
7519 id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
7520 threadId: command.threadId,
@@ -8268,6 +8278,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
8278 ? {}
8279 : { scheduledTaskId: command.scheduledTaskId }),
8280 ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
8281 + ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }),
8282 ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
8283 id: command.messageId,
8284 threadId: command.threadId,
@@ -8290,6 +8301,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
8301 ? {}
8302 : { scheduledTaskId: command.scheduledTaskId }),
8303 ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
8304 + ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }),
8305 ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
8306 id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
8307 threadId: command.threadId,
@@ -10765,6 +10777,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10777 ...(queuedMessage.senderThreadId === undefined
10778 ? {}
10779 : { senderThreadId: queuedMessage.senderThreadId }),
10780 + ...(queuedMessage.linkedSender === undefined
10781 + ? {}
10782 + : { linkedSender: queuedMessage.linkedSender }),
10783 ...(queuedMessage.idleCompaction === undefined
10784 ? {}
10785 : { idleCompaction: queuedMessage.idleCompaction }),
apps/server/src/orchestration-v2/ThreadManagementService.ts
+3
@@ -25,6 +25,7 @@ import {
25 type OrchestrationV2ServerCommand,
26 type OrchestrationV2ConversationMessage,
27 type OrchestrationV2CreationSource,
28 + type OrchestrationV2LinkedSender,
29 type OrchestrationV2Run,
30 type OrchestrationV2ThreadShellSnapshot,
31 type OrchestrationV2ThreadProjection,
@@ -143,6 +144,7 @@ export interface ThreadManagementSendInput {
144 readonly messageId: MessageId;
145 readonly scheduledTaskId?: ScheduledTaskId;
146 readonly senderThreadId?: ThreadId;
147 + readonly linkedSender?: OrchestrationV2LinkedSender;
148 readonly text: string;
149 readonly attachments: ReadonlyArray<ChatAttachment>;
150 readonly modelSelection?: ModelSelection;
@@ -866,6 +868,7 @@ const make = Effect.gen(function* () {
868 messageId: input.messageId,
869 ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }),
870 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
871 + ...(input.linkedSender === undefined ? {} : { linkedSender: input.linkedSender }),
872 text: input.text,
873 attachments: input.attachments,
874 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+62
@@ -14,6 +14,7 @@ import {
14 CheckpointRef,
15 CommandId,
16 ContextTransferId,
17 + EnvironmentId,
18 EventId,
19 MessageId,
20 NodeId,
@@ -5631,6 +5632,67 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
5632 }),
5633 );
5634
5635 + it.effect("keeps a linked environment's sender on started and queued messages", () =>
5636 + Effect.gen(function* () {
5637 + const orchestrator = yield* Orchestrator.OrchestratorV2;
5638 + const threadId = ThreadId.make("runtime-layer-linked-sender-thread");
5639 + const linkedSender = {
5640 + environmentId: EnvironmentId.make("environment-linked"),
5641 + threadId: ThreadId.make("linked-sending-agent"),
5642 + title: "Linked sending agent",
5643 + };
5644 + yield* orchestrator.dispatch({
5645 + type: "thread.create",
5646 + createdBy: "user",
5647 + creationSource: "web",
5648 + commandId: CommandId.make("runtime-layer-linked-sender-create"),
5649 + threadId,
5650 + projectId: ProjectId.make("runtime-layer-linked-sender-project"),
5651 + title: "Linked sender",
5652 + modelSelection,
5653 + runtimeMode: "full-access",
5654 + interactionMode: "default",
5655 + branch: null,
5656 + worktreePath: "/tmp/runtime-layer-linked-sender",
5657 + });
5658 + for (const [suffix, type] of [
5659 + ["started", "start_immediately"],
5660 + ["queued", "queue_after_active"],
5661 + ] as const) {
5662 + yield* orchestrator.dispatch({
5663 + type: "message.dispatch",
5664 + createdBy: "agent",
5665 + creationSource: "mcp",
5666 + linkedSender,
5667 + commandId: CommandId.make(`runtime-layer-linked-sender-${suffix}`),
5668 + threadId,
5669 + messageId: MessageId.make(`runtime-layer-linked-sender-${suffix}`),
5670 + text: `Linked ${suffix} message`,
5671 + attachments: [],
5672 + modelSelection,
5673 + dispatchMode: { type },
5674 + });
5675 + }
5676 +
5677 + const projection = yield* orchestrator.getThreadProjection(threadId);
5678 + for (const suffix of ["started", "queued"]) {
5679 + const message = projection.messages.find(
5680 + (candidate) => candidate.id === `runtime-layer-linked-sender-${suffix}`,
5681 + );
5682 + assert.deepStrictEqual(message?.linkedSender, linkedSender);
5683 + assert.isUndefined(message?.senderThreadId);
5684 + }
5685 + const startedItem = projection.turnItems.find(
5686 + (item) =>
5687 + item.type === "user_message" && item.messageId === "runtime-layer-linked-sender-started",
5688 + );
5689 + assert.deepStrictEqual(
5690 + startedItem?.type === "user_message" ? startedItem.linkedSender : undefined,
5691 + linkedSender,
5692 + );
5693 + }),
5694 + );
5695 +
5696 it.effect("settles a thread its own agent settled once the turn completes", () =>
5697 Effect.gen(function* () {
5698 const orchestrator = yield* Orchestrator.OrchestratorV2;
apps/server/src/peer/PeerForwarding.test.ts
+6
@@ -416,6 +416,12 @@ it.effect("an agent here works on a linked environment's threads within its own
416 });
417 expect(sent.isError).toBe(false);
418 expect(sent.structuredContent).toMatchObject({ threadId: boxThread, delivery: "started" });
419 + // The box records which thread here sent it.
420 + expect((yield* Ref.get(seen)).sends[0]?.linkedSender).toEqual({
421 + environmentId: laptop.environmentId,
422 + threadId: "thread:laptop-full",
423 + title: "thread:laptop-full",
424 + });
425
426 // A plan-mode agent here may not steer that thread there: the box
427 // refuses it, because the call carries the agent's own modes.
apps/server/src/peer/PeerForwarding.ts
+14 -5
@@ -98,15 +98,14 @@ const make = Effect.gen(function* () {
98 const threads = yield* ThreadManagement.ThreadManagementService;
99
100 /**
101 - * The caller's own limits, which travel with every forwarded call: the peer sees only the
101 + * The caller's own limits and thread, which travel with every forwarded call: the peer sees only the
102 * link's credential, so a caller that may not control threads here is refused here. Work a
103 * link started never uses this environment's links, since the peer would see this
104 * environment's session instead of that link, and its fence could not hold.
105 */
106 - const callerLimits = (scope: Scope) =>
106 + const forwardingCaller = (scope: Scope) =>
107 readCaller().pipe(
108 Effect.tap((caller) => assertNotLinked(caller, "use this environment's links")),
109 - Effect.map((caller) => caller.limits),
109 Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
110 Effect.provideService(ThreadManagement.ThreadManagementService, threads),
111 );
@@ -131,7 +130,7 @@ const make = Effect.gen(function* () {
130 environmentId: EnvironmentId,
131 params: unknown,
132 ) {
134 - const limits = yield* callerLimits(scope);
133 + const { caller, limits } = yield* forwardingCaller(scope);
134 const encoded = (yield* Schema.encodeUnknownEffect(parameters as Schema.Encoder<unknown>)(
135 params,
136 ).pipe(Effect.mapError(unavailable))) as Record<string, unknown>;
@@ -146,11 +145,21 @@ const make = Effect.gen(function* () {
145 if (typeof args.clientRequestId === "string") {
146 args.clientRequestId = yield* scopedRequestId(scope.requestNamespace, args.clientRequestId);
147 }
148 + // So a message sent there names the thread that sent it, even to a client that cannot reach here.
149 + const sender =
150 + caller === undefined
151 + ? undefined
152 + : {
153 + environmentId: scope.environmentId,
154 + threadId: caller.id,
155 + title: caller.title,
156 + };
157 return yield* peers.call({
158 environmentId,
159 tool: toolName,
160 arguments: args,
161 limits,
162 + ...(sender === undefined ? {} : { sender }),
163 success: success as Schema.Decoder<A>,
164 });
165 });
@@ -240,7 +249,7 @@ const make = Effect.gen(function* () {
249
250 const listLinks: PeerForwarding["Service"]["links"] = Effect.fn("PeerForwarding.listLinks")(
251 function* (scope) {
243 - yield* callerLimits(scope);
252 + yield* forwardingCaller(scope);
253 yield* requireEnabled;
254 const listed = yield* links.list.pipe(
255 Effect.mapError(
apps/server/src/peer/PeerMcpClient.test.ts
+59 -1
@@ -1,6 +1,11 @@
1 import { NodeHttpServer } from "@effect/platform-node";
2 import { expect, it } from "@effect/vitest";
3 -import { OrchestratorMcpFailure } from "@t3tools/contracts";
3 +import {
4 + EnvironmentId,
5 + OrchestrationV2LinkedSender,
6 + OrchestratorMcpFailure,
7 + ThreadId,
8 +} from "@t3tools/contracts";
9 import * as Context from "effect/Context";
10 import * as DateTime from "effect/DateTime";
11 import * as Deferred from "effect/Deferred";
@@ -44,6 +49,59 @@ const refusal = new OrchestratorMcpFailure({
49 message: "Thread thread-gone was not found.",
50 });
51
52 +const senderToolkit = Toolkit.make(
53 + Tool.make("sender", {
54 + description: "Returns the thread this request is made for.",
55 + success: Schema.Struct({ senderThread: Schema.NullOr(OrchestrationV2LinkedSender) }),
56 + dependencies: [McpInvocationContext.McpInvocationContext],
57 + }),
58 +);
59 +
60 +it.effect("tells the peer which thread a call is made for", () =>
61 + Effect.scoped(
62 + Effect.gen(function* () {
63 + const handlers = McpToolAccess.toLayer(senderToolkit, {
64 + sender: McpToolAccess.reads(() =>
65 + McpInvocationContext.McpInvocationContext.pipe(
66 + Effect.map((scope) => ({ senderThread: scope.client?.senderThread ?? null })),
67 + ),
68 + ),
69 + });
70 + const box = descriptorOf("environment-box", "Box");
71 + const b = yield* servePeer(box, McpHttpServer.toolkitRegistration(senderToolkit, handlers));
72 + const context = yield* Layer.build(
73 + layerLinkingEnvironment(descriptorOf("environment-a", "A")),
74 + );
75 + const links = Context.get(context, PeerLinks.PeerLinks);
76 + const client = Context.get(context, PeerMcpClient.PeerMcpClient);
77 + yield* linkTo(links, b);
78 + // A thread id may hold any character; it arrives as sent.
79 + const sender = {
80 + environmentId: EnvironmentId.make("environment-a"),
81 + threadId: ThreadId.make("import:claude/orc lead"),
82 + title: "orc lead / opus → fable",
83 + };
84 + const call = (input: { readonly sender?: typeof sender }) =>
85 + client.call({
86 + environmentId: box.environmentId,
87 + tool: "sender",
88 + arguments: {},
89 + limits: { runtimeMode: "full-access", interactionMode: "default" },
90 + ...input,
91 + success: Schema.Struct({ senderThread: Schema.NullOr(OrchestrationV2LinkedSender) }),
92 + });
93 + expect(yield* call({ sender })).toEqual({ senderThread: sender });
94 + expect(yield* call({})).toEqual({ senderThread: null });
95 + // A long title is cut to whole characters rather than breaking the call.
96 + const long = yield* call({ sender: { ...sender, title: "🧵".repeat(5000) } });
97 + expect(long.senderThread?.title).toBe("🧵".repeat(200));
98 + // A title holding an unpaired surrogate still lets the call through.
99 + const broken = yield* call({ sender: { ...sender, title: "Review \ud800" } });
100 + expect(broken.senderThread?.title).toBe("Review \ufffd");
101 + }),
102 + ).pipe(Effect.provide(NodeHttpServer.layerTest)),
103 +);
104 +
105 it.effect.each([false, true])(
106 "reuses an initialized session before its first call finishes (cancelled: %s)",
107 (cancelFirst) =>
apps/server/src/peer/PeerMcpClient.ts
+26 -1
@@ -3,6 +3,7 @@ import {
3 OrchestratorMcpFailure,
4 type PeerLinkError,
5 type ProviderInteractionMode,
6 + type OrchestrationV2LinkedSender,
7 type RuntimeMode,
8 } from "@t3tools/contracts";
9 import * as Context from "effect/Context";
@@ -21,6 +22,9 @@ import * as PeerLinks from "./PeerLinks.ts";
22 /** The only MCP protocol version a T3 Code `/mcp` registers. */
23 const PROTOCOL_VERSION = "2025-06-18";
24
25 +/** A title can be any length; the header carrying it stays well under HTTP header limits. */
26 +const SENDER_TITLE_MAX_LENGTH = 200;
27 +
28 /** The limits a call carries to the peer: the calling agent's modes here. */
29 export interface PeerCallLimits {
30 readonly runtimeMode: RuntimeMode;
@@ -41,6 +45,8 @@ export class PeerMcpClient extends Context.Service<
45 readonly tool: string;
46 readonly arguments: Record<string, unknown>;
47 readonly limits: PeerCallLimits;
48 + /** The thread here the call is made for, sent as `T3-Sender-Thread`. */
49 + readonly sender?: OrchestrationV2LinkedSender;
50 readonly success: S;
51 }) => Effect.Effect<S["Type"], OrchestratorMcpFailure>;
52 }
@@ -161,6 +167,20 @@ const make = Effect.gen(function* () {
167 const limitHeader = {
168 [McpInvocationContext.MODE_LIMIT_HEADER]: `${input.limits.runtimeMode}/${input.limits.interactionMode}`,
169 };
170 + const senderHeader =
171 + input.sender === undefined
172 + ? {}
173 + : {
174 + [McpInvocationContext.SENDER_THREAD_HEADER]: [
175 + input.sender.environmentId,
176 + input.sender.threadId,
177 + // Whole code points, so a cut never leaves half an emoji for encodeURIComponent.
178 + Array.from(input.sender.title).slice(0, SENDER_TITLE_MAX_LENGTH).join(""),
179 + ]
180 + // encodeURIComponent throws on an unpaired surrogate, which a title can hold.
181 + .map((part) => encodeURIComponent(part.toWellFormed()))
182 + .join("/"),
183 + };
184 const sessionKey = `${input.environmentId} ${resolved.url}`;
185 const callOnce = (sessionId: string) =>
186 post(
@@ -172,7 +192,12 @@ const make = Effect.gen(function* () {
192 method: "tools/call",
193 params: { name: input.tool, arguments: input.arguments },
194 },
175 - { ...limitHeader, "mcp-session-id": sessionId, "mcp-protocol-version": PROTOCOL_VERSION },
195 + {
196 + ...limitHeader,
197 + ...senderHeader,
198 + "mcp-session-id": sessionId,
199 + "mcp-protocol-version": PROTOCOL_VERSION,
200 + },
201 );
202 const existing = (yield* Ref.get(sessions)).get(sessionKey);
203 const sessionId = existing ?? (yield* openSession(resolved.url, resolved.token, limitHeader));
apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+21 -2
@@ -1283,7 +1283,22 @@ describe("MessagesTimeline agent messages", () => {
1283 setup();
1284 const onOpenThread = vi.fn();
1285 await using screen = await renderTimeline(
1286 - [message(AGENT_MESSAGE, { createdBy: "agent", senderThreadId: SENDER_THREAD_ID })],
1286 + [
1287 + message(AGENT_MESSAGE, { createdBy: "agent", senderThreadId: SENDER_THREAD_ID }),
1288 + // Sent from a linked environment this client does not reach.
1289 + message(
1290 + "Linked review finished",
1291 + {
1292 + createdBy: "agent",
1293 + linkedSender: {
1294 + environmentId: EnvironmentId.make("environment-linked"),
1295 + threadId: SENDER_THREAD_ID,
1296 + title: "Release lead",
1297 + },
1298 + },
1299 + "message-linked",
1300 + ),
1301 + ],
1302 { onOpenThread },
1303 );
1304 const row = screen.button(/^Agent/);
@@ -1295,10 +1310,14 @@ describe("MessagesTimeline agent messages", () => {
1310 await click(row);
1311 expect(screen.text()).toContain("The migration drops the index before backfilling it.");
1312 await click(screen.button("Open thread"));
1298 - expect(onOpenThread).toHaveBeenCalledWith(SENDER_THREAD_ID);
1313 + expect(onOpenThread).toHaveBeenCalledWith(SENDER_THREAD_ID, ENVIRONMENT_ID);
1314
1315 await click(screen.button(/^Agent/));
1316 expect(screen.text()).not.toContain("drops the index");
1317 +
1318 + // The linked sender shows the title it sent, and its thread cannot be opened from here.
1319 + await click(screen.button(/^Release lead/));
1320 + expect(screen.buttons("Open thread")).toHaveLength(0);
1321 });
1322
1323 it("leaves messages sent by T3 Code as full bubbles", async () => {
apps/web/src/components/chat/MessagesTimeline.tsx
+4 -1
@@ -260,7 +260,10 @@ interface MessagesTimelineProps {
260 announceTurnStatus?: boolean;
261 onOpenToolDiff?: (target: ToolCallDiffTarget) => void;
262 onOpenTurnDiff?: (runId: RunId, filePath?: string) => void;
263 - onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void;
263 + onOpenThread: (
264 + threadId: OrchestrationV2TurnItem["threadId"],
265 + environmentId?: EnvironmentId,
266 + ) => void;
267 renderHtmlRender?: TimelineRowSharedState["renderHtmlRender"];
268 turnItemSource?: TimelineRowSharedState["turnItemSource"];
269 /**
apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx
+32 -4
@@ -18,8 +18,17 @@ vi.mock(import("@t3tools/client-runtime/state/thread-workflows"), async (importO
18 vi.mock(import("../../state/entities"), async (importOriginal) => ({
19 ...(await importOriginal()),
20 useThreadProjection: (() => state.projection) as never,
21 - useQuietThreadShell: ((target: unknown) =>
22 - target === null ? null : { title: "Release lead" }) as never,
21 + // The linked environment is connected, but its thread is not in the loaded shell.
22 + useQuietThreadShell: ((target: { readonly environmentId: string } | null) =>
23 + target === null || target.environmentId === "environment:linked"
24 + ? null
25 + : { title: "Release lead" }) as never,
26 +}));
27 +
28 +vi.mock(import("../../state/environments"), async (importOriginal) => ({
29 + ...(await importOriginal()),
30 + useEnvironment: ((environmentId: string | null) =>
31 + environmentId === "environment:linked" ? { environmentId } : null) as never,
32 }));
33
34 vi.mock(import("../../state/query"), async (importOriginal) => ({
@@ -141,6 +150,19 @@ it("shows who sent a queued message and folds automation and agent prompts", asy
150 senderThreadId: "thread:lead",
151 },
152 ],
153 + [
154 + "run:linked",
155 + "Linked review finished.",
156 + {
157 + createdBy: "agent",
158 + creationSource: "mcp",
159 + linkedSender: {
160 + environmentId: "environment:linked",
161 + threadId: "thread:linked-lead",
162 + title: "Title when sent",
163 + },
164 + },
165 + ],
166 [
167 "run:server",
168 "Continue where you left off.",
@@ -158,6 +180,8 @@ it("shows who sent a queued message and folds automation and agent prompts", asy
180 };
181 const onOpenThread = vi.fn();
182 await using _screen = await renderQueue({ onOpenThread });
183 + // Four rows collapse the queue.
184 + await page.getByRole("button", { name: "Show all 4 queued" }).click();
185
186 const automation = page.getByRole("button", { name: /PR dispatcher/ });
187 await expect.element(automation).toHaveAttribute("aria-expanded", "false");
@@ -167,8 +191,12 @@ it("shows who sent a queued message and folds automation and agent prompts", asy
191 await expect.element(page.getByRole("link", { name: "Open automation" })).toBeInTheDocument();
192
193 await expect.element(page.getByRole("button", { name: /Release lead/ })).toBeVisible();
170 - await page.getByRole("button", { name: "Open thread" }).click({ force: true });
171 - expect(onOpenThread).toHaveBeenCalledExactlyOnceWith("thread:lead");
194 + await page.getByRole("button", { name: "Open thread" }).nth(0).click({ force: true });
195 + expect(onOpenThread).toHaveBeenCalledExactlyOnceWith("thread:lead", "environment:test");
196 + // A sender in a connected linked environment keeps the title it sent and opens there.
197 + await expect.element(page.getByRole("button", { name: /Title when sent/ })).toBeVisible();
198 + await page.getByRole("button", { name: "Open thread" }).nth(1).click({ force: true });
199 + expect(onOpenThread).toHaveBeenLastCalledWith("thread:linked-lead", "environment:linked");
200
201 await expect.element(page.getByText("Sent by T3 Code")).toBeVisible();
202 await expect.element(page.getByText("Continue where you left off.")).toBeVisible();
apps/web/src/components/chat/QueuedRunsControl.tsx
+20 -9
@@ -29,6 +29,7 @@ import { useId, useImperativeHandle, useRef, useState, type ReactNode, type Ref
29 import { useAssetUrls } from "../../assets/assetUrls";
30 import { threadEnvironment } from "../../state/threads";
31 import { useQuietThreadShell, useThreadProjection } from "../../state/entities";
32 +import { useEnvironment } from "../../state/environments";
33 import { useAtomCommand } from "../../state/use-atom-command";
34 import { isImageAttachment, type ChatMessage } from "../../types";
35 import { cn } from "~/lib/utils";
@@ -91,7 +92,7 @@ export function QueuedRunsControl({
92 readonly onEditQueuedRun: (request: EditQueuedRunRequest) => void;
93 readonly onCancelEdit: () => void;
94 readonly timestampFormat: TimestampFormat;
94 - readonly onOpenThread: (threadId: ThreadId) => void;
95 + readonly onOpenThread: (threadId: ThreadId, environmentId?: EnvironmentId) => void;
96 }) {
97 const projection = useThreadProjection(
98 scopeThreadRef(props.environmentId, props.threadId),
@@ -411,19 +412,22 @@ function QueuedMessage(props: {
412 readonly thumbnails: ReadonlyArray<QueuedRowThumbnail>;
413 readonly isEditing: boolean;
414 readonly timestampFormat: TimestampFormat;
414 - readonly onOpenThread: (threadId: ThreadId) => void;
415 + readonly onOpenThread: (threadId: ThreadId, environmentId?: EnvironmentId) => void;
416 readonly children: ReactNode;
417 }) {
418 const presentation = props.message ? resolveUserMessagePresentation(props.message) : null;
419 const attribution = presentation?.attribution ?? null;
420 const scheduledTaskId = presentation?.scheduledTaskId;
421 const senderThreadId = props.message?.senderThreadId;
422 + // A linked environment's agent sent it from a thread there.
423 + const senderRef =
424 + props.message?.linkedSender ??
425 + (senderThreadId === undefined ? null : scopeThreadRef(props.environmentId, senderThreadId));
426 const [expanded, setExpanded] = useState(false);
427 const taskTitle = useScheduledTaskTitle(props.environmentId, scheduledTaskId);
423 - const senderShell = useQuietThreadShell(
424 - attribution === "agent" && senderThreadId
425 - ? { environmentId: props.environmentId, threadId: senderThreadId }
426 - : null,
428 + const senderShell = useQuietThreadShell(attribution === "agent" ? senderRef : null);
429 + const linkedSenderEnvironment = useEnvironment(
430 + props.message?.linkedSender?.environmentId ?? null,
431 );
432 const fold =
433 attribution === "automation"
@@ -435,7 +439,8 @@ function QueuedMessage(props: {
439 : attribution === "agent"
440 ? {
441 icon: MessagesSquareIcon,
438 - label: senderShell?.title.trim() || "Agent",
442 + label:
443 + senderShell?.title.trim() || props.message?.linkedSender?.title.trim() || "Agent",
444 summary: props.previewText.split(/\r?\n/).find((line) => line.trim()) ?? "",
445 }
446 : null;
@@ -508,8 +513,14 @@ function QueuedMessage(props: {
513 <div className="flex items-center gap-0.5 pe-1 text-xs text-muted-foreground">
514 {props.message ? (
515 <span className="me-1 flex items-center gap-2 px-1 opacity-0 transition-opacity duration-200 pointer-coarse:opacity-100 focus-within:opacity-100 group-hover/queued:opacity-100">
511 - {attribution === "agent" && senderThreadId ? (
512 - <InlineButton tone="muted" onClick={() => props.onOpenThread(senderThreadId)}>
516 + {attribution === "agent" &&
517 + senderRef &&
518 + // Only an environment this client is connected to can open the sender's thread there.
519 + (props.message?.linkedSender === undefined || linkedSenderEnvironment !== null) ? (
520 + <InlineButton
521 + tone="muted"
522 + onClick={() => props.onOpenThread(senderRef.threadId, senderRef.environmentId)}
523 + >
524 Open thread
525 </InlineButton>
526 ) : null}
apps/web/src/components/chat/TimelineUserMessageRow.tsx
+21 -9
@@ -9,9 +9,11 @@ import {
9 type ServerProviderSkill,
10 ThreadId,
11 } from "@t3tools/contracts";
12 +import { scopeThreadRef } from "@t3tools/client-runtime/environment";
13 import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message";
14 import { Link } from "@tanstack/react-router";
15 import { useQuietThreadShell } from "../../state/entities";
16 +import { useEnvironment } from "../../state/environments";
17 import { useEnvironmentQuery } from "../../state/query";
18 import { serverEnvironment } from "../../state/server";
19 import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
@@ -429,7 +431,12 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
431 const ctx = use(TimelineRowCtx);
432 const { onImageExpand, onFileOpen } = ctx;
433 const coarsePointer = useMediaQuery({ pointer: "coarse" });
432 - const senderThreadId = row.message.senderThreadId;
434 + // A linked environment's agent sent it from a thread there.
435 + const senderRef =
436 + row.message.linkedSender ??
437 + (row.message.senderThreadId === undefined
438 + ? null
439 + : scopeThreadRef(ctx.activeThreadEnvironmentId, row.message.senderThreadId));
440 const resources = selectMessageImageResources(row.message.attachments);
441 const previewUrls = useAssetUrls(ctx.activeThreadEnvironmentId, resources);
442 const [projectPreviews] = useState(createMessageAttachmentPreviewProjector);
@@ -459,12 +466,14 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
466 const folded = userMessage.attribution === "agent";
467 const [expanded, setExpanded] = useState(false);
468 const revealFoldRef = findRevealRef(() => setExpanded(true));
462 - const senderShell = useQuietThreadShell(
463 - folded && senderThreadId
464 - ? { environmentId: ctx.activeThreadEnvironmentId, threadId: senderThreadId }
465 - : null,
466 - );
467 - const senderLabel = senderShell?.title.trim() || "Agent";
469 + const senderShell = useQuietThreadShell(folded ? senderRef : null);
470 + const senderLabel =
471 + senderShell?.title.trim() || row.message.linkedSender?.title.trim() || "Agent";
472 + // Only an environment this client is connected to can open the sender's thread there.
473 + const linkedSenderEnvironment = useEnvironment(row.message.linkedSender?.environmentId ?? null);
474 + const canOpenSender =
475 + senderRef !== null &&
476 + (row.message.linkedSender === undefined || linkedSenderEnvironment !== null);
477 const resolvedContext = resolveUserMessageContext({ ...row.message, text: userMessage.text });
478 const previewImages = userImages.filter((image) => image.name.startsWith("preview-annotation-"));
479 const revertTurnCount = row.revertTurnCount;
@@ -786,8 +795,11 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
795 floatActions ? "flex-wrap" : "shrink-0",
796 )}
797 >
789 - {folded && senderThreadId ? (
790 - <InlineButton onClick={() => ctx.onOpenThread(senderThreadId)} tone="muted">
798 + {folded && senderRef && canOpenSender ? (
799 + <InlineButton
800 + onClick={() => ctx.onOpenThread(senderRef.threadId, senderRef.environmentId)}
801 + tone="muted"
802 + >
803 Open thread
804 </InlineButton>
805 ) : null}
apps/web/src/components/chat/timelineRowContext.ts
+4 -1
@@ -81,7 +81,10 @@ export interface TimelineRowSharedState {
81 renderHtmlRender: ((row: Extract<TimelineRow, { kind: "html-render" }>) => ReactNode) | undefined;
82 /** Unset, expanded rows read detail and command output from the environment. */
83 turnItemSource: TurnItemSource | undefined;
84 - onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void;
84 + onOpenThread: (
85 + threadId: OrchestrationV2TurnItem["threadId"],
86 + environmentId?: EnvironmentId,
87 + ) => void;
88 workflowOpening: WorkflowOpening | null;
89 /** Absent hides "Fork from this response", as in the guest view. */
90 onForkFromRun:
apps/web/src/session-logic.ts
+1
@@ -593,6 +593,7 @@ export function deriveTimelineEntriesFromVisibleTurnItems(
593 createdBy: item.createdBy,
594 creationSource: item.creationSource,
595 ...(item.senderThreadId !== undefined ? { senderThreadId: item.senderThreadId } : {}),
596 + ...(item.linkedSender !== undefined ? { linkedSender: item.linkedSender } : {}),
597 ...(item.idleCompaction !== undefined ? { idleCompaction: item.idleCompaction } : {}),
598 ...(item.scheduledTaskId !== undefined
599 ? { scheduledTaskId: item.scheduledTaskId }
apps/web/src/types.ts
+2
@@ -13,6 +13,7 @@ import type {
13 ProviderInteractionMode,
14 RunId,
15 RuntimeMode,
16 + OrchestrationV2LinkedSender,
17 ScheduledTaskId,
18 ThreadId,
19 } from "@t3tools/contracts";
@@ -83,6 +84,7 @@ export interface ChatMessage {
84 readonly creationSource?: OrchestrationV2CreationSource;
85 readonly scheduledTaskId?: ScheduledTaskId;
86 readonly senderThreadId?: ThreadId;
87 + readonly linkedSender?: OrchestrationV2LinkedSender;
88 readonly idleCompaction?: import("@t3tools/contracts").OrchestrationV2IdleCompaction;
89 readonly createdAt: string;
90 readonly updatedAt: string;
packages/contracts/src/orchestrationV2.ts
+16
@@ -139,6 +139,18 @@ export const OrchestrationV2DelegatedFrom = Schema.Struct({
139 });
140 export type OrchestrationV2DelegatedFrom = typeof OrchestrationV2DelegatedFrom.Type;
141
142 +/**
143 + * The thread in a linked environment whose agent sent this message here, and its title
144 + * then, for a client that cannot reach that environment. `senderThreadId` names only a
145 + * thread in this environment.
146 + */
147 +export const OrchestrationV2LinkedSender = Schema.Struct({
148 + environmentId: EnvironmentId,
149 + threadId: ThreadId,
150 + title: Schema.String,
151 +});
152 +export type OrchestrationV2LinkedSender = typeof OrchestrationV2LinkedSender.Type;
153 +
154 export const OrchestrationV2NativeRefStrength = Schema.Literals(["strong", "weak", "none"]);
155 export type OrchestrationV2NativeRefStrength = typeof OrchestrationV2NativeRefStrength.Type;
156
@@ -1314,6 +1326,7 @@ export const OrchestrationV2ConversationMessage = Schema.Struct({
1326 ...OrchestrationV2CreationFields,
1327 scheduledTaskId: Schema.optional(ScheduledTaskId),
1328 senderThreadId: Schema.optional(ThreadId),
1329 + linkedSender: Schema.optional(OrchestrationV2LinkedSender),
1330 idleCompaction: Schema.optional(OrchestrationV2IdleCompaction),
1331 /**
1332 * The message is the script a provider-native workflow run executes, not prose. Clients show
@@ -1633,6 +1646,7 @@ export const OrchestrationV2TurnItem = Schema.Union([
1646 messageId: MessageId,
1647 scheduledTaskId: Schema.optional(ScheduledTaskId),
1648 senderThreadId: Schema.optional(ThreadId),
1649 + linkedSender: Schema.optional(OrchestrationV2LinkedSender),
1650 idleCompaction: Schema.optional(OrchestrationV2IdleCompaction),
1651 workflowScript: OrchestrationV2ConversationMessage.fields.workflowScript,
1652 freshContext: OrchestrationV2Run.fields.freshContext,
@@ -2482,6 +2496,7 @@ export const OrchestrationV2TurnItemJson = Schema.Union([
2496 messageId: MessageId,
2497 scheduledTaskId: Schema.optional(ScheduledTaskId),
2498 senderThreadId: Schema.optional(ThreadId),
2499 + linkedSender: Schema.optional(OrchestrationV2LinkedSender),
2500 idleCompaction: Schema.optional(OrchestrationV2IdleCompaction),
2501 workflowScript: OrchestrationV2ConversationMessage.fields.workflowScript,
2502 freshContext: OrchestrationV2Run.fields.freshContext,
@@ -3197,6 +3212,7 @@ export const OrchestrationV2Command = Schema.Union([
3212 ...OrchestrationV2CreationFields,
3213 scheduledTaskId: Schema.optional(ScheduledTaskId),
3214 senderThreadId: Schema.optional(ThreadId),
3215 + linkedSender: Schema.optional(OrchestrationV2LinkedSender),
3216 idleCompaction: Schema.optional(OrchestrationV2IdleCompaction),
3217 /** Start a new provider session without the thread's earlier context. Never steers. */
3218 freshContext: Schema.optional(Schema.Boolean),