Compare commits

...
9 changed files with 574 additions and 96 deletions

No files matched your search

@@ -1,4 +1,5 @@
import {
ApprovalRequestId,
CheckpointRef,
CommandId,
CorrelationId,
@@ -2462,6 +2463,188 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
]);
}),
);
it.effect("only clears pending turn starts targeted by failure signals", () =>
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)));
const listPendingStarts = () => sql<{ readonly messageId: string }>`
SELECT pending_message_id AS "messageId"
FROM projection_turns
WHERE thread_id = ${threadId}
AND turn_id IS NULL
AND state = 'pending'
`;
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-old"),
runtimeMode: "full-access",
createdAt: "2026-02-26T13:00:00.000Z",
},
});
yield* appendAndProject({
type: "thread.turn-start-requested",
eventId: EventId.make("evt-start-failed-2"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-02-26T13:00:00.100Z",
commandId: CommandId.make("cmd-start-failed-2"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-start-failed-2"),
metadata: {},
payload: {
threadId,
messageId: MessageId.make("message-start-new"),
runtimeMode: "full-access",
createdAt: "2026-02-26T13:00:00.100Z",
},
});
yield* appendAndProject({
type: "thread.activity-appended",
eventId: EventId.make("evt-start-failed-3"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-02-26T13:00:00.200Z",
commandId: CommandId.make("cmd-start-failed-3"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-start-failed-3"),
metadata: { requestId: ApprovalRequestId.make("message-start-old") },
payload: {
threadId,
activity: {
id: EventId.make("activity-start-failed-old"),
tone: "error",
kind: "provider.turn.start.failed",
summary: "Provider turn start failed",
payload: { requestId: "message-start-old", detail: "Provider startup failed" },
turnId: null,
createdAt: "2026-02-26T13:00:00.200Z",
},
},
});
const pendingRows = yield* listPendingStarts();
assert.deepEqual(pendingRows, [{ messageId: "message-start-new" }]);
yield* appendAndProject({
type: "thread.activity-appended",
eventId: EventId.make("evt-start-failed-4"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-02-26T13:00:00.300Z",
commandId: CommandId.make("cmd-start-failed-4"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-start-failed-4"),
metadata: { requestId: ApprovalRequestId.make("message-start-new") },
payload: {
threadId,
activity: {
id: EventId.make("activity-start-failed-new"),
tone: "error",
kind: "provider.turn.start.failed",
summary: "Provider turn start failed",
payload: { requestId: "message-start-new", detail: "Provider startup failed" },
turnId: null,
createdAt: "2026-02-26T13:00:00.300Z",
},
},
});
const clearedRows = yield* listPendingStarts();
assert.deepEqual(clearedRows, []);
yield* appendAndProject({
type: "thread.turn-start-requested",
eventId: EventId.make("evt-start-failed-5"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-02-26T13:00:00.500Z",
commandId: CommandId.make("cmd-start-failed-5"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-start-failed-5"),
metadata: {},
payload: {
threadId,
messageId: MessageId.make("message-start-terminal"),
runtimeMode: "full-access",
createdAt: "2026-02-26T13:00:00.500Z",
},
});
yield* appendAndProject({
type: "thread.session-set",
eventId: EventId.make("evt-start-failed-6"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-02-26T13:00:00.600Z",
commandId: CommandId.make("cmd-start-failed-6"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-start-failed-6"),
metadata: {},
payload: {
threadId,
session: {
threadId,
status: "error",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: "Earlier session failed",
updatedAt: "2026-02-26T13:00:00.400Z",
},
},
});
const rowsAfterStaleSession = yield* listPendingStarts();
assert.deepEqual(rowsAfterStaleSession, [{ messageId: "message-start-terminal" }]);
yield* appendAndProject({
type: "thread.session-set",
eventId: EventId.make("evt-start-failed-7"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-02-26T13:00:00.700Z",
commandId: CommandId.make("cmd-start-failed-7"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-start-failed-7"),
metadata: {},
payload: {
threadId,
session: {
threadId,
status: "stopped",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: "2026-02-26T13:00:00.700Z",
},
},
});
const rowsAfterCurrentSession = yield* listPendingStarts();
assert.deepEqual(rowsAfterCurrentSession, []);
}),
);
});
it.effect("restores pending turn-start metadata across projection pipeline restart", () =>
@@ -1056,9 +1056,52 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
return;
}
case "thread.activity-appended": {
if (event.payload.activity.kind !== "provider.turn.start.failed") {
return;
}
const requestId = event.metadata.requestId;
if (requestId === undefined) {
return;
}
const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({
threadId: event.payload.threadId,
});
if (
Option.isNone(pendingTurnStart) ||
String(requestId) !== pendingTurnStart.value.messageId
) {
return;
}
yield* projectionTurnRepository.deletePendingTurnStartByThreadId({
threadId: event.payload.threadId,
});
return;
}
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"
) {
const pendingTurnStart =
yield* projectionTurnRepository.getPendingTurnStartByThreadId({
threadId: event.payload.threadId,
});
if (
Option.isSome(pendingTurnStart) &&
pendingTurnStart.value.requestedAt <= event.payload.session.updatedAt
) {
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,
@@ -1858,60 +1907,81 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
});
const getThreadShellById: ProjectionSnapshotQueryShape["getThreadShellById"] = (threadId) =>
Effect.gen(function* () {
const [threadRow, latestTurnRow, sessionRow] = yield* Effect.all([
getActiveThreadRowById({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadShellById:getThread:query",
"ProjectionSnapshotQuery.getThreadShellById:getThread:decodeRow",
sql
.withTransaction(
Effect.gen(function* () {
const [threadRow, latestTurnRow, sessionRow, pendingTurnStartRow] = yield* Effect.all([
getActiveThreadRowById({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadShellById:getThread:query",
"ProjectionSnapshotQuery.getThreadShellById:getThread:decodeRow",
),
),
),
),
),
getLatestTurnRowByThread({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:query",
"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:decodeRow",
getLatestTurnRowByThread({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:query",
"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:decodeRow",
),
),
),
),
),
getThreadSessionRowByThread({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadShellById:getSession:query",
"ProjectionSnapshotQuery.getThreadShellById:getSession:decodeRow",
getThreadSessionRowByThread({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadShellById:getSession:query",
"ProjectionSnapshotQuery.getThreadShellById:getSession:decodeRow",
),
),
),
),
),
]);
getPendingTurnStartRowByThread({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadShellById:getPendingTurnStart:query",
"ProjectionSnapshotQuery.getThreadShellById:getPendingTurnStart:decodeRow",
),
),
),
]);
if (Option.isNone(threadRow)) {
return Option.none<OrchestrationThreadShell>();
}
if (Option.isNone(threadRow)) {
return Option.none<OrchestrationThreadShell>();
}
return Option.some({
id: threadRow.value.threadId,
projectId: threadRow.value.projectId,
title: threadRow.value.title,
modelSelection: threadRow.value.modelSelection,
runtimeMode: threadRow.value.runtimeMode,
interactionMode: threadRow.value.interactionMode,
branch: threadRow.value.branch,
worktreePath: threadRow.value.worktreePath,
latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,
createdAt: threadRow.value.createdAt,
updatedAt: threadRow.value.updatedAt,
archivedAt: threadRow.value.archivedAt,
settledOverride: threadRow.value.settledOverride,
settledAt: threadRow.value.settledAt,
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
latestUserMessageAt: threadRow.value.latestUserMessageAt,
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
hasPendingUserInput: threadRow.value.pendingUserInputCount > 0,
hasActionableProposedPlan: threadRow.value.hasActionableProposedPlan > 0,
} satisfies OrchestrationThreadShell);
});
return Option.some({
id: threadRow.value.threadId,
projectId: threadRow.value.projectId,
title: threadRow.value.title,
modelSelection: threadRow.value.modelSelection,
runtimeMode: threadRow.value.runtimeMode,
interactionMode: threadRow.value.interactionMode,
branch: threadRow.value.branch,
worktreePath: threadRow.value.worktreePath,
latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,
createdAt: threadRow.value.createdAt,
updatedAt: threadRow.value.updatedAt,
archivedAt: threadRow.value.archivedAt,
settledOverride: threadRow.value.settledOverride,
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,
} satisfies OrchestrationThreadShell);
}),
)
.pipe(
Effect.mapError((error) =>
isPersistenceError(error)
? error
: toPersistenceSqlError("ProjectionSnapshotQuery.getThreadShellById:transaction")(
error,
),
),
);
const getThreadDetailById: ProjectionSnapshotQueryShape["getThreadDetailById"] = (threadId) =>
Effect.gen(function* () {
@@ -371,6 +371,7 @@ describe("ProviderCommandReactor", () => {
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
Layer.provideMerge(NodeServices.layer),
Layer.provide(SqlitePersistenceMemory),
);
runtime = ManagedRuntime.make(layer);
@@ -411,6 +412,7 @@ describe("ProviderCommandReactor", () => {
return {
engine,
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
snapshotQuery,
startSession,
sendTurn,
interruptTurn,
@@ -466,6 +468,97 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
effectIt.effect("clears pending work when session startup fails before binding", () =>
Effect.gen(function* () {
const harness = yield* Effect.promise(() => createHarness());
const now = "2026-01-01T00:00:00.000Z";
const messageId = asMessageId("user-message-start-failed");
harness.startSession.mockImplementationOnce(
(_: unknown, __: unknown) => Effect.fail("simulated startup failure") as never,
);
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-failed"),
threadId: ThreadId.make("thread-1"),
message: {
messageId,
role: "user",
text: "hello reactor",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
});
yield* Effect.promise(() =>
waitFor(async () => {
const readModel = await harness.readModel();
return (
readModel.threads[0]?.activities.some(
(activity) => activity.kind === "provider.turn.start.failed",
) ?? false
);
}),
);
const readModel = yield* harness.snapshotQuery.getSnapshot();
expect(readModel.threads[0]?.session).toBeNull();
expect(
readModel.threads[0]?.activities.find(
(activity) => activity.kind === "provider.turn.start.failed",
),
).toMatchObject({ payload: { requestId: messageId } });
const shellSnapshot = yield* harness.snapshotQuery.getShellSnapshot();
expect(shellSnapshot.threads[0]?.hasPendingTurnStart).toBe(false);
}),
);
effectIt.effect("clears pending work when turn startup is interrupted", () =>
Effect.gen(function* () {
const harness = yield* Effect.promise(() => createHarness());
const now = "2026-01-01T00:00:00.000Z";
const messageId = asMessageId("user-message-start-interrupted");
harness.sendTurn.mockImplementationOnce(() => Effect.interrupt);
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-interrupted"),
threadId: ThreadId.make("thread-1"),
message: {
messageId,
role: "user",
text: "hello reactor",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
});
yield* Effect.promise(() =>
waitFor(async () => {
const readModel = await harness.readModel();
return (
readModel.threads[0]?.activities.some(
(activity) => activity.kind === "provider.turn.start.failed",
) ?? false
);
}),
);
const readModel = yield* harness.snapshotQuery.getSnapshot();
expect(
readModel.threads[0]?.activities.find(
(activity) => activity.kind === "provider.turn.start.failed",
),
).toMatchObject({ payload: { requestId: messageId } });
const shellSnapshot = yield* harness.snapshotQuery.getShellSnapshot();
expect(shellSnapshot.threads[0]?.hasPendingTurnStart).toBe(false);
}),
);
it("generates a thread title on the first turn", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -29,6 +29,8 @@ import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import type { ProviderServiceError } from "../../provider/Errors.ts";
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { ProviderRegistry } from "../../provider/Services/ProviderRegistry.ts";
@@ -190,6 +192,7 @@ const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const providerService = yield* ProviderService;
const providerRegistry = yield* ProviderRegistry;
const gitWorkflow = yield* GitWorkflowService;
@@ -766,6 +769,7 @@ const make = Effect.gen(function* () {
detail: `User message '${event.payload.messageId}' was not found for turn start request.`,
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.messageId,
});
return;
}
@@ -801,29 +805,40 @@ const make = Effect.gen(function* () {
}
}
const handleTurnStartFailure = (cause: Cause.Cause<unknown>) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
const handleTurnStartFailure = Effect.fnUntraced(function* (cause: Cause.Cause<unknown>) {
const interrupted = Cause.hasInterruptsOnly(cause);
if (interrupted) {
const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({
threadId: event.payload.threadId,
});
if (
Option.isNone(pendingTurnStart) ||
pendingTurnStart.value.messageId !== event.payload.messageId
) {
return;
}
}
const detail = formatFailureDetail(cause);
return setThreadSessionErrorOnTurnStartFailure({
const detail = interrupted
? "Provider turn start was interrupted before it began."
: formatFailureDetail(cause);
if (!interrupted) {
yield* setThreadSessionErrorOnTurnStartFailure({
threadId: event.payload.threadId,
detail,
createdAt: event.payload.createdAt,
});
}
yield* appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.turn.start.failed",
summary: "Provider turn start failed",
detail,
turnId: null,
createdAt: event.payload.createdAt,
}).pipe(
Effect.flatMap(() =>
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.turn.start.failed",
summary: "Provider turn start failed",
detail,
turnId: null,
createdAt: event.payload.createdAt,
}),
),
Effect.asVoid,
);
};
requestId: event.payload.messageId,
});
});
const recoverTurnStartFailure = (cause: Cause.Cause<unknown>) =>
handleTurnStartFailure(cause).pipe(
@@ -1085,4 +1100,6 @@ const make = Effect.gen(function* () {
} satisfies ProviderCommandReactorShape;
});
export const ProviderCommandReactorLive = Layer.effect(ProviderCommandReactor, make);
export const ProviderCommandReactorLive = Layer.effect(ProviderCommandReactor, make).pipe(
Layer.provide(ProjectionTurnRepositoryLive),
);
+45 -1
View File
@@ -648,7 +648,11 @@ describe("resolveSidebarV2Status", () => {
updatedAt: "2026-03-09T10:00:00.000Z",
};
const idle = { hasPendingApprovals: false, hasPendingUserInput: false };
const idle = {
hasPendingApprovals: false,
hasPendingTurnStart: false,
hasPendingUserInput: false,
};
it("prioritizes approval over a running session", () => {
expect(resolveSidebarV2Status({ ...idle, hasPendingApprovals: true, session })).toBe(
@@ -678,6 +682,16 @@ describe("resolveSidebarV2Status", () => {
).toBe("working");
});
it("reports working while a turn start is pending without a session", () => {
expect(
resolveSidebarV2Status({
...idle,
hasPendingTurnStart: true,
session: null,
}),
).toBe("working");
});
it("reports failed only while the session status is error", () => {
expect(
resolveSidebarV2Status({
@@ -734,6 +748,7 @@ describe("resolveThreadStatusPill", () => {
const baseThread = {
hasActionableProposedPlan: false,
hasPendingApprovals: false,
hasPendingTurnStart: false,
hasPendingUserInput: false,
interactionMode: "plan" as const,
latestTurn: null,
@@ -781,6 +796,35 @@ describe("resolveThreadStatusPill", () => {
).toMatchObject({ label: "Working", pulse: true });
});
it("shows working while a new thread turn is waiting for its first session update", () => {
expect(
resolveThreadStatusPill({
thread: {
...baseThread,
hasPendingTurnStart: true,
session: null,
},
}),
).toMatchObject({ label: "Working", pulse: true });
});
it("keeps showing working through a ready session before the turn starts", () => {
expect(
resolveThreadStatusPill({
thread: {
...baseThread,
hasPendingTurnStart: true,
session: {
...baseThread.session,
status: "ready",
activeTurnId: null,
updatedAt: "2026-03-09T10:00:02.000Z",
},
},
}),
).toMatchObject({ label: "Working", pulse: true });
});
it("shows plan ready when a settled plan turn has a proposed plan ready for follow-up", () => {
expect(
resolveThreadStatusPill({
+8 -3
View File
@@ -112,6 +112,7 @@ type ThreadStatusInput = Pick<
SidebarThreadSummary,
| "hasActionableProposedPlan"
| "hasPendingApprovals"
| "hasPendingTurnStart"
| "hasPendingUserInput"
| "interactionMode"
| "latestTurn"
@@ -428,7 +429,7 @@ export type SidebarV2Status = "approval" | "input" | "working" | "failed" | "rea
type SidebarV2StatusInput = Pick<
SidebarThreadSummary,
"hasPendingApprovals" | "hasPendingUserInput" | "session"
"hasPendingApprovals" | "hasPendingTurnStart" | "hasPendingUserInput" | "session"
>;
export function resolveSidebarV2Status(thread: SidebarV2StatusInput): SidebarV2Status {
@@ -438,7 +439,11 @@ export function resolveSidebarV2Status(thread: SidebarV2StatusInput): SidebarV2S
if (thread.hasPendingUserInput) {
return "input";
}
if (thread.session?.status === "running" || thread.session?.status === "starting") {
if (
thread.session?.status === "running" ||
thread.session?.status === "starting" ||
thread.hasPendingTurnStart === true
) {
return "working";
}
if (thread.session?.status === "error") {
@@ -505,7 +510,7 @@ export function resolveThreadStatusPill(input: {
};
}
if (thread.session?.status === "running") {
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,