Skip to content

Commit 6406b0f

Browse files
fix(agents): address review comments on agent orchestration and UI
1 parent 409ef90 commit 6406b0f

14 files changed

Lines changed: 445 additions & 134 deletions

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

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2035,15 +2035,27 @@ const make = Effect.gen(function* () {
20352035
`Agent ${input.targetAgentId} was not found in .agents, .github/agents, or AGENTS.md.`,
20362036
);
20372037
}
2038-
const providers = yield* loadProviders;
2039-
const agentSelection =
2038+
let providers = yield* loadProviders;
2039+
let agentSelection =
20402040
agent === undefined || input.target?.model !== undefined
20412041
? undefined
20422042
: resolveModelForAgent(
20432043
agent,
20442044
providersForTarget(providers, input.target),
20452045
parent.thread.modelSelection.instanceId,
20462046
);
2047+
if (
2048+
agent?.model !== undefined &&
2049+
input.target?.model === undefined &&
2050+
agentSelection === undefined
2051+
) {
2052+
providers = yield* providerRegistry.refreshInstance(agent.model.instanceId);
2053+
agentSelection = resolveModelForAgent(
2054+
agent,
2055+
providersForTarget(providers, input.target),
2056+
parent.thread.modelSelection.instanceId,
2057+
);
2058+
}
20472059
if (
20482060
agent?.model !== undefined &&
20492061
input.target?.model === undefined &&

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ const OrchestratorCapabilitiesTool = Tool.make("orchestrator_capabilities", {
6565

6666
export const DelegateTaskTool = Tool.make("delegate_task", {
6767
description:
68-
"Needs an agent running inside a T3 thread. Delegate one task to a T3-owned child agent/subagent of THIS thread and run it with only the supplied task prompt, without copying parent conversation history. Choose providers and models from orchestrator_capabilities, which uses the same live catalog as the composer. Prefer native subagent tools for same-provider work only when they support the chosen model. Use this for any model missing from the native tool, including same-provider work, for cross-provider work, or for explicitly T3-owned child tasks. Set targetAgentId to run the child with a named custom persona; that agent's model or tier is selected when the child thread starts and does not switch models during a run. A custom lead's canDelegateTo allowlist is enforced for this T3 delegate_task tool only; provider-native delegation remains controlled by the provider. Agent frontmatter tools policies are unsupported. For every T3 delegated review round, call delegate_task again with the original brief, prior findings, responses, and unresolved objections in the task prompt. Track each round by its own taskId and use a distinct clientRequestId per round, stable across retries of that round. The childThreadId is backing storage, not the target for starting another delegated review round through t3_thread_send. Provider, model, model options (see orchestrator_capabilities), runtime mode, and interaction mode inherit unless target overrides them. Prefer mode='async' for long work; mode='wait' blocks until completion or timeout. timeoutMs on mode=wait is only the parent's wait budget and does not cancel the child. waitTimedOut on that wait call means the timeout fired; keep that taskId and read status on later task_status. An async child's completion wakes this thread through a notification, steered into active turns where supported or queued otherwise, so end the turn instead of polling or spawning watchers; use task_status only when the result is needed mid-turn.",
68+
"Needs an agent running inside a T3 thread. Delegate one task to a T3-owned child agent/subagent of THIS thread and run it with only the supplied task prompt, without copying parent conversation history. Choose providers and models from orchestrator_capabilities, which uses the same live catalog as the composer. Prefer native subagent tools for same-provider work only when they support the chosen model. Use this for any model missing from the native tool, including same-provider work, for cross-provider work, or for explicitly T3-owned child tasks. Set targetAgentId to run the child with a named custom persona; that agent's model or tier is selected when the child thread starts and does not switch models during a run. A custom lead's canDelegateTo allowlist is enforced for this T3 delegate_task tool only; provider-native delegation remains controlled by the provider. Agent frontmatter tools policies are unsupported. For every T3 delegated review round, call delegate_task again with the original brief, prior findings, responses, and unresolved objections in the task prompt. Track each round by its own taskId and use a distinct clientRequestId per round, stable across retries of that round. The childThreadId is backing storage, not the target for starting another delegated review round through t3_thread_send. Provider, model, model options (see orchestrator_capabilities), runtime mode, and interaction mode inherit unless target overrides them. When orchestrator_capabilities lists runtime modes for the target provider, an explicit non-inherit runtimeMode must be one of those modes; an inherited mode uses the broadest listed mode that does not exceed the parent mode, falling back to approval-required if no such mode qualifies. Prefer mode='async' for long work; mode='wait' blocks until completion or timeout. timeoutMs on mode=wait is only the parent's wait budget and does not cancel the child. waitTimedOut on that wait call means the timeout fired; keep that taskId and read status on later task_status. An async child's completion wakes this thread through a notification, steered into active turns where supported or queued otherwise, so end the turn instead of polling or spawning watchers; use task_status only when the result is needed mid-turn.",
6969
parameters: OrchestratorMcpDelegateTaskInput,
7070
success: OrchestratorMcpDelegateTaskResult,
7171
failure: OrchestratorMcpFailure,

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

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ import {
8484
} from "./CheckpointRestoreSafety.ts";
8585
import { CheckpointServiceV2 } from "./CheckpointService.ts";
8686
import { CommandPolicyV2, resolveMessageDispatchIntent } from "./CommandPolicy.ts";
87-
import { CommandReceiptStoreV2 } from "./CommandReceiptStore.ts";
87+
import { CommandReceiptStoreV2, type CommandReceiptV2 } from "./CommandReceiptStore.ts";
8888
import { ContextHandoffServiceV2 } from "./ContextHandoffService.ts";
8989
import { notificationTurnItem } from "@t3tools/provider-core/server/notification";
9090
import { isRestartNoteSource } from "./RestartBackgroundNote.ts";
@@ -358,6 +358,9 @@ export interface OrchestratorV2Shape {
358358
readonly getThreadEventSequence: (
359359
threadId: ThreadId,
360360
) => Effect.Effect<number, OrchestratorV2Error>;
361+
readonly getCommandReceipt: (
362+
commandId: CommandId,
363+
) => Effect.Effect<CommandReceiptV2 | null, OrchestratorDispatchError>;
361364
readonly streamStoredEvents: Stream.Stream<OrchestrationV2StoredEvent, OrchestratorV2Error>;
362365
readonly streamStoredEventsFrom: (input?: {
363366
readonly threadId?: ThreadId;
@@ -11384,6 +11387,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1138411387
eventSink
1138511388
.latestSequence({ threadId })
1138611389
.pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),
11390+
getCommandReceipt: (commandId) =>
11391+
commandReceipts.getByCommandId(commandId).pipe(
11392+
Effect.map(Option.getOrNull),
11393+
Effect.mapError(
11394+
(cause) =>
11395+
new OrchestratorDispatchError({
11396+
commandId,
11397+
commandType: "unknown",
11398+
cause,
11399+
}),
11400+
),
11401+
),
1138711402
streamStoredEvents: eventSink.stream().pipe(
1138811403
Stream.mapError(
1138911404
(cause) =>
@@ -11530,6 +11545,14 @@ const layerUnavailable: Layer.Layer<OrchestratorV2> = Layer.succeed(
1153011545
cause: "Orchestration V2 live runtime is not configured.",
1153111546
}),
1153211547
),
11548+
getCommandReceipt: (commandId) =>
11549+
Effect.fail(
11550+
new OrchestratorDispatchError({
11551+
commandId,
11552+
commandType: "unknown",
11553+
cause: "Orchestration V2 live runtime is not configured.",
11554+
}),
11555+
),
1153311556
streamStoredEvents: Stream.fail(
1153411557
new OrchestratorDomainEventStreamError({
1153511558
cause: "Orchestration V2 live runtime is not configured.",

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,7 @@ export interface ThreadManagementServiceShape {
333333
Orchestrator.OrchestratorV2Error
334334
>;
335335
readonly getThreadShell: Orchestrator.OrchestratorV2["Service"]["getThreadShell"];
336+
readonly getCommandReceipt: Orchestrator.OrchestratorV2["Service"]["getCommandReceipt"];
336337
readonly listProjectThreads: (input: {
337338
readonly projectId: ProjectId;
338339
readonly includeSubagents: boolean;
@@ -1011,6 +1012,7 @@ const make = Effect.gen(function* () {
10111012
getShellSnapshot: orchestrator.getShellSnapshot,
10121013
readShellSnapshot: orchestrator.readShellSnapshot,
10131014
getThreadShell: orchestrator.getThreadShell,
1015+
getCommandReceipt: orchestrator.getCommandReceipt,
10141016
listProjectThreads,
10151017
sendToThread,
10161018
waitForThread,

‎apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -865,3 +865,49 @@ it.effect("enforces a custom lead allowlist for direct delegated-task commands",
865865
expect(dispatched).toEqual([]);
866866
}).pipe(Effect.provide(layerIntakeTest)),
867867
);
868+
869+
it.effect("skips agent delegation validation if command receipt was already accepted", () =>
870+
Effect.gen(function* () {
871+
const parentThreadId = ThreadId.make("thread:delegation-replay");
872+
const commandId = CommandId.make("delegate-replay");
873+
const dispatched: OrchestrationV2ServerCommand[] = [];
874+
const layer = Layer.mergeAll(
875+
Layer.mock(ThreadManagementService.ThreadManagementService)({
876+
getCommandReceipt: () =>
877+
Effect.succeed({
878+
commandId,
879+
threadId: parentThreadId,
880+
commandType: "delegated_task.request",
881+
acceptedAt: NOW,
882+
resultSequence: 1,
883+
status: "accepted",
884+
error: null,
885+
}),
886+
dispatch: (command) => {
887+
dispatched.push(command);
888+
return Effect.succeed({ sequence: 1, storedEvents: [] });
889+
},
890+
}),
891+
);
892+
893+
const result = yield* Effect.exit(
894+
dispatchCommand({
895+
type: "delegated_task.request",
896+
commandId,
897+
parentThreadId,
898+
parentRunId: RunId.make("run:delegation-replay"),
899+
parentNodeId: NodeId.make("node:delegation-replay"),
900+
task: "Review the change",
901+
targetAgentId: AgentId.make("non-existent-agent"),
902+
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
903+
runtimeMode: "full-access",
904+
interactionMode: "default",
905+
createdBy: "agent",
906+
creationSource: "mcp",
907+
}).pipe(Effect.provide(layer)),
908+
);
909+
910+
expect(result._tag).toBe("Success");
911+
expect(dispatched.length).toBe(1);
912+
}).pipe(Effect.provide(layerIntakeTest)),
913+
);

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,12 @@ const validateDelegatedTaskAgent = Effect.fn("ThreadMessageIntake.validateDelega
5858
command: Extract<OrchestrationV2Command, { readonly type: "delegated_task.request" }>,
5959
) {
6060
const threads = yield* ThreadManagement.ThreadManagementService;
61+
const existingReceipt = yield* threads
62+
.getCommandReceipt(command.commandId)
63+
.pipe(Effect.catchCause(() => Effect.succeed(null)));
64+
if (existingReceipt !== null && existingReceipt.status === "accepted") {
65+
return;
66+
}
6167
const parent = yield* threads.getThreadShell(command.parentThreadId);
6268
if (parent === null) return;
6369

‎apps/server/src/relay/AgentAwarenessRelay.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,7 @@ const makeTestRelay = Effect.fnUntraced(function* (
192192
}),
193193
readShellSnapshot: unused,
194194
ensureLegacyTranscript: unused,
195+
getCommandReceipt: unused,
195196
dispatch: unused,
196197
searchThread: () => Effect.die("unused"),
197198
searchThreadStream: () => Stream.empty,

‎apps/server/src/serverRuntimeStartup.ts‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -285,17 +285,15 @@ const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
285285
if (existingThread === undefined) {
286286
const serverSettings = yield* ServerSettings.ServerSettingsService;
287287
const settings = yield* serverSettings.getSettings;
288+
const projectSettings = resolveProjectSettings(settings, project.id, project).settings;
288289
const launched = yield* threadLaunch.launch({
289290
commandId: CommandId.make(yield* randomUUID),
290291
projectId: project.id,
291292
title: "New thread",
292-
modelSelection:
293-
resolveProjectSettings(settings, project.id, project).settings.defaultModelSelection ??
294-
threadModelSelection,
295-
modelSelectionExplicit: true,
293+
modelSelection: projectSettings.defaultModelSelection ?? threadModelSelection,
294+
modelSelectionExplicit: projectSettings.defaultModelSelection !== null,
296295
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
297-
runtimeMode: resolveProjectSettings(settings, project.id, project).settings
298-
.defaultRuntimeMode,
296+
runtimeMode: projectSettings.defaultRuntimeMode,
299297
workspaceStrategy: { type: "root" },
300298
createdBy: "system",
301299
creationSource: "server",

‎apps/web/src/components/chat/AgentPicker.test.tsx‎

Lines changed: 66 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -130,13 +130,75 @@ it("distinguishes inheriting the project default from explicitly choosing no age
130130

131131
expect(label()).toBe("Code Reviewer (Default)");
132132
act(() => renderer.root.findByProps({ "aria-label": "Select custom agent" }).props.onClick());
133-
choose("none");
133+
choose("control:none");
134134
expect(label()).toBe("No custom agent");
135135
act(() => renderer.root.findByProps({ "aria-label": "Select custom agent" }).props.onClick());
136-
expect(renderer.root.findByProps({ "data-value": "none" }).props["aria-checked"]).toBe(true);
136+
expect(renderer.root.findByProps({ "data-value": "control:none" }).props["aria-checked"]).toBe(
137+
true,
138+
);
137139

138-
choose("default");
140+
choose("control:default");
139141
expect(label()).toBe("Code Reviewer (Default)");
140142
act(() => renderer.root.findByProps({ "aria-label": "Select custom agent" }).props.onClick());
141-
expect(renderer.root.findByProps({ "data-value": "default" }).props["aria-checked"]).toBe(true);
143+
expect(renderer.root.findByProps({ "data-value": "control:default" }).props["aria-checked"]).toBe(
144+
true,
145+
);
146+
});
147+
148+
it("does not collide custom agents whose id is 'default' or 'none' with control options", () => {
149+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
150+
const collisionAgents: ReadonlyArray<AgentSummary> = [
151+
{
152+
id: AgentId.make("default"),
153+
name: "Default Named Agent",
154+
description: "Default description",
155+
},
156+
{
157+
id: AgentId.make("none"),
158+
name: "None Named Agent",
159+
description: "None description",
160+
},
161+
];
162+
163+
function CollisionHarness() {
164+
const [selectedAgentId, setSelectedAgentId] = useState<AgentId | null | undefined>(undefined);
165+
return (
166+
<AgentPicker
167+
agents={collisionAgents}
168+
selectedAgentId={selectedAgentId}
169+
onSelectAgent={setSelectedAgentId}
170+
allowNone
171+
/>
172+
);
173+
}
174+
175+
act(() => {
176+
renderer = create(<CollisionHarness />);
177+
});
178+
const label = () =>
179+
renderer.root.findByProps({ "data-composer-control-label": true }).children.join("");
180+
const choose = (value: string) => {
181+
const item = renderer.root.findByProps({ "data-value": value });
182+
act(() => item.props.onClick());
183+
};
184+
185+
// Select agent with id "default"
186+
act(() => renderer.root.findByProps({ "aria-label": "Select custom agent" }).props.onClick());
187+
choose("agent:default");
188+
expect(label()).toBe("Default Named Agent");
189+
190+
// Select agent with id "none"
191+
act(() => renderer.root.findByProps({ "aria-label": "Select custom agent" }).props.onClick());
192+
choose("agent:none");
193+
expect(label()).toBe("None Named Agent");
194+
195+
// Select control:none
196+
act(() => renderer.root.findByProps({ "aria-label": "Select custom agent" }).props.onClick());
197+
choose("control:none");
198+
expect(label()).toBe("No custom agent");
199+
200+
// Select control:default
201+
act(() => renderer.root.findByProps({ "aria-label": "Select custom agent" }).props.onClick());
202+
choose("control:default");
203+
expect(label()).toBe("Agent");
142204
});

0 commit comments

Comments
 (0)