Skip to content

Commit f991781

Browse files
EtanHeyHappy Camprjuliusmarminge
authored
fix(server,web,mobile): messages from a linked environment name the thread that sent them (#34721)
Co-authored-by: Happy Campr <[email protected]> Co-authored-by: Julius Marminge <[email protected]>
1 parent 82465ed commit f991781

25 files changed

Lines changed: 432 additions & 42 deletions

‎apps/mobile/src/features/threads/ThreadFeed.tsx‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,7 @@ import {
246246
useQuietThreadShell,
247247
useThreadChipIcons,
248248
} from "../../state/entities";
249+
import { useEnvironmentPresentation } from "../../state/presentation";
249250
import { useThreadSelection } from "../../state/use-thread-selection";
250251
import { useEnvironmentQuery } from "../../state/query";
251252
import { serverEnvironment } from "../../state/server";
@@ -1333,6 +1334,8 @@ function useMarkdownStyles(): MarkdownStyleSets {
13331334
function AgentMessageFoldHeader(props: {
13341335
readonly environmentId: EnvironmentId;
13351336
readonly senderThreadId?: ThreadId;
1337+
/** A linked environment's sender title, for when this client cannot reach it. */
1338+
readonly senderTitle?: string;
13361339
readonly summary: string;
13371340
readonly expanded: boolean;
13381341
readonly onToggle: () => void;
@@ -1341,7 +1344,7 @@ function AgentMessageFoldHeader(props: {
13411344
const senderShell = useQuietThreadShell(
13421345
props.senderThreadId ? scopeThreadRef(props.environmentId, props.senderThreadId) : null,
13431346
);
1344-
const label = senderShell?.title.trim() || "Agent";
1347+
const label = senderShell?.title.trim() || props.senderTitle?.trim() || "Agent";
13451348
return (
13461349
<Pressable
13471350
accessibilityRole="button"
@@ -1384,8 +1387,12 @@ function AgentMessageFoldHeader(props: {
13841387
function OpenSenderThreadButton(props: {
13851388
readonly environmentId: EnvironmentId;
13861389
readonly senderThreadId: ThreadId;
1390+
/** In a linked environment, shown only when this client is connected to it. */
1391+
readonly linked?: boolean;
13871392
}) {
13881393
const openLinkedThread = useOpenLinkedThread();
1394+
const linkedEnvironment = useEnvironmentPresentation(props.linked ? props.environmentId : null);
1395+
if (props.linked && linkedEnvironment.presentation === null) return null;
13891396
return (
13901397
<Pressable
13911398
accessibilityRole="link"
@@ -1916,6 +1923,12 @@ function renderFeedEntry(
19161923
if (isUser) {
19171924
const enterAnimated = isFreshTimestamp(message.createdAt);
19181925
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);
19191932
const foldExpanded = foldRowId !== null && (props.expandedWorkRows[foldRowId] ?? false);
19201933
const bubbleBodyVisible = foldRowId === null || foldExpanded;
19211934
const intentBadge = props.userMessageGrouping.continuesSteer
@@ -2036,8 +2049,9 @@ function renderFeedEntry(
20362049
{presentation.attribution === "guest" ? <GuestBubbleTint /> : null}
20372050
{foldRowId !== null ? (
20382051
<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 } : {})}
20412055
summary={
20422056
replaceComposerContextReferences(presentation.text, (ref) => ref.label)
20432057
.split(/\r?\n/)
@@ -2144,10 +2158,11 @@ function renderFeedEntry(
21442158
) : null}
21452159
{bubbleBodyVisible ? (
21462160
<View className="mt-1 flex-row items-center justify-end gap-1 pr-0.5">
2147-
{foldRowId !== null && message.senderThreadId ? (
2161+
{foldRowId !== null && senderRef ? (
21482162
<OpenSenderThreadButton
2149-
environmentId={props.environmentId}
2150-
senderThreadId={message.senderThreadId}
2163+
environmentId={senderRef.environmentId}
2164+
senderThreadId={senderRef.threadId}
2165+
linked={message.linkedSender !== undefined}
21512166
/>
21522167
) : null}
21532168
{intentBadge ? (

‎apps/mobile/src/features/threads/ThreadQueueControl.tsx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,10 @@ function QueuedRunSender(props: {
7070
}) {
7171
const { attribution, scheduledTaskId } = resolveUserMessagePresentation(props.message);
7272
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;
7375
const senderShell = useQuietThreadShell(
74-
senderThreadId ? scopeThreadRef(props.environmentId, senderThreadId) : null,
76+
linkedSender ?? (senderThreadId ? scopeThreadRef(props.environmentId, senderThreadId) : null),
7577
);
7678
const tasks = useEnvironmentQuery(
7779
scheduledTaskId
@@ -88,7 +90,7 @@ function QueuedRunSender(props: {
8890
: attribution === "agent"
8991
? {
9092
icon: "bubble.left.and.bubble.right" as const,
91-
label: senderShell?.title.trim() || "Agent",
93+
label: senderShell?.title.trim() || linkedSender?.title.trim() || "Agent",
9294
}
9395
: attribution === "t3code"
9496
? { icon: null, label: "Sent by T3 Code" }

‎apps/mobile/src/lib/filePreview.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,9 @@ vi.mock("../state/entities", () => ({
182182
vi.mock("../state/use-thread-selection", () => ({
183183
useThreadSelection: () => ({ selectedThread: null }),
184184
}));
185+
vi.mock("../state/presentation", () => ({
186+
useEnvironmentPresentation: () => ({ isReady: true, presentation: null }),
187+
}));
185188
vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() }));
186189
vi.mock("../state/use-atom-command", () => ({}));
187190
vi.mock("../state/v2-item-support", () => ({}));

‎apps/mobile/src/lib/threadActivity.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,7 @@ export interface ThreadFeedMessage {
140140
readonly creationSource?: OrchestrationV2CreationSource;
141141
readonly scheduledTaskId?: ScheduledTaskId;
142142
readonly senderThreadId?: ThreadId;
143+
readonly linkedSender?: import("@t3tools/contracts").OrchestrationV2LinkedSender;
143144
readonly idleCompaction?: import("@t3tools/contracts").OrchestrationV2IdleCompaction;
144145
readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
145146
readonly sourceThreadId: ThreadId;
@@ -2387,6 +2388,7 @@ export function buildThreadFeed(
23872388
creationSource: item.creationSource,
23882389
...(item.scheduledTaskId ? { scheduledTaskId: item.scheduledTaskId } : {}),
23892390
...(item.senderThreadId ? { senderThreadId: item.senderThreadId } : {}),
2391+
...(item.linkedSender ? { linkedSender: item.linkedSender } : {}),
23902392
...(item.idleCompaction ? { idleCompaction: item.idleCompaction } : {}),
23912393
}
23922394
: {}),

‎apps/server/src/mcp/McpHttpServer.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
ProviderInteractionMode,
2222
type RunId,
2323
RuntimeMode,
24+
OrchestrationV2LinkedSender,
2425
ThreadId,
2526
} from "@t3tools/contracts";
2627

@@ -190,6 +191,34 @@ const withModeLimit = (
190191
: { ...invocation, client: { ...invocation.client, narrowedTo: limit.value } };
191192
};
192193

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+
193222
// The Linked environments beta is off here: links wait until it is on again.
194223
const linkedEnvironmentsOff = HttpServerResponse.jsonUnsafe(
195224
{
@@ -235,7 +264,7 @@ const makeMcpAuthMiddleware = Effect.gen(function* () {
235264
offerOAuth: Option.isSome(clients) && !looksLikeProviderToken(token),
236265
});
237266
}
238-
const asked = withModeLimit(invocation, request);
267+
const asked = withModeLimit(withSenderThread(invocation, request), request);
239268
if (asked === undefined) return invalidModeLimit;
240269
const limited = McpInvocationContext.withRuntimeModeCeiling(asked, runtimeModeCeiling);
241270
const linkedEnvironments = yield* linksEnabled;

‎apps/server/src/mcp/McpInvocationContext.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
PreviewAutomationUnavailableError,
77
type ProviderInstanceId,
88
type ProviderInteractionMode,
9+
type OrchestrationV2LinkedSender,
910
type RuntimeMode,
1011
type ThreadId,
1112
} from "@t3tools/contracts";
@@ -45,6 +46,8 @@ export interface McpClientCaller {
4546
* another environment passing on the limits of the agent it calls for.
4647
*/
4748
readonly narrowedTo?: ClientModes | undefined;
49+
/** A linked environment's thread this request is made for (`T3-Sender-Thread`). */
50+
readonly senderThread?: OrchestrationV2LinkedSender | undefined;
4851
/** An outside client's thread links go through this hosted app, as Copy thread's do. */
4952
readonly hostedAppUrl?: string | undefined;
5053
}
@@ -57,6 +60,13 @@ export interface McpClientCaller {
5760
*/
5861
export const MODE_LIMIT_HEADER = "t3-mode-limit";
5962

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+
6070
export interface ClientModes {
6171
readonly runtimeMode: RuntimeMode;
6272
readonly interactionMode: ProviderInteractionMode;

‎apps/server/src/mcp/OrchestratorMcpService.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3813,6 +3813,55 @@ describe("OrchestratorMcpService thread lookup", () => {
38133813
}),
38143814
);
38153815

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+
38163865
it.effect("refuses waiting without orchestration capability before reading the target", () =>
38173866
Effect.gen(function* () {
38183867
const sent = yield* Ref.make(0);

‎apps/server/src/mcp/OrchestratorMcpService.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3147,6 +3147,10 @@ const make = Effect.gen(function* () {
31473147
}),
31483148
threadId: input.threadId,
31493149
...(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+
: {}),
31503154
messageId,
31513155
text: input.message,
31523156
attachments: [],

‎apps/server/src/orchestration-v2/EffectWorker.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,9 @@ export const layerExecutor: Layer.Layer<
346346
...(message.senderThreadId === undefined
347347
? {}
348348
: { senderThreadId: message.senderThreadId }),
349+
...(message.linkedSender === undefined
350+
? {}
351+
: { linkedSender: message.linkedSender }),
349352
})
350353
.pipe(
351354
// A disabled instance cannot retry this completed turn; its result stands.

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2643,6 +2643,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
26432643
...(queuedMessage.senderThreadId === undefined
26442644
? {}
26452645
: { senderThreadId: queuedMessage.senderThreadId }),
2646+
...(queuedMessage.linkedSender === undefined
2647+
? {}
2648+
: { linkedSender: queuedMessage.linkedSender }),
26462649
...(queuedMessage.idleCompaction === undefined
26472650
? {}
26482651
: { idleCompaction: queuedMessage.idleCompaction }),
@@ -5460,6 +5463,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
54605463
readonly creationSource: OrchestrationV2ConversationMessage["creationSource"];
54615464
readonly scheduledTaskId?: OrchestrationV2ConversationMessage["scheduledTaskId"];
54625465
readonly senderThreadId?: OrchestrationV2ConversationMessage["senderThreadId"];
5466+
readonly linkedSender?: OrchestrationV2ConversationMessage["linkedSender"];
54635467
readonly idleCompaction?: OrchestrationV2ConversationMessage["idleCompaction"];
54645468
readonly delegatedCompletion?: OrchestrationV2ConversationMessage["delegatedCompletion"];
54655469
readonly notification?: OrchestrationV2ConversationMessage["notification"];
@@ -5604,6 +5608,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
56045608
? {}
56055609
: { scheduledTaskId: input.scheduledTaskId }),
56065610
...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
5611+
...(input.linkedSender === undefined ? {} : { linkedSender: input.linkedSender }),
56075612
...(input.idleCompaction === undefined ? {} : { idleCompaction: input.idleCompaction }),
56085613
id: input.messageId,
56095614
threadId: input.command.threadId,
@@ -5624,6 +5629,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
56245629
? {}
56255630
: { scheduledTaskId: input.scheduledTaskId }),
56265631
...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
5632+
...(input.linkedSender === undefined ? {} : { linkedSender: input.linkedSender }),
56275633
...(input.idleCompaction === undefined ? {} : { idleCompaction: input.idleCompaction }),
56285634
id: idAllocator.derive.userTurnItem({ messageId: input.messageId }),
56295635
threadId: input.command.threadId,
@@ -6786,6 +6792,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
67866792
? {}
67876793
: { scheduledTaskId: command.scheduledTaskId }),
67886794
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
6795+
...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }),
67896796
...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
67906797
forceRestart: dispatchMode.type === "restart_active",
67916798
});
@@ -7076,6 +7083,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
70767083
? {}
70777084
: { scheduledTaskId: command.scheduledTaskId }),
70787085
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
7086+
...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }),
70797087
...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
70807088
id: command.messageId,
70817089
threadId: command.threadId,
@@ -7483,6 +7491,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
74837491
? {}
74847492
: { scheduledTaskId: command.scheduledTaskId }),
74857493
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
7494+
...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }),
74867495
...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
74877496
id: command.messageId,
74887497
threadId: command.threadId,
@@ -7505,6 +7514,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
75057514
? {}
75067515
: { scheduledTaskId: command.scheduledTaskId }),
75077516
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
7517+
...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }),
75087518
...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
75097519
id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
75107520
threadId: command.threadId,
@@ -8268,6 +8278,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
82688278
? {}
82698279
: { scheduledTaskId: command.scheduledTaskId }),
82708280
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
8281+
...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }),
82718282
...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
82728283
id: command.messageId,
82738284
threadId: command.threadId,
@@ -8290,6 +8301,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
82908301
? {}
82918302
: { scheduledTaskId: command.scheduledTaskId }),
82928303
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
8304+
...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }),
82938305
...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
82948306
id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
82958307
threadId: command.threadId,
@@ -10765,6 +10777,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1076510777
...(queuedMessage.senderThreadId === undefined
1076610778
? {}
1076710779
: { senderThreadId: queuedMessage.senderThreadId }),
10780+
...(queuedMessage.linkedSender === undefined
10781+
? {}
10782+
: { linkedSender: queuedMessage.linkedSender }),
1076810783
...(queuedMessage.idleCompaction === undefined
1076910784
? {}
1077010785
: { idleCompaction: queuedMessage.idleCompaction }),

0 commit comments

Comments
 (0)