fix(server): queue messages during context compaction (#11107)
Co-authored-by: Claude Fable 5.1 <[email protected]>
This commit is contained in:
1 parent
ef6fa11874
commit
57aee3e19f
2 files changed
+373
-92
No files matched your search
@@ -175,6 +175,8 @@ describe("ProviderCommandReactor", () => {
|
||||
readonly titleRegenerationBeforeStart?: "one" | "two";
|
||||
readonly serverActivation?: Effect.Effect<void>;
|
||||
readonly beforeReadySessionDispatch?: () => Effect.Effect<void>;
|
||||
readonly beforeTurnStartDispatch?: () => Effect.Effect<void>;
|
||||
readonly afterTurnStartDispatch?: () => Effect.Effect<void>;
|
||||
readonly compactThreadEffect?: () => Effect.Effect<void, ProviderAdapterRequestError>;
|
||||
readonly interruptTurnEffect?: () => Effect.Effect<void, ProviderAdapterRequestError>;
|
||||
readonly stopSessionEffect?: () => Effect.Effect<void, ProviderAdapterRequestError>;
|
||||
@@ -431,11 +433,21 @@ describe("ProviderCommandReactor", () => {
|
||||
return Effect.die(new Error("Injected title regeneration completion failure"));
|
||||
}
|
||||
}
|
||||
return (
|
||||
const isReplay =
|
||||
command.type === "thread.turn.start" &&
|
||||
command.commandId.startsWith("server:after-compaction:");
|
||||
const before =
|
||||
command.type === "thread.session.set" && command.session.status === "ready"
|
||||
? (input?.beforeReadySessionDispatch?.() ?? Effect.void)
|
||||
: Effect.void
|
||||
).pipe(Effect.andThen(engine.dispatch(command)));
|
||||
? input?.beforeReadySessionDispatch
|
||||
: isReplay
|
||||
? input?.beforeTurnStartDispatch
|
||||
: undefined;
|
||||
return (before?.() ?? Effect.void).pipe(
|
||||
Effect.andThen(engine.dispatch(command)),
|
||||
Effect.tap(() =>
|
||||
isReplay ? (input?.afterTurnStartDispatch?.() ?? Effect.void) : Effect.void,
|
||||
),
|
||||
);
|
||||
},
|
||||
get streamDomainEvents() {
|
||||
return engine.streamDomainEvents;
|
||||
@@ -973,86 +985,203 @@ describe("ProviderCommandReactor", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("keeps turns blocked until compaction restores the session", () =>
|
||||
Effect.gen(function* () {
|
||||
const readyDispatchStarted = yield* Deferred.make<void>();
|
||||
const releaseReadyDispatch = yield* Deferred.make<void>();
|
||||
let blockReadyDispatch = false;
|
||||
const harness = yield* Effect.promise(() =>
|
||||
createHarness({
|
||||
beforeReadySessionDispatch: () =>
|
||||
blockReadyDispatch
|
||||
? Deferred.succeed(readyDispatchStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(releaseReadyDispatch)),
|
||||
)
|
||||
: Effect.void,
|
||||
}),
|
||||
);
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const dispatchTurn = (id: string, text: string, createdAt: string) =>
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make(`cmd-${id}`),
|
||||
effectIt.effect.each(["resume", "stop before resume", "stop after send"])(
|
||||
"queues messages until compaction restores the session (%s)",
|
||||
(scenario) =>
|
||||
Effect.gen(function* () {
|
||||
const stopBeforeResume = scenario === "stop before resume";
|
||||
const readyDispatchStarted = yield* Deferred.make<void>();
|
||||
const releaseReadyDispatch = yield* Deferred.make<void>();
|
||||
const firstSent = yield* Deferred.make<void>();
|
||||
const queuedSent = yield* Deferred.make<void>();
|
||||
const resumeStarted = yield* Deferred.make<void>();
|
||||
const releaseResume = yield* Deferred.make<void>();
|
||||
const resumeDispatched = yield* Deferred.make<void>();
|
||||
const queuedSendStarted = yield* Deferred.make<void>();
|
||||
const releaseQueuedSend = yield* Deferred.make<void>();
|
||||
let blockReadyDispatch = false;
|
||||
const harness = yield* Effect.promise(() =>
|
||||
createHarness({
|
||||
beforeTurnStartDispatch: () =>
|
||||
stopBeforeResume
|
||||
? Deferred.succeed(resumeStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(releaseResume)),
|
||||
)
|
||||
: Effect.void,
|
||||
afterTurnStartDispatch: () => Deferred.succeed(resumeDispatched, undefined),
|
||||
beforeReadySessionDispatch: () =>
|
||||
blockReadyDispatch
|
||||
? Deferred.succeed(readyDispatchStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(releaseReadyDispatch)),
|
||||
)
|
||||
: Effect.void,
|
||||
}),
|
||||
);
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
let sentCount = 0;
|
||||
harness.sendTurn.mockImplementation(() =>
|
||||
Effect.succeed({ threadId, turnId: asTurnId("turn-1") }).pipe(
|
||||
Effect.tap(() => {
|
||||
sentCount++;
|
||||
return sentCount === 1
|
||||
? Deferred.succeed(firstSent, undefined)
|
||||
: sentCount === 2 && scenario === "stop after send"
|
||||
? Deferred.succeed(queuedSendStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(releaseQueuedSend)),
|
||||
)
|
||||
: sentCount === 3
|
||||
? Deferred.succeed(queuedSent, undefined)
|
||||
: Effect.void;
|
||||
}),
|
||||
),
|
||||
);
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const dispatchTurn = (id: string, text: string, createdAt: string) =>
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make(`cmd-${id}`),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: asMessageId(`user-message-${id}`),
|
||||
role: "user",
|
||||
text,
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt,
|
||||
});
|
||||
|
||||
yield* dispatchTurn("before-blocked-compact", "hello", now);
|
||||
yield* Deferred.await(firstSent);
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-ready-before-blocked-compact"),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: asMessageId(`user-message-${id}`),
|
||||
role: "user",
|
||||
text,
|
||||
attachments: [],
|
||||
session: {
|
||||
threadId,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt,
|
||||
createdAt: now,
|
||||
});
|
||||
|
||||
yield* dispatchTurn("before-blocked-compact", "hello", now);
|
||||
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-ready-before-blocked-compact"),
|
||||
threadId,
|
||||
session: {
|
||||
blockReadyDispatch = true;
|
||||
yield* dispatchTurn("blocked-compact", "/compact", "2026-01-01T00:00:01.000Z");
|
||||
yield* Deferred.await(readyDispatchStarted);
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.interaction-mode.set",
|
||||
commandId: CommandId.make("cmd-queued-mode-plan"),
|
||||
threadId,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
});
|
||||
interactionMode: "plan",
|
||||
createdAt: now,
|
||||
});
|
||||
yield* dispatchTurn("during-compact-recovery", "first queued", "2026-01-01T00:00:02.000Z");
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.interaction-mode.set",
|
||||
commandId: CommandId.make("cmd-queued-mode-default"),
|
||||
threadId,
|
||||
interactionMode: "default",
|
||||
createdAt: now,
|
||||
});
|
||||
yield* dispatchTurn(
|
||||
"during-compact-recovery-2",
|
||||
"second queued",
|
||||
"2026-01-01T00:00:03.000Z",
|
||||
);
|
||||
yield* Effect.promise(() => harness.drain());
|
||||
expect(harness.sendTurn).toHaveBeenCalledTimes(1);
|
||||
const beforeRestore = (yield* Effect.promise(() => harness.readModel())).threads.find(
|
||||
(entry) => entry.id === threadId,
|
||||
);
|
||||
expect(
|
||||
beforeRestore?.activities.filter(
|
||||
(activity) => activity.kind === "provider.turn.start.failed",
|
||||
),
|
||||
).toEqual([]);
|
||||
expect(yield* Effect.promise(() => harness.readPendingTurnStarts())).toEqual([
|
||||
{ threadId: "thread-1" },
|
||||
]);
|
||||
|
||||
blockReadyDispatch = true;
|
||||
yield* dispatchTurn("blocked-compact", "/compact", "2026-01-01T00:00:01.000Z");
|
||||
yield* Deferred.await(readyDispatchStarted);
|
||||
|
||||
yield* dispatchTurn("during-compact-recovery", "too soon", "2026-01-01T00:00:02.000Z");
|
||||
yield* Effect.promise(() =>
|
||||
waitFor(async () => {
|
||||
const thread = (await harness.readModel()).threads.find((entry) => entry.id === threadId);
|
||||
return (
|
||||
thread?.activities.some(
|
||||
(activity) => activity.kind === "provider.turn.start.failed",
|
||||
) === true
|
||||
yield* Deferred.succeed(releaseReadyDispatch, undefined);
|
||||
if (scenario === "stop after send") {
|
||||
yield* Deferred.await(queuedSendStarted);
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.session.stop",
|
||||
commandId: CommandId.make("cmd-stop-after-queued-send"),
|
||||
threadId,
|
||||
createdAt: "2026-01-01T00:00:04.000Z",
|
||||
});
|
||||
yield* Effect.promise(() => harness.drain());
|
||||
const stoppedThread = (yield* Effect.promise(() => harness.readModel())).threads.find(
|
||||
(entry) => entry.id === threadId,
|
||||
);
|
||||
}),
|
||||
);
|
||||
expect(harness.sendTurn).toHaveBeenCalledTimes(1);
|
||||
expect(yield* Effect.promise(() => harness.readPendingTurnStarts())).toEqual([
|
||||
{ threadId: "thread-1" },
|
||||
]);
|
||||
|
||||
yield* Deferred.succeed(releaseReadyDispatch, undefined);
|
||||
yield* Effect.promise(() =>
|
||||
waitFor(async () => {
|
||||
const thread = (await harness.readModel()).threads.find((entry) => entry.id === threadId);
|
||||
return thread?.session?.status === "ready";
|
||||
}),
|
||||
);
|
||||
}),
|
||||
expect(stoppedThread?.session?.status).toBe("stopped");
|
||||
expect(
|
||||
stoppedThread?.activities.filter(
|
||||
(activity) => activity.summary === "Queued message was not sent",
|
||||
),
|
||||
).toEqual([
|
||||
expect.objectContaining({
|
||||
payload: {
|
||||
requestId: "user-message-during-compact-recovery-2",
|
||||
detail: expect.any(String),
|
||||
},
|
||||
}),
|
||||
]);
|
||||
expect(harness.sendTurn).toHaveBeenCalledTimes(2);
|
||||
yield* Deferred.succeed(releaseQueuedSend, undefined);
|
||||
return;
|
||||
}
|
||||
if (stopBeforeResume) {
|
||||
yield* Deferred.await(resumeStarted);
|
||||
yield* dispatchTurn("compact-during-resume", "/compact", "2026-01-01T00:00:04.000Z");
|
||||
yield* Effect.promise(() => harness.drain());
|
||||
expect(harness.compactThread).toHaveBeenCalledTimes(1);
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.session.stop",
|
||||
commandId: CommandId.make("cmd-stop-before-queued-resume"),
|
||||
threadId,
|
||||
createdAt: "2026-01-01T00:00:04.000Z",
|
||||
});
|
||||
yield* Effect.promise(() => harness.drain());
|
||||
yield* Deferred.succeed(releaseResume, undefined);
|
||||
yield* Deferred.await(resumeDispatched);
|
||||
yield* Effect.promise(() => harness.drain());
|
||||
expect(harness.sendTurn).toHaveBeenCalledTimes(1);
|
||||
const stoppedThread = (yield* Effect.promise(() => harness.readModel())).threads.find(
|
||||
(entry) => entry.id === threadId,
|
||||
);
|
||||
expect(stoppedThread?.session?.status).toBe("stopped");
|
||||
expect(yield* Effect.promise(() => harness.readPendingTurnStarts())).toEqual([]);
|
||||
expect(
|
||||
stoppedThread?.activities.filter(
|
||||
(activity) => activity.summary === "Queued message was not sent",
|
||||
),
|
||||
).toHaveLength(2);
|
||||
return;
|
||||
}
|
||||
yield* Deferred.await(queuedSent);
|
||||
expect(harness.sendTurn.mock.calls.slice(1).map(([request]) => request)).toEqual([
|
||||
expect.objectContaining({ input: "first queued", interactionMode: "plan" }),
|
||||
expect.objectContaining({ input: "second queued", interactionMode: "default" }),
|
||||
]);
|
||||
const afterRestore = (yield* Effect.promise(() => harness.readModel())).threads.find(
|
||||
(entry) => entry.id === threadId,
|
||||
);
|
||||
expect(
|
||||
afterRestore?.messages.filter((message) => message.text === "first queued"),
|
||||
).toHaveLength(1);
|
||||
expect(
|
||||
afterRestore?.messages.filter((message) => message.text === "second queued"),
|
||||
).toHaveLength(1);
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("does not overwrite concurrent session state after compaction failure", () =>
|
||||
@@ -1136,6 +1265,21 @@ describe("ProviderCommandReactor", () => {
|
||||
(entry) => entry.id === threadId,
|
||||
);
|
||||
expect(compactingThread?.session?.status).toBe("starting");
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-queued-before-stop"),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: asMessageId("user-message-queued-before-stop"),
|
||||
role: "user",
|
||||
text: "do not restart after stopping",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
});
|
||||
yield* Effect.promise(() => harness.drain());
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.session.stop",
|
||||
commandId: CommandId.make("cmd-stop-during-compact"),
|
||||
@@ -1151,7 +1295,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
return (
|
||||
compactingThread?.activities.some(
|
||||
(activity) => activity.kind === "provider.turn.start.failed",
|
||||
(activity) => activity.summary === "Context compaction failed",
|
||||
) === true
|
||||
);
|
||||
}),
|
||||
@@ -1167,6 +1311,14 @@ describe("ProviderCommandReactor", () => {
|
||||
(entry) => entry.id === threadId,
|
||||
);
|
||||
expect(recoveredThread?.session?.status).toBe("ready");
|
||||
expect(harness.sendTurn).toHaveBeenCalledTimes(1);
|
||||
expect(
|
||||
recoveredThread?.activities.find(
|
||||
(activity) => activity.summary === "Queued message was not sent",
|
||||
),
|
||||
).toMatchObject({
|
||||
payload: { requestId: "user-message-queued-before-stop" },
|
||||
});
|
||||
expect(
|
||||
recoveredThread?.activities.find(
|
||||
(activity) => activity.kind === "provider.session.stop.failed",
|
||||
|
||||
@@ -18,6 +18,7 @@ import * as Cache from "effect/Cache";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Equal from "effect/Equal";
|
||||
@@ -346,6 +347,19 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const threadModelSelections = new Map<string, ModelSelection>();
|
||||
const compactingThreadIds = new Set<ThreadId>();
|
||||
type QueuedTurnStart = Extract<ProviderIntentEvent, { type: "thread.turn-start-requested" }>;
|
||||
// Turn starts received while a thread compacts, replayed in order once its session is restored.
|
||||
const turnsAfterCompaction = new Map<ThreadId, Array<QueuedTurnStart>>();
|
||||
// Replay command id → the queued turn start it re-requests. `sent` settles once the replay's
|
||||
// provider send finishes, which is what lets the next queued turn follow it in order.
|
||||
const resumedTurnStarts = new Map<
|
||||
CommandId,
|
||||
{
|
||||
readonly event: QueuedTurnStart;
|
||||
readonly queued: Array<QueuedTurnStart>;
|
||||
readonly sent: Deferred.Deferred<void>;
|
||||
}
|
||||
>();
|
||||
const stoppingThreadIds = new Set<ThreadId>();
|
||||
|
||||
const appendProviderFailureActivity = (input: {
|
||||
@@ -388,6 +402,71 @@ const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const cancelTurnsAfterCompaction = Effect.fn("cancelTurnsAfterCompaction")(function* (
|
||||
threadId: ThreadId,
|
||||
detail: string,
|
||||
) {
|
||||
const queued = turnsAfterCompaction.get(threadId) ?? [];
|
||||
turnsAfterCompaction.delete(threadId);
|
||||
for (const event of queued) {
|
||||
yield* appendProviderFailureActivity({
|
||||
threadId,
|
||||
kind: "provider.turn.start.failed",
|
||||
summary: "Queued message was not sent",
|
||||
detail,
|
||||
turnId: null,
|
||||
createdAt: DateTime.formatIso(yield* DateTime.now),
|
||||
requestId: event.payload.messageId,
|
||||
}).pipe(Effect.ignore({ log: true, message: "failed to report canceled queued message" }));
|
||||
}
|
||||
});
|
||||
|
||||
const resumeTurnsAfterCompaction = Effect.fn("resumeTurnsAfterCompaction")(function* (
|
||||
threadId: ThreadId,
|
||||
) {
|
||||
const queued = turnsAfterCompaction.get(threadId) ?? [];
|
||||
while (queued.length > 0 && turnsAfterCompaction.get(threadId) === queued) {
|
||||
const event = queued[0]!;
|
||||
const turnStart = yield* projectionSnapshotQuery.getTurnStartMessage({
|
||||
threadId,
|
||||
messageId: event.payload.messageId,
|
||||
});
|
||||
if (turnsAfterCompaction.get(threadId) !== queued) return;
|
||||
// In flight from here on: a cancellation reports it when the replay runs, not from the queue.
|
||||
queued.shift();
|
||||
if (Option.isNone(turnStart)) continue;
|
||||
// Reissue the durable request after restoration clears compaction's
|
||||
// pending slot. Reusing the message id preserves a single user bubble.
|
||||
const commandId = yield* serverCommandId("after-compaction");
|
||||
const sent = yield* Deferred.make<void>();
|
||||
resumedTurnStarts.set(commandId, { event, queued, sent });
|
||||
const { messageId, ...request } = event.payload;
|
||||
yield* orchestrationEngine
|
||||
.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId,
|
||||
...request,
|
||||
message: {
|
||||
messageId,
|
||||
role: "user",
|
||||
text: turnStart.value.message.text,
|
||||
attachments: turnStart.value.message.attachments ?? [],
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.onError(() =>
|
||||
Effect.sync(() => {
|
||||
resumedTurnStarts.delete(commandId);
|
||||
queued.unshift(event);
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Deferred.await(sent);
|
||||
resumedTurnStarts.delete(commandId);
|
||||
}
|
||||
if (turnsAfterCompaction.get(threadId) === queued) turnsAfterCompaction.delete(threadId);
|
||||
});
|
||||
|
||||
const formatFailureDetail = (cause: Cause.Cause<unknown>): string => {
|
||||
const failReason = cause.reasons.find(Cause.isFailReason);
|
||||
if (isProviderAdapterRequestError(failReason?.error)) {
|
||||
@@ -1181,8 +1260,11 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
const processTurnStartRequested = Effect.fn("processTurnStartRequested")(function* (
|
||||
event: Extract<ProviderIntentEvent, { type: "thread.turn-start-requested" }>,
|
||||
receivedEvent: Extract<ProviderIntentEvent, { type: "thread.turn-start-requested" }>,
|
||||
) {
|
||||
const resumed =
|
||||
receivedEvent.commandId !== null ? resumedTurnStarts.get(receivedEvent.commandId) : undefined;
|
||||
const event = resumed ? { ...receivedEvent, payload: resumed.event.payload } : receivedEvent;
|
||||
const key = turnStartKeyForEvent(event);
|
||||
if (yield* hasHandledTurnStartRecently(key)) {
|
||||
return;
|
||||
@@ -1219,6 +1301,12 @@ const make = Effect.gen(function* () {
|
||||
createdAt: event.payload.createdAt,
|
||||
requestId: event.payload.messageId,
|
||||
});
|
||||
if (resumed && turnsAfterCompaction.get(event.payload.threadId) !== resumed.queued) {
|
||||
return yield* appendTurnStartFailure(
|
||||
"Queued message was not sent",
|
||||
"The queued message was canceled before it could resume. Send it again to continue.",
|
||||
);
|
||||
}
|
||||
|
||||
const handleTurnStartFailure = (cause: Cause.Cause<unknown>) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
@@ -1381,6 +1469,7 @@ const make = Effect.gen(function* () {
|
||||
const latestThread = yield* resolveThreadShell(event.payload.threadId);
|
||||
if (
|
||||
compactingThreadIds.has(event.payload.threadId) ||
|
||||
turnsAfterCompaction.has(event.payload.threadId) ||
|
||||
latestThread?.session?.status === "starting" ||
|
||||
latestThread?.session?.status === "running"
|
||||
) {
|
||||
@@ -1391,6 +1480,9 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
compactingThreadIds.add(event.payload.threadId);
|
||||
const clearCompacting = Effect.sync(
|
||||
() => void compactingThreadIds.delete(event.payload.threadId),
|
||||
);
|
||||
yield* Effect.gen(function* () {
|
||||
yield* ensureSessionForThread(
|
||||
event.payload.threadId,
|
||||
@@ -1410,17 +1502,32 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
}).pipe(
|
||||
Effect.andThen(restoreCompaction(event.payload.threadId, true)),
|
||||
Effect.catchCause(recoverCompactionFailure),
|
||||
Effect.ensuring(Effect.sync(() => void compactingThreadIds.delete(event.payload.threadId))),
|
||||
Effect.andThen(clearCompacting),
|
||||
Effect.andThen(resumeTurnsAfterCompaction(event.payload.threadId)),
|
||||
Effect.catchCause((cause) =>
|
||||
recoverCompactionFailure(cause).pipe(
|
||||
Effect.ensuring(clearCompacting),
|
||||
Effect.andThen(
|
||||
cancelTurnsAfterCompaction(
|
||||
event.payload.threadId,
|
||||
"Context compaction failed. Send this message again to continue.",
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (compactingThreadIds.has(event.payload.threadId)) {
|
||||
return yield* appendTurnStartFailure(
|
||||
"Provider turn start failed",
|
||||
"Wait for context compaction to finish before sending another message.",
|
||||
);
|
||||
if (
|
||||
!resumed &&
|
||||
(compactingThreadIds.has(event.payload.threadId) ||
|
||||
turnsAfterCompaction.has(event.payload.threadId))
|
||||
) {
|
||||
const queued = turnsAfterCompaction.get(event.payload.threadId) ?? [];
|
||||
queued.push(event);
|
||||
turnsAfterCompaction.set(event.payload.threadId, queued);
|
||||
return;
|
||||
}
|
||||
const sendTurnRequest = yield* buildSendTurnRequestForThread({
|
||||
threadId: event.payload.threadId,
|
||||
@@ -1440,14 +1547,24 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* providerService
|
||||
const send = providerService
|
||||
.sendTurn(sendTurnRequest.value)
|
||||
.pipe(Effect.asVoid, Effect.catchCause(recoverTurnStartFailure), Effect.forkScoped);
|
||||
.pipe(Effect.asVoid, Effect.catchCause(recoverTurnStartFailure));
|
||||
// The forked send settles `sent` from here on, so drop the entry the post-processing hook uses.
|
||||
if (resumed && event.commandId !== null) resumedTurnStarts.delete(event.commandId);
|
||||
yield* send.pipe(
|
||||
Effect.ensuring(resumed ? Deferred.succeed(resumed.sent, undefined) : Effect.void),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
});
|
||||
|
||||
const processTurnInterruptRequested = Effect.fn("processTurnInterruptRequested")(function* (
|
||||
event: Extract<ProviderIntentEvent, { type: "thread.turn-interrupt-requested" }>,
|
||||
) {
|
||||
yield* cancelTurnsAfterCompaction(
|
||||
event.payload.threadId,
|
||||
"Context compaction was interrupted. Send this message again to continue.",
|
||||
);
|
||||
const thread = yield* resolveThreadShell(event.payload.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
@@ -1643,11 +1760,15 @@ const make = Effect.gen(function* () {
|
||||
const wasCompacting = compactingThreadIds.has(thread.id);
|
||||
stoppingThreadIds.add(thread.id);
|
||||
const clearStopping = Effect.sync(() => void stoppingThreadIds.delete(thread.id));
|
||||
yield* (
|
||||
thread.session && thread.session.status !== "stopped"
|
||||
? providerService.stopSession({ threadId: thread.id })
|
||||
: Effect.void
|
||||
yield* cancelTurnsAfterCompaction(
|
||||
thread.id,
|
||||
"The session was stopped during context compaction. Send this message again to continue.",
|
||||
).pipe(
|
||||
Effect.andThen(
|
||||
thread.session && thread.session.status !== "stopped"
|
||||
? providerService.stopSession({ threadId: thread.id })
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.matchCauseEffect({
|
||||
onFailure: (cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
@@ -1761,6 +1882,14 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const processDomainEventSafely = (event: ProviderIntentEvent) =>
|
||||
processDomainEvent(event).pipe(
|
||||
// A replay that returned before forking its send still holds its entry; settle it so
|
||||
// the compaction queue moves on. Forked sends drop the entry first and settle it themselves.
|
||||
Effect.ensuring(
|
||||
Effect.suspend(() => {
|
||||
const resumed = event.commandId !== null && resumedTurnStarts.get(event.commandId);
|
||||
return resumed ? Deferred.succeed(resumed.sent, undefined) : Effect.void;
|
||||
}),
|
||||
),
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.interrupt;
|
||||
|
||||
Reference in new issue
Block a user