Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions apps/server/src/mcp/OrchestratorMcpService.activity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ it("readThread preserves caller access errors and prefers activity-run status ov
input.threadId === parentThreadId
? Effect.succeed(projection)
: Effect.die(`unexpected thread ${input.threadId}`),
getRunCount: () => Effect.succeed(projection.runs.length),
} satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
ServerSettings.layerTest(),
Layer.mock(ProviderRegistry.ProviderRegistry)({
Expand Down Expand Up @@ -364,6 +365,7 @@ it("readThread pages cut-off text without splitting an emoji across pages", asyn
},
getThreadRecords: () => Effect.succeed(projection),
getProjectThreadRecords: () => Effect.succeed(projection),
getRunCount: () => Effect.succeed(projection.runs.length),
getThreadShell: () =>
Effect.succeed(projection.thread as unknown as OrchestrationV2ThreadShell),
} satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
Expand Down Expand Up @@ -471,6 +473,7 @@ it("readThread returns the newest items that fit the response budget", async ()
},
getThreadRecords: () => Effect.succeed(projection),
getProjectThreadRecords: () => Effect.succeed(projection),
getRunCount: () => Effect.succeed(projection.runs.length),
getThreadShell: () =>
Effect.succeed(projection.thread as unknown as OrchestrationV2ThreadShell),
} satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
Expand Down Expand Up @@ -577,6 +580,7 @@ it("readThread keeps an activity page within an MCP client's output limit and pa
},
getThreadRecords: () => Effect.succeed(projection),
getProjectThreadRecords: () => Effect.succeed(projection),
getRunCount: () => Effect.succeed(projection.runs.length),
getThreadShell: () =>
Effect.succeed(projection.thread as unknown as OrchestrationV2ThreadShell),
} satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
Expand Down Expand Up @@ -858,6 +862,7 @@ it("readThread and sendToThread reach threads in other projects", async () => {
hasMore: false,
hasEarlier: false,
}),
getRunCount: (threadId) => Effect.succeed(foreignProjection(threadId).runs.length),
getProjectThreadRecords: (input) =>
input.threadId === foreignThreadId && input.projectId === foreignProjectId
? Effect.succeed(foreignProjection(input.threadId))
Expand Down
60 changes: 43 additions & 17 deletions apps/server/src/mcp/OrchestratorMcpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -973,6 +973,7 @@ function listItemFromShell(
function threadDetail(
scope: McpInvocationScope,
projection: Pick<OrchestrationV2ThreadProjection, "thread" | "runs" | "runtimeRequests">,
runCount: number,
itemCount: number,
shell: OrchestrationV2ThreadShell,
nowMs: number,
Expand Down Expand Up @@ -1018,7 +1019,7 @@ function threadDetail(
...(projection.thread.delegatedFrom == null
? {}
: { delegatedFrom: projection.thread.delegatedFrom }),
runCount: projection.runs.length,
runCount,
itemCount,
pendingRequestCount: projection.runtimeRequests.filter(
(request) => request.status === "pending",
Expand Down Expand Up @@ -1464,6 +1465,7 @@ const make = Effect.gen(function* () {
const loadReadableThread = Effect.fn("OrchestratorMcpService.loadReadableThread")(function* (
scope: McpInvocationScope,
threadId: ThreadId,
runLimit: number,
) {
const { parent } = yield* loadCaller(scope, []);
const shell = yield* threadManagement
Expand All @@ -1478,20 +1480,38 @@ const make = Effect.gen(function* () {
);
}
const input = { projectId: shell.projectId, threadId };
// Transfers are needed only to acknowledge a caller's child-task result.
const records =
parent === undefined
? threadManagement
.getProjectThreadRecords(input, ["runs", "providerTurns", "runtimeRequests"])
.pipe(Effect.map((target) => ({ ...target, contextTransfers: [] })))
: threadManagement.getProjectThreadRecords(input, [
"runs",
"providerTurns",
"runtimeRequests",
"contextTransfers",
]);
const target = yield* records.pipe(Effect.mapError(threadManagementFailure));
return { parent, target, shell } as const;
// Acknowledging a caller's child-task result matches it against every run and transfer.
if (
parent !== undefined &&
shell.lineage.parentThreadId === parent.thread.id &&
shell.lineage.relationshipToParent === "subagent"
) {
const target = yield* threadManagement
.getProjectThreadRecords(input, [
"runs",
"providerTurns",
"runtimeRequests",
"contextTransfers",
])
.pipe(Effect.mapError(threadManagementFailure));
return { parent, target, shell, runCount: target.runs.length } as const;
}
// Long threads hold thousands of runs; the read shows only the recent and active ones.
const [records, runCount] = yield* Effect.all([
threadManagement.getProjectThreadRecords(input, ["runs", "runtimeRequests"], {
latestRunLimit: runLimit,
runStatuses: ThreadManagementService.ACTIVE_RUN_STATUSES,
runtimeRequestStatuses: ["pending"],
}),
threadManagement.getRunCount(threadId),
]).pipe(Effect.mapError(threadManagementFailure));
const { providerTurns } = yield* threadManagement
.getProjectThreadRecords(input, ["providerTurns"], {
providerTurnAttemptIds: records.runs.flatMap((run) => run.activeAttemptId ?? []),
})
.pipe(Effect.mapError(threadManagementFailure));
const target = { ...records, providerTurns, contextTransfers: [] };
return { parent, target, shell, runCount } as const;
});

const loadProviders = providerRegistry.getProviders;
Expand Down Expand Up @@ -3302,7 +3322,12 @@ const make = Effect.gen(function* () {
} satisfies OrchestratorMcpThreadListResult;
}),
readThread: Effect.fn("OrchestratorMcpService.readThread")(function* (scope, input) {
const { parent, target, shell } = yield* loadReadableThread(scope, input.threadId);
const runLimit = input.runLimit ?? DEFAULT_THREAD_RUN_LIMIT;
const { parent, target, shell, runCount } = yield* loadReadableThread(
scope,
input.threadId,
runLimit,
);
const view = input.view ?? "messages";
const limit = input.limit ?? DEFAULT_THREAD_READ_LIMIT;
const maxChars = input.maxCharsPerItem ?? DEFAULT_THREAD_ITEM_MAX_CHARS;
Expand Down Expand Up @@ -3341,6 +3366,7 @@ const make = Effect.gen(function* () {
const thread = threadDetail(
scope,
target,
runCount,
timeline.totalItems,
shell,
yield* Clock.currentTimeMillis,
Expand All @@ -3350,7 +3376,7 @@ const make = Effect.gen(function* () {
);
const recentRuns = target.runs
.toSorted((left, right) => right.ordinal - left.ordinal)
.slice(0, input.runLimit ?? DEFAULT_THREAD_RUN_LIMIT)
.slice(0, runLimit)
.map((run) => threadRun(target, run));
const { items, start } = timelineItemsWithinBudget(
{ thread, recentRuns, nextPosition: null, hasMore: false, earlierPosition: null },
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/mcp/toolkits/core.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1336,6 +1336,7 @@ it.effect("discovers workflow stop targets and requires orchestration capability
getThreadShell: (id) => Effect.succeed(McpToolAccessTestkit.liveThreadShell(id)),
getProjectThreadRecords: () =>
Effect.succeed(McpToolAccessTestkit.idleThreadProjection(shell)),
getRunCount: () => Effect.succeed(1),
getTimelinePage: () =>
Effect.succeed({ items: [row], totalItems: 1, hasMore: false, hasEarlier: false }),
stopWorkflow: (input) =>
Expand Down
6 changes: 6 additions & 0 deletions apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,7 @@ export interface OrchestratorV2Shape {
options: ProjectionTimelinePageOptions,
) => Effect.Effect<ProjectionTimelinePage, OrchestratorProjectionError>;
readonly getMessageCount: (threadId: ThreadId) => Effect.Effect<number, OrchestratorV2Error>;
readonly getRunCount: (threadId: ThreadId) => Effect.Effect<number, OrchestratorV2Error>;
readonly getMessagesById: (
threadId: ThreadId,
messageIds: ReadonlyArray<MessageId>,
Expand Down Expand Up @@ -16264,6 +16265,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
.getMessageCount(threadId)
.pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));
}),
getRunCount: Effect.fn("OrchestratorV2.getRunCount")(function (threadId) {
return projectionStore
.getRunCount(threadId)
.pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));
}),
getMessagesById: Effect.fn("OrchestratorV2.getMessagesById")(function (threadId, messageIds) {
return projectionStore
.getMessagesById(threadId, messageIds)
Expand Down
25 changes: 25 additions & 0 deletions apps/server/src/orchestration-v2/ProjectionStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -729,6 +729,31 @@ it.effect("idle compaction filters keep the latest run, live work and the newest
.join("\n");
assert.notInclude(runPlan, "orchestration_v2_projection_runs_thread_ordinal_idx");
assert.match(runPlan, /SEARCH orchestration_v2_projection_runs USING INDEX \w*status\w*/);
// The newest runs by ordinal, whatever their status, plus older runs the statuses match.
for (const [filter, expected] of [
[{ latestRunLimit: 2 }, [4, 5]],
[{ latestRunLimit: 2, runStatuses: ["rolled_back"] as const }, [1, 4, 5]],
] as const) {
const traced = traceSqlStatements();
const recent = yield* store
.getThreadRecords(threadId, ["runs"], filter)
.pipe(Effect.withTracer(traced.tracer));
assert.deepEqual(
recent.runs.map((run) => run.ordinal),
[...expected],
);
const recentQuery = traced.statements.find((statement) =>
statement.includes("FROM orchestration_v2_projection_runs"),
);
assert.isDefined(recentQuery);
// Fetches the chosen runs by key instead of walking every run of the thread.
assert.match(
(yield* sql.unsafe<{ readonly detail: string }>(`EXPLAIN QUERY PLAN ${recentQuery}`))
.map((row) => row.detail)
.join("\n"),
/^SEARCH orchestration_v2_projection_runs USING INDEX \w+ \(run_id=\?\)/,
);
}
// An id filter reads by primary key, not every row of the thread.
const byId = traceSqlStatements();
const found = yield* store
Expand Down
Loading
Loading