From 87ece8c7e20f5479470ee97b7e8a2be88f704b9a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 04:23:08 +0000 Subject: [PATCH] fix(server): thread reads no longer load every run of the thread t3_thread_read decoded every run, provider turn and runtime request of the thread before trimming to runLimit, and its timeline page decoded every run and run attempt to decide row visibility. A read cost time proportional to the thread's history. The read now loads the runLimit newest runs plus active runs, the provider turns of those runs' active attempts, pending requests only, and a COUNT(*) for runCount. A caller reading its own subagent thread still loads everything, since acknowledging a task result matches every run. The local timeline reads only the rolled-back, queued and cancelled runs and the superseded attempts that can hide rows, as plain columns, and joins each row's run status. Co-Authored-By: Claude Opus 5.5 --- .../OrchestratorMcpService.activity.test.ts | 5 ++ apps/server/src/mcp/OrchestratorMcpService.ts | 60 +++++++++++---- apps/server/src/mcp/toolkits/core.test.ts | 1 + .../src/orchestration-v2/Orchestrator.ts | 6 ++ .../orchestration-v2/ProjectionStore.test.ts | 25 ++++++ .../src/orchestration-v2/ProjectionStore.ts | 77 ++++++++++++++----- .../ProviderTurnControlService.test.ts | 1 + .../ThreadManagementService.ts | 6 ++ apps/server/src/peer/RemoteDelegation.test.ts | 2 + .../src/relay/AgentAwarenessRelay.test.ts | 1 + 10 files changed, 149 insertions(+), 35 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts index 742b5969b64cb..4a7b08fbd870b 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts @@ -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), ServerSettings.layerTest(), Layer.mock(ProviderRegistry.ProviderRegistry)({ @@ -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), @@ -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), @@ -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), @@ -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)) diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index b7908d1d74878..7fd6e0888daf5 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -973,6 +973,7 @@ function listItemFromShell( function threadDetail( scope: McpInvocationScope, projection: Pick, + runCount: number, itemCount: number, shell: OrchestrationV2ThreadShell, nowMs: number, @@ -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", @@ -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 @@ -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; @@ -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; @@ -3341,6 +3366,7 @@ const make = Effect.gen(function* () { const thread = threadDetail( scope, target, + runCount, timeline.totalItems, shell, yield* Clock.currentTimeMillis, @@ -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 }, diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index 81614e5eb4274..6a98097e8fa47 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -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) => diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 27b7a2e12878d..ce23a7704ac13 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -435,6 +435,7 @@ export interface OrchestratorV2Shape { options: ProjectionTimelinePageOptions, ) => Effect.Effect; readonly getMessageCount: (threadId: ThreadId) => Effect.Effect; + readonly getRunCount: (threadId: ThreadId) => Effect.Effect; readonly getMessagesById: ( threadId: ThreadId, messageIds: ReadonlyArray, @@ -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) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index b961ef1e0dc34..2c667bf43679f 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -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 diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 289bdce2276c0..73b3d7dd5f8d2 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -363,6 +363,8 @@ export interface ProjectionRecordFilter { readonly runStatuses?: ReadonlyArray; /** Keeps the thread's highest-ordinal run even when `runStatuses` excludes it. */ readonly includeLatestRun?: true; + /** The thread's N highest-ordinal runs, plus any run `runStatuses` matches. Ignores `includeLatestRun`. */ + readonly latestRunLimit?: number; readonly providerTurnThreadIds?: ReadonlyArray; /** Only the provider turn whose token usage was updated last. */ readonly latestProviderTurnUsageOnly?: true; @@ -536,6 +538,7 @@ export interface ProjectionStoreV2Shape { limit: number, ) => Effect.Effect; readonly getSubagentCount: (threadId: ThreadId) => Effect.Effect; + readonly getRunCount: (threadId: ThreadId) => Effect.Effect; /** Child threads of the thread's app-owned tasks, in task order, without decoding the tasks. */ readonly listAppOwnedChildThreadIds: ( threadId: ThreadId, @@ -3925,23 +3928,43 @@ export const layer: Layer.Layer = (fields !== undefined && !fields.includes("runs")) || (window === undefined && (matchesNothing(filter?.runIds) || - (matchesNothing(filter?.runStatuses) && filter?.includeLatestRun !== true))) + (matchesNothing(filter?.runStatuses) && + filter?.includeLatestRun !== true && + filter?.latestRunLimit === undefined))) ? Effect.succeed([]) : window === undefined ? sql` SELECT payload_json FROM orchestration_v2_projection_runs - WHERE ${threadColumn(filter?.runIds)} = ${threadId} + WHERE ${threadColumn(filter?.latestRunLimit === undefined ? filter?.runIds : [])} = ${threadId} ${filter?.runIds === undefined ? sql`` : sql`AND run_id IN (SELECT value FROM json_each(${encodeIdList(filter.runIds)}))`} ${ - filter?.runStatuses === undefined - ? sql`ORDER BY ordinal ASC` - : filter.includeLatestRun !== true - ? // `+ordinal` stops SQLite from walking every run in the (thread_id, ordinal) - // index to skip a sort; a status index reads only matching runs. - sql`AND status IN (SELECT value FROM json_each(${encodeIdList(filter.runStatuses)})) + filter?.latestRunLimit !== undefined + ? sql`AND run_id IN ( + SELECT run_id FROM ( + SELECT run_id FROM orchestration_v2_projection_runs + WHERE thread_id = ${threadId} + ORDER BY ordinal DESC + LIMIT ${filter.latestRunLimit} + ) + ${ + filter.runStatuses === undefined + ? sql`` + : sql`UNION + SELECT run_id FROM orchestration_v2_projection_runs + WHERE thread_id = ${threadId} + AND status IN (SELECT value FROM json_each(${encodeIdList(filter.runStatuses)}))` + } + ) + ORDER BY ordinal ASC` + : filter?.runStatuses === undefined + ? sql`ORDER BY ordinal ASC` + : filter.includeLatestRun !== true + ? // `+ordinal` stops SQLite from walking every run in the (thread_id, ordinal) + // index to skip a sort; a status index reads only matching runs. + sql`AND status IN (SELECT value FROM json_each(${encodeIdList(filter.runStatuses)})) ORDER BY +ordinal ASC` - : sql`AND (status IN (SELECT value FROM json_each(${encodeIdList(filter.runStatuses)})) + : sql`AND (status IN (SELECT value FROM json_each(${encodeIdList(filter.runStatuses)})) OR run_id = ( SELECT run_id FROM orchestration_v2_projection_runs WHERE thread_id = ${threadId} @@ -6317,6 +6340,13 @@ export const layer: Layer.Layer = Effect.map((rows) => rows[0]?.bytes ?? 0), Effect.mapError(controlReadError(threadId)), ); + const getRunCount: ProjectionStoreV2Shape["getRunCount"] = (threadId) => + sql<{ + count: number; + }>`SELECT COUNT(*) AS count FROM orchestration_v2_projection_runs WHERE thread_id = ${threadId}`.pipe( + Effect.map((rows) => rows[0]?.count ?? 0), + Effect.mapError(controlReadError(threadId)), + ); const getSubagentCount: ProjectionStoreV2Shape["getSubagentCount"] = (threadId) => sql<{ count: number; @@ -6804,7 +6834,6 @@ export const layer: Layer.Layer = */ const readTimelineWindow = Effect.fn("ProjectionStore.readTimelineWindow")(function* ( threadId: ThreadId, - runs: ProjectionRecords<"runs">["runs"], includePersistentOutput: boolean, where: Statement.Fragment, limit: Statement.Fragment = sql``, @@ -6823,7 +6852,9 @@ export const layer: Layer.Layer = persistent_output: number; attempt_id: string | null; attempt_status: string | null; + run_status: OrchestrationV2Run["status"] | null; }>`SELECT item.turn_item_id, item.run_id, item.node_id, item.parent_item_id, item.type, item.status, item.ordinal, + run.status AS run_status, ${includePersistentOutput ? sql`attempt.attempt_id` : sql`NULL`} AS attempt_id, ${includePersistentOutput ? sql`attempt.status` : sql`NULL`} AS attempt_status, ${includePersistentOutput ? sql`item.inline_work_output` : sql`0`} AS persistent_output, @@ -6831,6 +6862,7 @@ export const layer: Layer.Layer = CASE WHEN item.type = 'user_message' THEN json_extract(item.payload_json, '$.createdBy') END AS created_by, CASE WHEN item.type IN ('user_message', 'assistant_message') THEN json_extract(item.payload_json, '$.messageId') END AS message_id FROM orchestration_v2_projection_turn_items AS item + LEFT JOIN orchestration_v2_projection_runs AS run ON run.run_id = item.run_id ${ includePersistentOutput ? sql`LEFT JOIN orchestration_v2_projection_nodes AS node ON node.node_id = item.node_id @@ -6843,7 +6875,6 @@ export const layer: Layer.Layer = } WHERE item.thread_id = ${threadId} ${where} ORDER BY item.ordinal ASC, item.turn_item_id ASC ${limit}`; - const runStatuses = new Map(runs.map((run) => [String(run.id), run.status])); return rows.map((row): TimelineIndexItem => ({ id: TurnItemId.make(row.turn_item_id), threadId, @@ -6853,7 +6884,7 @@ export const layer: Layer.Layer = type: row.type, status: row.status, ordinal: row.ordinal, - runStatus: row.run_id === null ? undefined : runStatuses.get(row.run_id), + runStatus: row.run_status ?? undefined, attemptId: row.attempt_id, attemptStatus: row.attempt_status, persistentOutput: row.persistent_output === 1, @@ -6895,9 +6926,18 @@ export const layer: Layer.Layer = AND NOT (json_extract(payload_json, '$.forkedFrom.type') IS 'run' AND json_extract(payload_json, '$.lineage.sideChat') IS NOT 1)`; if (ownRowsOnly.length === 0) return null; - const records = yield* getThreadRecords(threadId, ["runs", "attempts"]); + const records = yield* getThreadRecords(threadId, []); if (inheritedRunFork(records.thread) !== null) return null; - const superseded = records.attempts.filter((attempt) => attempt.status === "superseded"); + // Only these runs and attempts can hide rows, and their columns are all visibility reads. + const [hidingRuns, superseded] = yield* Effect.all([ + sql<{ id: RunId; status: OrchestrationV2Run["status"] }>` + SELECT run_id AS id, status FROM orchestration_v2_projection_runs + WHERE thread_id = ${threadId} AND status IN ('rolled_back', 'queued', 'cancelled')`, + sql<{ runId: RunId; rootNodeId: NodeId; status: "superseded" }>` + SELECT run_id AS runId, root_node_id AS rootNodeId, status + FROM orchestration_v2_projection_run_attempts + WHERE thread_id = ${threadId} AND status = 'superseded'`, + ]); const stopRequests = superseded.length === 0 ? [] @@ -6905,8 +6945,8 @@ export const layer: Layer.Layer = SELECT DISTINCT run_id FROM orchestration_v2_projection_turn_items WHERE thread_id = ${threadId} AND type = 'run_interrupt_request'`; const isVisible = createOrchestrationV2TurnItemVisibility({ - runs: records.runs, - attempts: records.attempts, + runs: hidingRuns, + attempts: superseded, items: stopRequests.map((row) => ({ type: "run_interrupt_request" as const, runId: row.run_id === null ? null : RunId.make(row.run_id), @@ -6918,7 +6958,7 @@ export const layer: Layer.Layer = // are found without reading the thread. const stoppedRuns = new Set(stopRequests.map((row) => row.run_id)); const runsWithStatus = (...statuses: ReadonlyArray) => - records.runs.flatMap((run) => (statuses.includes(run.status) ? [String(run.id)] : [])); + hidingRuns.flatMap((run) => (statuses.includes(run.status) ? [String(run.id)] : [])); const rolledBack = runsWithStatus("rolled_back"); const heldInput = runsWithStatus("queued", "cancelled"); const steered = [...new Set(superseded.map((attempt) => String(attempt.runId)))].filter( @@ -6990,7 +7030,7 @@ export const layer: Layer.Layer = hidden, visibleBefore, read: (where: Statement.Fragment, limit?: Statement.Fragment) => - readTimelineWindow(threadId, records.runs, includePersistentOutput, where, limit), + readTimelineWindow(threadId, includePersistentOutput, where, limit), }; }); type LocalTimeline = NonNullable>>; @@ -9373,6 +9413,7 @@ export const layer: Layer.Layer = getMessageCount: readOnReader(getMessageCount), getTranscriptByteFloor: readOnReader(getTranscriptByteFloor), getSubagentCount: readOnReader(getSubagentCount), + getRunCount: readOnReader(getRunCount), listAppOwnedChildThreadIds: readOnReader(listAppOwnedChildThreadIds), hasPendingDelegatedCompletion: readOnReader(hasPendingDelegatedCompletion), getNextTurnItemOrdinal: readOnReader(getNextTurnItemOrdinal), diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index 069e36ceef916..48eacd6bbd18f 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -247,6 +247,7 @@ it.effect( getTranscriptByteFloor: () => Effect.die("unused transcript byte floor"), hasPendingDelegatedCompletion: () => Effect.die("unused hasPendingDelegatedCompletion"), getSubagentCount: () => Effect.die("unused subagent count"), + getRunCount: () => Effect.die("unused run count"), listAppOwnedChildThreadIds: () => Effect.die("unused listAppOwnedChildThreadIds"), getNextTurnItemOrdinal: () => Effect.die("unused ordinal read"), getTurnItem: () => Effect.die("unused turn item read"), diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 611d9a3244f24..bfd676d7a3a22 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -405,6 +405,7 @@ export interface ThreadManagementServiceShape { readonly getThreadHistoryPage: Orchestrator.OrchestratorV2["Service"]["getThreadHistoryPage"]; readonly getTimelinePage: Orchestrator.OrchestratorV2["Service"]["getTimelinePage"]; readonly getMessageCount: Orchestrator.OrchestratorV2["Service"]["getMessageCount"]; + readonly getRunCount: Orchestrator.OrchestratorV2["Service"]["getRunCount"]; readonly getMessagesById: Orchestrator.OrchestratorV2["Service"]["getMessagesById"]; readonly getTurnItem: (input: { readonly threadId: ThreadId; @@ -1720,6 +1721,11 @@ const make = Effect.gen(function* () { Effect.andThen(orchestrator.getMessageCount(threadId)), ); }), + getRunCount: Effect.fn("ThreadManagementService.getRunCount")(function (threadId) { + return ensureProjectionTranscript(threadId).pipe( + Effect.andThen(orchestrator.getRunCount(threadId)), + ); + }), getMessagesById: Effect.fn("ThreadManagementService.getMessagesById")( function (threadId, messageIds) { return ensureProjectionTranscript(threadId).pipe( diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts index 90c6eb83baae5..34e021cc798d0 100644 --- a/apps/server/src/peer/RemoteDelegation.test.ts +++ b/apps/server/src/peer/RemoteDelegation.test.ts @@ -280,6 +280,8 @@ const boxToolkitLayer = (thread: BoxThread) => { getThreadShell: shellOf, getProjectThreadRecords: (input) => projectionOf(input.threadId), getThreadRecords: (threadId) => projectionOf(threadId), + getRunCount: (threadId) => + projectionOf(threadId).pipe(Effect.map((projection) => projection.runs.length)), waitForThread: (input) => Effect.gen(function* () { yield* Ref.update(thread.waitedFor, (seen) => [...seen, input.runId]); diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts index 10388e99fe7c5..5cde458a1cd30 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.test.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts @@ -238,6 +238,7 @@ const makeTestRelay = Effect.fnUntraced(function* ( getThreadHistoryPage: () => Effect.die("unused"), getTimelinePage: () => Effect.die("Unused timeline read"), getMessageCount: () => Effect.die("unused message count"), + getRunCount: () => Effect.die("unused run count"), getMessagesById: () => Effect.die("unused messages by id"), getTurnItem: () => Effect.die("unused turn item read"), getThreadRecords: () => Effect.die("unused record read"),