Skip to content

Commit c430548

Browse files
committed
fix(server): distinguish requested child work from automatic wakes
1 parent f598302 commit c430548

9 files changed

Lines changed: 112 additions & 59 deletions

File tree

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
ProviderDriverKind,
99
ProviderInstanceId,
1010
RunId,
11+
ScheduledTaskId,
1112
ThreadId,
1213
type OrchestrationV2ThreadProjection,
1314
type ServerProvider,
@@ -111,7 +112,11 @@ describe("OrchestratorMcpService", () => {
111112
{
112113
id: MessageId.make("message:mcp-ack-monitor"),
113114
runId: monitorRunId,
114-
creationSource: "server",
115+
creationSource: wakeKind === "scheduled" ? "web" : "server",
116+
createdBy: wakeKind === "scheduled" ? "user" : "agent",
117+
...(wakeKind === "scheduled"
118+
? { scheduledTaskId: ScheduledTaskId.make("mcp-ack-schedule") }
119+
: {}),
115120
role: "user",
116121
...(wakeKind === "scheduled"
117122
? {}

‎apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts‎

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4196,14 +4196,16 @@ describe("orchestrator MCP toolkit", () => {
41964196
archivedIntake: false,
41974197
followupStatus,
41984198
})),
4199-
...(["server_wakes", "stop_idle", "stop_active"] as const).map((scenario) => ({
4200-
completionWake: "always" as const,
4201-
delayedDelivery: false,
4202-
closedCohort: false,
4203-
archivedIntake: false,
4204-
followupStatus: "completed" as const,
4205-
scenario,
4206-
})),
4199+
...(["server_wakes", "stop_idle", "stop_active", "user_answer"] as const).map(
4200+
(scenario) => ({
4201+
completionWake: "always" as const,
4202+
delayedDelivery: false,
4203+
closedCohort: false,
4204+
archivedIntake: false,
4205+
followupStatus: "completed" as const,
4206+
scenario,
4207+
}),
4208+
),
42074209
] as const
42084210
).map((testCase) => ({ scenario: "normal" as const, ...testCase })),
42094211
)(
@@ -4455,8 +4457,11 @@ describe("orchestrator MCP toolkit", () => {
44554457
);
44564458
yield* orchestrator.dispatch({
44574459
type: "message.dispatch",
4458-
createdBy: "agent",
4459-
creationSource: "server",
4460+
createdBy: source === undefined ? "user" : "agent",
4461+
creationSource: source === undefined ? "web" : "server",
4462+
...(source === undefined
4463+
? { scheduledTaskId: ScheduledTaskId.make("automatic-schedule") }
4464+
: {}),
44604465
commandId: CommandId.make(`wake-comparison:auto:${index}`),
44614466
threadId: worker.childThreadId!,
44624467
messageId: MessageId.make(`wake-comparison:auto:${index}`),
@@ -4490,8 +4495,8 @@ describe("orchestrator MCP toolkit", () => {
44904495
);
44914496
yield* orchestrator.dispatch({
44924497
type: "message.dispatch",
4493-
createdBy: "agent",
4494-
creationSource: "mcp",
4498+
createdBy: scenario === "user_answer" ? "user" : "agent",
4499+
creationSource: scenario === "user_answer" ? "server" : "mcp",
44954500
commandId: CommandId.make(`wake-comparison:followup:${index}`),
44964501
threadId: worker.childThreadId!,
44974502
messageId: MessageId.make(`wake-comparison:followup:${index}`),

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4713,7 +4713,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
47134713
parentThreadId !== null &&
47144714
projection.thread.lineage.relationshipToParent === "subagent" &&
47154715
childOrigin?.type === "node" &&
4716-
command.creationSource !== "server"
4716+
command.notification === undefined &&
4717+
command.scheduledTaskId === undefined &&
4718+
(command.creationSource !== "server" || command.createdBy === "user")
47174719
) {
47184720
const pendingTask = (yield* Ref.get(events)).findLast(
47194721
(event) =>

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
RuntimeRequestId,
2121
RunAttemptId,
2222
RunId,
23+
ScheduledTaskId,
2324
ThreadId,
2425
TurnItemId,
2526
type ThreadPullRequestLink,
@@ -544,6 +545,13 @@ const followUpResultRecovery = Effect.gen(function* () {
544545
...(yield* store.getThreadProjection(childId)).messages.at(-1)!,
545546
id: wake.userMessageId,
546547
runId: wake.id,
548+
...(source === undefined
549+
? {
550+
creationSource: "web",
551+
createdBy: "user",
552+
scheduledTaskId: ScheduledTaskId.make("automatic-schedule"),
553+
}
554+
: {}),
547555
notification:
548556
source === undefined
549557
? undefined

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

Lines changed: 37 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -3517,8 +3517,10 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
35173517
WHERE message.thread_id = child.thread_id
35183518
AND message.message_id = json_extract(terminal.payload_json, '$.userMessageId')
35193519
AND CASE WHEN json_valid(message.payload_json) THEN
3520-
json_extract(message.payload_json, '$.notification.source.kind') = 'monitor'
3520+
json_extract(message.payload_json, '$.notification') IS NOT NULL
3521+
OR json_extract(message.payload_json, '$.scheduledTaskId') IS NOT NULL
35213522
OR (json_extract(message.payload_json, '$.creationSource') = 'server'
3523+
AND json_extract(message.payload_json, '$.createdBy') IS NOT 'user'
35223524
AND NOT (
35233525
(terminal.ordinal = 1 AND json_extract(message.payload_json, '$.notification') IS NULL)
35243526
OR json_extract(terminal.payload_json, '$.restartContinuationOfRunId') IS NOT NULL
@@ -6304,42 +6306,40 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
63046306
),
63056307
getThreadSnapshotWindow: (threadId, options) =>
63066308
service.getThreadSnapshot(threadId).pipe(
6307-
Effect.flatMap((snapshot) =>
6308-
Effect.gen(function* () {
6309-
const anchorIndex =
6310-
options.anchorItemId === undefined
6311-
? snapshot.projection.visibleTurnItems.length
6312-
: snapshot.projection.visibleTurnItems.findIndex(
6313-
(row) => row.sourceItemId === options.anchorItemId,
6314-
) + 1;
6315-
const candidates = snapshot.projection.visibleTurnItems.slice(0, anchorIndex);
6316-
const turnAnchors =
6317-
options.userTurnLimit === undefined
6318-
? []
6319-
: candidates.flatMap((row, index) =>
6320-
isThreadHistoryTurnStart(row.item) ? [index] : [],
6321-
);
6322-
const rawStart = turnAnchors.at(-(THREAD_HISTORY_MAX_RAW_TURNS + 2)) ?? 0;
6323-
const anchors = turnAnchors.filter(
6324-
(index) => index >= rawStart && isThreadHistoryUserTurn(candidates[index]!.item),
6325-
);
6326-
const anchorLimit = (options.userTurnLimit ?? 0) + 2;
6327-
const start =
6328-
anchors.length > 0
6329-
? anchors.length < anchorLimit
6330-
? rawStart
6331-
: anchors.at(-anchorLimit)!
6332-
: Math.max(0, anchorIndex - options.rowLimit);
6333-
const visibleTurnItems = candidates.slice(start);
6334-
return {
6335-
...snapshot,
6336-
projection: {
6337-
...snapshot.projection,
6338-
visibleTurnItems,
6339-
},
6340-
};
6341-
}),
6342-
),
6309+
Effect.map((snapshot) => {
6310+
const anchorIndex =
6311+
options.anchorItemId === undefined
6312+
? snapshot.projection.visibleTurnItems.length
6313+
: snapshot.projection.visibleTurnItems.findIndex(
6314+
(row) => row.sourceItemId === options.anchorItemId,
6315+
) + 1;
6316+
const candidates = snapshot.projection.visibleTurnItems.slice(0, anchorIndex);
6317+
const turnAnchors =
6318+
options.userTurnLimit === undefined
6319+
? []
6320+
: candidates.flatMap((row, index) =>
6321+
isThreadHistoryTurnStart(row.item) ? [index] : [],
6322+
);
6323+
const rawStart = turnAnchors.at(-(THREAD_HISTORY_MAX_RAW_TURNS + 2)) ?? 0;
6324+
const anchors = turnAnchors.filter(
6325+
(index) => index >= rawStart && isThreadHistoryUserTurn(candidates[index]!.item),
6326+
);
6327+
const anchorLimit = (options.userTurnLimit ?? 0) + 2;
6328+
const start =
6329+
anchors.length > 0
6330+
? anchors.length < anchorLimit
6331+
? rawStart
6332+
: anchors.at(-anchorLimit)!
6333+
: Math.max(0, anchorIndex - options.rowLimit);
6334+
const visibleTurnItems = candidates.slice(start);
6335+
return {
6336+
...snapshot,
6337+
projection: {
6338+
...snapshot.projection,
6339+
visibleTurnItems,
6340+
},
6341+
};
6342+
}),
63436343
),
63446344
};
63456345

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

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -206,21 +206,28 @@ export function subagentResultForRun(
206206
};
207207
}
208208

209-
/** Requested task work excludes automatic wakes. Restart continuations retain their source work. */
209+
/** Task results follow requested work, explicit user answers, and its restart continuations.
210+
* Notification and scheduled wakes cannot replace that work.
211+
*/
210212
export function delegatedWorkRuns(projection: {
211213
readonly runs: OrchestrationV2ThreadProjection["runs"];
212214
readonly messages: ReadonlyArray<
213-
Pick<OrchestrationV2ConversationMessage, "id" | "runId" | "creationSource" | "notification">
215+
Pick<
216+
OrchestrationV2ConversationMessage,
217+
"id" | "runId" | "createdBy" | "creationSource" | "notification" | "scheduledTaskId"
218+
>
214219
>;
215220
}) {
216221
const requests = new Map(projection.messages.map((message) => [message.id, message]));
217222
const workRunIds = new Set<OrchestrationV2Run["id"]>();
218223
for (const run of projection.runs.toSorted((a, b) => a.ordinal - b.ordinal)) {
219224
const request = requests.get(run.userMessageId);
220225
if (
221-
request?.notification?.source.kind !== "monitor" &&
226+
request?.notification === undefined &&
227+
request?.scheduledTaskId === undefined &&
222228
(request?.creationSource !== "server" ||
223-
(run.ordinal === 1 && request.notification === undefined) ||
229+
request.createdBy === "user" ||
230+
run.ordinal === 1 ||
224231
(run.restartContinuationOfRunId !== undefined &&
225232
workRunIds.has(run.restartContinuationOfRunId)))
226233
)
@@ -233,7 +240,10 @@ export function delegatedWorkRuns(projection: {
233240
export function delegatedTaskProgress(projection: {
234241
readonly runs: OrchestrationV2ThreadProjection["runs"];
235242
readonly messages: ReadonlyArray<
236-
Pick<OrchestrationV2ConversationMessage, "id" | "runId" | "creationSource" | "notification">
243+
Pick<
244+
OrchestrationV2ConversationMessage,
245+
"id" | "runId" | "createdBy" | "creationSource" | "notification" | "scheduledTaskId"
246+
>
237247
>;
238248
readonly subagents: ReadonlyArray<
239249
Pick<OrchestrationV2ThreadProjection["subagents"][number], "status" | "completionDelivery">

‎apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -438,7 +438,7 @@ export function layerWithRegistry<Error>(
438438
Layer.provide(layerOrchestratorProvided),
439439
Layer.provide(
440440
Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({
441-
ensureTranscript: () => Effect.void,
441+
ensureTranscript: () => Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
442442
}),
443443
),
444444
);

‎packages/client-runtime/src/operations/commands.test.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -610,8 +610,26 @@ describe("V2 environment commands", () => {
610610
},
611611
],
612612
};
613+
// Keep the interrupt target compatible with older servers while a queue
614+
// exists. The current server still selects live work under its own lock.
615+
const queuedProjection = {
616+
...projection,
617+
runs: [
618+
...projection.runs,
619+
{
620+
...projection.runs[0]!,
621+
id: RunId.make("queued-after-active"),
622+
ordinal: 2,
623+
status: "queued" as const,
624+
},
625+
],
626+
};
613627
const commands: OrchestrationV2Command[] = [];
614-
const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
628+
const supervisor = yield* makeSupervisor({
629+
commands,
630+
projects: [],
631+
projection: queuedProjection,
632+
});
615633

616634
const result = yield* interruptThreadTurn({ threadId: v2ThreadId }).pipe(
617635
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),

‎packages/client-runtime/src/operations/commands.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -782,7 +782,12 @@ export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThrea
782782
let runId = input.runId ?? (input.turnId as RunId | undefined);
783783
if (runId === undefined) {
784784
const parentProjection = yield* getProjection(input.threadId);
785-
runId = parentProjection.runs.at(-1)?.id;
785+
runId =
786+
parentProjection.runs.findLast((run) =>
787+
["preparing", "starting", "running", "waiting"].includes(run.status),
788+
)?.id ??
789+
parentProjection.runs.findLast((run) => run.status !== "queued")?.id ??
790+
parentProjection.runs.at(-1)?.id;
786791
if (runId === undefined) {
787792
let result = { sequence: 0 };
788793
for (const link of visibleThreadPullRequests(parentProjection.thread.pullRequests ?? [])) {

0 commit comments

Comments
 (0)