Skip to content
Open
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
77 changes: 76 additions & 1 deletion apps/server/src/orchestration-v2/ProjectionSettlement.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,28 @@ it.effect(
yield* createRun(yield* createThread(status), status);
}
const queued = yield* createThread("queued");
yield* createRun(queued, "queued");
const queuedRunId = yield* createRun(queued, "queued");
// thread.settle drops an automatic queued message, so the thread stays a candidate.
yield* store.apply({
id: EventId.make("event:settlement:queued:message"),
type: "message.updated",
threadId: queued,
occurredAt: old,
payload: {
createdBy: "agent",
creationSource: "mcp",
id: MessageId.make(`message:${queuedRunId}`),
threadId: queued,
runId: null,
nodeId: null,
role: "user",
text: "Queued by an agent",
attachments: [],
streaming: false,
createdAt: old,
updatedAt: old,
},
});
const blocked = yield* createThread("blocked");
yield* store.apply({
id: EventId.make("event:settlement:request"),
Expand Down Expand Up @@ -370,6 +391,60 @@ it.effect(
}).pipe(Effect.provide(layerSql)),
);

it.effect("sql: a failed thread holding a queued user message is not a settlement candidate", () =>
Effect.gen(function* () {
const store = yield* ProjectionStore.ProjectionStoreV2;
const threadId = yield* createThread("failed-with-queued");
const failedRunId = yield* createRun(threadId, "failed");
const messageId = MessageId.make("message:settlement:queued-after-failure");
yield* store.apply({
id: EventId.make("event:settlement:queued-after-failure:message"),
type: "message.updated",
threadId,
occurredAt: old,
payload: {
createdBy: "user",
creationSource: "web",
id: messageId,
threadId,
runId: null,
nodeId: null,
role: "user",
text: "Queued while the last turn failed",
attachments: [],
streaming: false,
createdAt: old,
updatedAt: old,
},
});
const failedRun = (yield* store.getThreadProjection(threadId)).runs.find(
(run) => run.id === failedRunId,
)!;
yield* store.apply({
id: EventId.make("event:settlement:queued-after-failure:run"),
type: "run.created",
threadId,
occurredAt: old,
payload: {
...failedRun,
id: RunId.make("run:settlement:queued-after-failure"),
ordinal: 2,
userMessageId: messageId,
status: "queued",
startedAt: null,
completedAt: null,
queueHeld: true,
},
});

// thread.auto-settle rejects this thread ("has a queued message"), so the sweep must skip it.
const candidate = (yield* store.getSettlementCandidates()).find(
(thread) => thread.id === threadId,
)!;
assert.isFalse(isAutoSettlementCandidate(candidate, DateTime.toEpochMillis(now)));
}).pipe(Effect.provide(layerSql)),
);

it.effect("sql: the resuming message time counts MCP sends and ignores agent notifications", () =>
Effect.gen(function* () {
const store = yield* ProjectionStore.ProjectionStoreV2;
Expand Down
22 changes: 21 additions & 1 deletion apps/server/src/orchestration-v2/ProjectionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,8 @@ export type ProjectionSettlementCandidate = Pick<
Pick<OrchestrationV2AppThread, "lastSnoozeWakeAt"> & {
/** Latest user or MCP agent message; automatic server and provider wakes are excluded. */
readonly latestResumingMessageAt: DateTime.Utc | null;
/** A queued run waits on a message the user sent; thread.settle rejects the thread. */
readonly hasQueuedUserMessage?: boolean;
};

const ProjectionCheckpointContext = Schema.Struct({
Expand Down Expand Up @@ -1348,6 +1350,7 @@ type SettlementThreadRow = Pick<
| "latest_user_message_at"
> & {
readonly latest_resuming_message_at: string | null;
readonly has_queued_user_message: 0 | 1;
};

type ShellRunItemCountRow = {
Expand Down Expand Up @@ -9408,7 +9411,23 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, ProjectionStoreService
)
ORDER BY message.updated_at DESC, message.message_id DESC
LIMIT 1
) AS latest_resuming_message_at
) AS latest_resuming_message_at,
-- Matches thread.settle: only automatic messages may be dropped from the queue.
EXISTS (
SELECT 1 FROM orchestration_v2_projection_runs queued
WHERE queued.thread_id = t.thread_id AND queued.status = 'queued'
AND NOT EXISTS (
SELECT 1 FROM orchestration_v2_projection_messages message
WHERE message.message_id = json_extract(queued.payload_json, '$.userMessageId')
AND message.thread_id = t.thread_id AND message.role = 'user'
AND (
json_extract(message.payload_json, '$.createdBy') IS NOT 'user'
OR json_extract(message.payload_json, '$.scheduledTaskId') IS NOT NULL
OR json_extract(message.payload_json, '$.notification') IS NOT NULL
OR json_extract(message.payload_json, '$.delegatedCompletion') IS NOT NULL
)
)
) AS has_queued_user_message
FROM orchestration_v2_projection_threads t
LEFT JOIN orchestration_v2_projection_runs r ON r.run_id = (
SELECT latest.run_id FROM orchestration_v2_projection_runs latest
Expand Down Expand Up @@ -9533,6 +9552,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, ProjectionStoreService
row.latest_resuming_message_at === null
? null
: DateTime.makeUnsafe(row.latest_resuming_message_at),
hasQueuedUserMessage: row.has_queued_user_message === 1,
activityRunStatus: null,
activityRunStartedAt: null,
pendingRuntimeRequest: null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ export function isAutoSettlementCandidate(
// A guest is waiting on the owner; settling would hide the Request.
if ((thread.pendingGuestMessageCount ?? 0) > 0) return false;
if (thread.activityRunStatus != null) return false;
if (thread.hasQueuedUserMessage === true) return false;
const pendingTasks = thread.pendingBackgroundTasks ?? [];
if (backgroundWorkHoldsCompletion(pendingTasks)) return false;
// Settling ends a watch, which would silently drop a reviewer's later comments.
Expand Down
Loading