Use projected pending turn state

This commit is contained in:
Theo Browne committed 2026-07-22 04:45:59 -07:00
1 parent 5ecf807001
commit cafe093de4
7 files changed
+185 -78

No files matched your search

@@ -2462,6 +2462,70 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
]);
}),
);
it.effect("clears a pending turn start when provider startup fails", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const threadId = ThreadId.make("thread-start-failed");
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
yield* appendAndProject({
type: "thread.turn-start-requested",
eventId: EventId.make("evt-start-failed-1"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-02-26T13:00:00.000Z",
commandId: CommandId.make("cmd-start-failed-1"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-start-failed-1"),
metadata: {},
payload: {
threadId,
messageId: MessageId.make("message-start-failed"),
runtimeMode: "full-access",
createdAt: "2026-02-26T13:00:00.000Z",
},
});
yield* appendAndProject({
type: "thread.session-set",
eventId: EventId.make("evt-start-failed-2"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-02-26T13:00:01.000Z",
commandId: CommandId.make("cmd-start-failed-2"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-start-failed-2"),
metadata: {},
payload: {
threadId,
session: {
threadId,
status: "ready",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: "Provider startup failed",
updatedAt: "2026-02-26T13:00:01.000Z",
},
},
});
const pendingRows = yield* sql<{ readonly threadId: string }>`
SELECT thread_id AS "threadId"
FROM projection_turns
WHERE thread_id = ${threadId}
AND turn_id IS NULL
AND state = 'pending'
`;
assert.deepEqual(pendingRows, []);
}),
);
});
it.effect("restores pending turn-start metadata across projection pipeline restart", () =>
@@ -1059,6 +1059,17 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
case "thread.session-set": {
const turnId = event.payload.session.activeTurnId;
if (turnId === null || event.payload.session.status !== "running") {
if (
event.payload.session.lastError !== null ||
event.payload.session.status === "error" ||
event.payload.session.status === "interrupted" ||
event.payload.session.status === "stopped"
) {
yield* projectionTurnRepository.deletePendingTurnStartByThreadId({
threadId: event.payload.threadId,
});
}
// Leaving the "running" session status is the turn-end signal:
// settle still-running turns so their duration reflects the whole
// turn rather than the last assistant message.
@@ -217,22 +217,39 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
checkpoint_status,
checkpoint_files_json
)
VALUES (
'thread-1',
'turn-1',
NULL,
'thread-1',
'plan-1',
'message-1',
'completed',
'2026-02-24T00:00:08.000Z',
'2026-02-24T00:00:08.000Z',
'2026-02-24T00:00:08.000Z',
1,
'checkpoint-1',
'ready',
'[{"path":"README.md","kind":"modified","additions":2,"deletions":1}]'
)
VALUES
(
'thread-1',
'turn-1',
NULL,
'thread-1',
'plan-1',
'message-1',
'completed',
'2026-02-24T00:00:08.000Z',
'2026-02-24T00:00:08.000Z',
'2026-02-24T00:00:08.000Z',
1,
'checkpoint-1',
'ready',
'[{"path":"README.md","kind":"modified","additions":2,"deletions":1}]'
),
(
'thread-1',
NULL,
'message-pending',
NULL,
NULL,
NULL,
'pending',
'2026-02-24T00:00:09.000Z',
NULL,
NULL,
NULL,
NULL,
NULL,
'[]'
)
`;
let sequence = 5;
@@ -432,12 +449,17 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
updatedAt: "2026-02-24T00:00:07.000Z",
},
latestUserMessageAt: "2026-02-24T00:00:04.000Z",
hasPendingTurnStart: true,
hasPendingApprovals: true,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
},
]);
const threadShell = yield* snapshotQuery.getThreadShellById(ThreadId.make("thread-1"));
assert.equal(threadShell._tag, "Some");
assert.equal(threadShell._tag === "Some" && threadShell.value.hasPendingTurnStart, true);
const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
assert.equal(threadDetail._tag, "Some");
if (threadDetail._tag === "Some") {
@@ -103,6 +103,9 @@ const ProjectionLatestTurnDbRowSchema = Schema.Struct({
sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
});
const ProjectionPendingTurnStartDbRowSchema = Schema.Struct({
threadId: ThreadId,
});
const ProjectionStateDbRowSchema = ProjectionState;
const ProjectionCountsRowSchema = Schema.Struct({
projectCount: Schema.Number,
@@ -614,6 +617,23 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const listActivePendingTurnStartRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionPendingTurnStartDbRowSchema,
execute: () =>
sql`
SELECT turns.thread_id AS "threadId"
FROM projection_turns turns
INNER JOIN projection_threads threads
ON threads.thread_id = turns.thread_id
WHERE threads.deleted_at IS NULL
AND threads.archived_at IS NULL
AND turns.turn_id IS NULL
AND turns.state = 'pending'
ORDER BY turns.thread_id ASC
`,
});
const listArchivedLatestTurnRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionLatestTurnDbRowSchema,
@@ -886,6 +906,20 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const getPendingTurnStartRowByThread = SqlSchema.findOneOption({
Request: ThreadIdLookupInput,
Result: ProjectionPendingTurnStartDbRowSchema,
execute: ({ threadId }) =>
sql`
SELECT thread_id AS "threadId"
FROM projection_turns
WHERE thread_id = ${threadId}
AND turn_id IS NULL
AND state = 'pending'
LIMIT 1
`,
});
const listCheckpointRowsByThread = SqlSchema.findAll({
Request: ThreadIdLookupInput,
Result: ProjectionCheckpointDbRowSchema,
@@ -1449,14 +1483,24 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listActiveLatestTurnRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query",
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:decodeRows",
Effect.all({
latestTurnRows: listActiveLatestTurnRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query",
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:decodeRows",
),
),
),
),
pendingTurnStartRows: listActivePendingTurnStartRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getShellSnapshot:listPendingTurnStarts:query",
"ProjectionSnapshotQuery.getShellSnapshot:listPendingTurnStarts:decodeRows",
),
),
),
}),
listProjectionStateRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
@@ -1468,8 +1512,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
]),
)
.pipe(
Effect.flatMap(([projectRows, threadRows, sessionRows, latestTurnRows, stateRows]) =>
Effect.flatMap(([projectRows, threadRows, sessionRows, turnRows, stateRows]) =>
Effect.gen(function* () {
const { latestTurnRows, pendingTurnStartRows } = turnRows;
let updatedAt: string | null = null;
for (const row of projectRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
@@ -1500,6 +1545,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
const sessionByThread = new Map(
sessionRows.map((row) => [row.threadId, mapSessionRow(row)] as const),
);
const pendingTurnStartThreadIds = new Set(
pendingTurnStartRows.map((row) => row.threadId),
);
const snapshot = {
snapshotSequence: computeSnapshotSequence(stateRows),
@@ -1529,6 +1577,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: row.settledAt,
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingTurnStart: pendingTurnStartThreadIds.has(row.threadId),
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
@@ -1859,7 +1908,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
const getThreadShellById: ProjectionSnapshotQueryShape["getThreadShellById"] = (threadId) =>
Effect.gen(function* () {
const [threadRow, latestTurnRow, sessionRow] = yield* Effect.all([
const [threadRow, latestTurnRow, sessionRow, pendingTurnStartRow] = yield* Effect.all([
getActiveThreadRowById({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
@@ -1884,6 +1933,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
getPendingTurnStartRowByThread({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadShellById:getPendingTurnStart:query",
"ProjectionSnapshotQuery.getThreadShellById:getPendingTurnStart:decodeRow",
),
),
),
]);
if (Option.isNone(threadRow)) {
@@ -1907,6 +1964,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
settledAt: threadRow.value.settledAt,
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
latestUserMessageAt: threadRow.value.latestUserMessageAt,
hasPendingTurnStart: Option.isSome(pendingTurnStartRow),
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
hasPendingUserInput: threadRow.value.pendingUserInputCount > 0,
hasActionableProposedPlan: threadRow.value.hasActionableProposedPlan > 0,
+3 -26
View File
@@ -170,7 +170,6 @@ describe("hasUnseenCompletion", () => {
hasPendingUserInput: false,
interactionMode: "default",
latestTurn: makeLatestTurn(),
latestUserMessageAt: null,
lastVisitedAt: "2026-03-09T10:04:00.000Z",
session: null,
}),
@@ -185,7 +184,6 @@ describe("hasUnseenCompletion", () => {
hasPendingUserInput: false,
interactionMode: "default",
latestTurn: makeLatestTurn(),
latestUserMessageAt: null,
lastVisitedAt: undefined,
session: null,
}),
@@ -736,10 +734,10 @@ describe("resolveThreadStatusPill", () => {
const baseThread = {
hasActionableProposedPlan: false,
hasPendingApprovals: false,
hasPendingTurnStart: false,
hasPendingUserInput: false,
interactionMode: "plan" as const,
latestTurn: null,
latestUserMessageAt: null,
lastVisitedAt: undefined,
session: {
threadId: ThreadId.make("thread-1"),
@@ -789,7 +787,7 @@ describe("resolveThreadStatusPill", () => {
resolveThreadStatusPill({
thread: {
...baseThread,
latestUserMessageAt: "2026-03-09T10:00:01.000Z",
hasPendingTurnStart: true,
session: null,
},
}),
@@ -801,7 +799,7 @@ describe("resolveThreadStatusPill", () => {
resolveThreadStatusPill({
thread: {
...baseThread,
latestUserMessageAt: "2026-03-09T10:00:01.000Z",
hasPendingTurnStart: true,
session: {
...baseThread.session,
status: "ready",
@@ -813,27 +811,6 @@ describe("resolveThreadStatusPill", () => {
).toMatchObject({ label: "Working", pulse: true });
});
it("does not show stale pending work after the turn acknowledges the message", () => {
expect(
resolveThreadStatusPill({
thread: {
...baseThread,
latestUserMessageAt: "2026-03-09T10:00:01.000Z",
latestTurn: {
...makeLatestTurn(),
requestedAt: "2026-03-09T10:00:02.000Z",
},
session: {
...baseThread.session,
status: "ready",
activeTurnId: null,
updatedAt: "2026-03-09T10:05:00.000Z",
},
},
}),
).toBeNull();
});
it("shows plan ready when a settled plan turn has a proposed plan ready for follow-up", () => {
expect(
resolveThreadStatusPill({
+2 -28
View File
@@ -112,10 +112,10 @@ type ThreadStatusInput = Pick<
SidebarThreadSummary,
| "hasActionableProposedPlan"
| "hasPendingApprovals"
| "hasPendingTurnStart"
| "hasPendingUserInput"
| "interactionMode"
| "latestTurn"
| "latestUserMessageAt"
| "session"
> & {
lastVisitedAt?: string | undefined;
@@ -224,32 +224,6 @@ export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
return completedAt > lastVisitedAt;
}
function hasPendingTurnStart(thread: ThreadStatusInput): boolean {
if (!thread.latestUserMessageAt) return false;
const latestUserMessageAt = Date.parse(thread.latestUserMessageAt);
if (Number.isNaN(latestUserMessageAt)) return false;
const latestTurnRequestedAt = thread.latestTurn
? Date.parse(thread.latestTurn.requestedAt)
: Number.NaN;
if (!Number.isNaN(latestTurnRequestedAt) && latestTurnRequestedAt >= latestUserMessageAt) {
return false;
}
// Session bootstrap may pass through starting/ready before the provider
// creates the turn; only terminal states can acknowledge a failed start.
const session = thread.session;
if (
!session ||
(session.status !== "error" && session.status !== "interrupted" && session.status !== "stopped")
) {
return true;
}
const sessionUpdatedAt = Date.parse(session.updatedAt);
return Number.isNaN(sessionUpdatedAt) || sessionUpdatedAt < latestUserMessageAt;
}
export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
if (target === null) return true;
return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
@@ -532,7 +506,7 @@ export function resolveThreadStatusPill(input: {
};
}
if (thread.session?.status === "running" || hasPendingTurnStart(thread)) {
if (thread.session?.status === "running" || thread.hasPendingTurnStart === true) {
return {
label: "Working",
colorClass: "text-sky-600 dark:text-sky-300/80",
+1
View File
@@ -412,6 +412,7 @@ export const OrchestrationThreadShell = Schema.Struct({
settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
session: Schema.NullOr(OrchestrationSession),
latestUserMessageAt: Schema.NullOr(IsoDateTime),
hasPendingTurnStart: Schema.optional(Schema.Boolean),
hasPendingApprovals: Schema.Boolean,
hasPendingUserInput: Schema.Boolean,
hasActionableProposedPlan: Schema.Boolean,