Skip to content

Commit 94a73f4

Browse files
maria-rcksclaude
andcommitted
refactor(chat): drop compaction changes from handoff preview
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 0d793e1 commit 94a73f4

8 files changed

Lines changed: 83 additions & 248 deletions

File tree

‎apps/mobile/src/features/threads/ThreadDetailScreen.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1440,7 +1440,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
14401440
environmentLabel={props.environmentLabel}
14411441
selectedThread={props.selectedThread}
14421442
hasCompactableConversation={
1443-
hasCompactableConversation && !props.isCompacting && !props.pendingHandoff
1443+
hasCompactableConversation && !props.isCompacting
14441444
}
14451445
serverConfig={props.serverConfig}
14461446
queueCount={props.selectedThreadQueueCount}

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 10 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -784,29 +784,18 @@ function rootProviderThreadsForProvider(
784784
}
785785

786786
// Failed and interrupted turns still contain conversation the next provider needs.
787-
// Queued, cancelled, rolled-back and never-started maintenance runs add no conversation.
788-
function isHandoffSourceRun(
789-
run: OrchestrationV2Run,
790-
messages: OrchestrationV2ThreadProjection["messages"],
791-
): boolean {
792-
return (
793-
(run.status === "completed" || run.status === "failed" || run.status === "interrupted") &&
794-
!(
795-
run.startedAt === null &&
796-
messages.some(
797-
(message) => message.id === run.userMessageId && isNativeMaintenanceCommand(message),
798-
)
799-
)
800-
);
787+
// Queued, cancelled, and rolled-back runs must not be replayed as conversation.
788+
function isHandoffSourceRun(run: OrchestrationV2Run): boolean {
789+
return run.status === "completed" || run.status === "failed" || run.status === "interrupted";
801790
}
802791

803792
function lastDeliveredRunForProviderThread(
804-
projection: Pick<OrchestrationV2ThreadProjection, "runs" | "providerTurns" | "messages">,
793+
projection: Pick<OrchestrationV2ThreadProjection, "runs" | "providerTurns">,
805794
providerThreadId: OrchestrationV2ProviderThread["id"],
806795
): OrchestrationV2Run | undefined {
807796
return projection.runs.findLast(
808797
(run) =>
809-
isHandoffSourceRun(run, projection.messages) &&
798+
isHandoffSourceRun(run) &&
810799
run.providerThreadId === providerThreadId &&
811800
(run.status === "completed" ||
812801
projection.providerTurns.some((turn) => turn.runAttemptId === run.activeAttemptId)),
@@ -1476,9 +1465,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
14761465
),
14771466
);
14781467
const latestCompletedRun = projection.runs.findLast((run) => run.status === "completed");
1479-
const latestHandoffRun = projection.runs.findLast((run) =>
1480-
isHandoffSourceRun(run, projection.messages),
1481-
);
1468+
const latestHandoffRun = projection.runs.findLast(isHandoffSourceRun);
14821469
const targetLastCompletedRun = lastDeliveredRunForProviderThread(
14831470
projection,
14841471
queuedProviderThread.id,
@@ -1490,7 +1477,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
14901477
? []
14911478
: projection.runs.filter(
14921479
(run) =>
1493-
isHandoffSourceRun(run, projection.messages) &&
1480+
isHandoffSourceRun(run) &&
14941481
run.ordinal > (targetLastCompletedRun?.ordinal ?? 0) &&
14951482
run.ordinal <= latestHandoffRun.ordinal,
14961483
);
@@ -4914,16 +4901,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
49144901
return;
49154902
}
49164903

4917-
// A prepared destination has not replaced the source conversation until
4918-
// its run starts. Failed starts must still allow returning to the source.
4919-
const latestStartedProviderRun = projection.runs.findLast(
4920-
(run) =>
4921-
run.status !== "rolled_back" && run.startedAt !== null && run.providerThreadId !== null,
4922-
);
49234904
const activeProviderThread = projection.providerThreads.find(
4924-
(candidate) =>
4925-
candidate.id ===
4926-
(latestStartedProviderRun?.providerThreadId ?? projection.thread.activeProviderThreadId),
4905+
(candidate) => candidate.id === projection.thread.activeProviderThreadId,
49274906
);
49284907
const activeRun = projection.runs.find(isBlockingRun);
49294908
// A message queued during worktree setup can arrive after that setup failed
@@ -5263,9 +5242,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
52635242
const ordinal = nextRunOrdinal(projection);
52645243
const runId = idAllocator.derive.run({ threadId: command.threadId, ordinal });
52655244
const latestCompletedRun = projection.runs.findLast((run) => run.status === "completed");
5266-
const latestHandoffRun = projection.runs.findLast((run) =>
5267-
isHandoffSourceRun(run, projection.messages),
5268-
);
5245+
const latestHandoffRun = projection.runs.findLast(isHandoffSourceRun);
52695246
const legacyImportItems =
52705247
projection.thread.historyOrigin === "v1_import"
52715248
? yield* readHandoffItems(command.threadId, [null])
@@ -5851,7 +5828,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
58515828
? []
58525829
: projection.runs.filter(
58535830
(run) =>
5854-
isHandoffSourceRun(run, projection.messages) &&
5831+
isHandoffSourceRun(run) &&
58555832
run.ordinal >
58565833
(requiresFullProviderSwitchContext
58575834
? 0

‎apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,6 @@ it("does not commit running state when inherited background routing cannot be re
7676
nodes: [{ id: rootNodeId, checkpointScopeId }],
7777
attempts: [{ id: attemptId }],
7878
providerThreads: [{ id: providerThreadId, providerSessionId }],
79-
providerTurns: [],
8079
messages: [{ id: messageId, text: "Continue", attachments: [] }],
8180
checkpointScopes: [{ id: checkpointScopeId }],
8281
contextHandoffs: [],
@@ -248,7 +247,6 @@ function makeLocalCommandHarness(input: {
248247
id: RunId.make("previous-native-run"),
249248
ordinal: 1,
250249
status: "completed" as const,
251-
startedAt: now,
252250
providerInstanceId: oldInstanceId,
253251
providerThreadId: oldProviderThreadId,
254252
},
@@ -791,7 +789,7 @@ effectIt.effect(
791789
expect(harness.open).not.toHaveBeenCalled();
792790
expect(harness.startRootRun).not.toHaveBeenCalled();
793791
const projection = harness.projection();
794-
expect(projection.runs.at(-1)).toMatchObject({ status: "completed", startedAt: null });
792+
expect(projection.runs.at(-1)?.status).toBe("completed");
795793
expect(projection.attempts[0]?.status).toBe("completed");
796794
expect(projection.nodes[0]?.status).toBe("completed");
797795
expect(projection.turnItems).toMatchObject([
@@ -818,7 +816,7 @@ effectIt.effect("persists a failed sign-out without starting a provider turn", (
818816

819817
expect(harness.open).not.toHaveBeenCalled();
820818
expect(harness.startRootRun).not.toHaveBeenCalled();
821-
expect(harness.projection().runs.at(-1)).toMatchObject({ status: "failed", startedAt: null });
819+
expect(harness.projection().runs.at(-1)?.status).toBe("failed");
822820
expect(harness.projection().turnItems).toMatchObject([
823821
{
824822
type: "error",
@@ -844,10 +842,7 @@ for (const previousMessages of [[], ["/compact", " /COMPACT "]]) {
844842
expect(harness.open).not.toHaveBeenCalled();
845843
expect(harness.tryHandlePromptCommand).not.toHaveBeenCalled();
846844
expect(harness.startRootRun).not.toHaveBeenCalled();
847-
expect(harness.projection().runs.at(-1)).toMatchObject({
848-
status: "failed",
849-
startedAt: null,
850-
});
845+
expect(harness.projection().runs.at(-1)?.status).toBe("failed");
851846
expect(harness.projection().turnItems).toMatchObject([
852847
{
853848
type: "error",

‎apps/server/src/orchestration-v2/ProviderTurnStartService.ts‎

Lines changed: 20 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -280,31 +280,6 @@ export const layer: Layer.Layer<
280280
cause: `Run ${runId} is missing its execution projection state.`,
281281
});
282282
}
283-
const deliveredAttemptIds = new Set(
284-
projection.providerTurns.map((turn) => turn.runAttemptId),
285-
);
286-
const readHandoffHistory = Effect.fn(function* (runIds?: ReadonlyArray<RunId>) {
287-
const items = yield* projectionStore.getTurnStartHistory(input.threadId, runIds);
288-
const maintenanceMessageIds = new Set(
289-
items.flatMap((item) =>
290-
item.type === "user_message" &&
291-
item.attachments.length === 0 &&
292-
["/compact", "/logout"].includes(item.text.trim().toLowerCase())
293-
? [item.messageId]
294-
: [],
295-
),
296-
);
297-
const excludedRunIds = new Set(
298-
projection.runs
299-
.filter(
300-
(source) =>
301-
maintenanceMessageIds.has(source.userMessageId) &&
302-
!deliveredAttemptIds.has(source.activeAttemptId),
303-
)
304-
.map((source) => source.id),
305-
);
306-
return items.filter((item) => item.runId === null || !excludedRunIds.has(item.runId));
307-
});
308283
// Settles a run that never reached the provider: one signal turn item plus
309284
// terminal run, attempt and root node, written only while the run is still
310285
// the current starting attempt.
@@ -313,6 +288,8 @@ export const layer: Layer.Layer<
313288
readonly signal: string;
314289
readonly status: "completed" | "failed";
315290
readonly now: DateTime.Utc;
291+
/** Omitted when the run never started, so `startedAt` stays as projected. */
292+
readonly startedAt?: DateTime.Utc;
316293
readonly providerInstanceId: OrchestrationV2Run["providerInstanceId"];
317294
readonly itemProviderThreadId: OrchestrationV2ProviderThread["id"];
318295
readonly item:
@@ -328,6 +305,7 @@ export const layer: Layer.Layer<
328305
readonly providerThreadUpdate?: OrchestrationV2ProviderThread;
329306
}) {
330307
const { now, status } = input;
308+
const started = input.startedAt === undefined ? {} : { startedAt: input.startedAt };
331309
const item: OrchestrationV2TurnItem = {
332310
id: idAllocator.derive.runSignalTurnItem({ runId, signal: input.signal }),
333311
threadId: projection.thread.id,
@@ -352,14 +330,14 @@ export const layer: Layer.Layer<
352330
};
353331
const eventPayloads = [
354332
{ type: "turn-item.updated", payload: item },
355-
{ type: "run.updated", payload: { ...run, status, completedAt: now } },
333+
{ type: "run.updated", payload: { ...run, status, ...started, completedAt: now } },
356334
{
357335
type: "run-attempt.updated",
358-
payload: { ...attempt, status, completedAt: now },
336+
payload: { ...attempt, status, ...started, completedAt: now },
359337
},
360338
{
361339
type: "node.updated",
362-
payload: { ...rootNode, status, completedAt: now },
340+
payload: { ...rootNode, status, ...started, completedAt: now },
363341
},
364342
...(input.providerThreadUpdate === undefined
365343
? []
@@ -407,7 +385,6 @@ export const layer: Layer.Layer<
407385
const previousNativeRun = projection.runs.reduce<OrchestrationV2Run | undefined>(
408386
(previous, candidate) =>
409387
candidate.ordinal < run.ordinal &&
410-
candidate.startedAt !== null &&
411388
candidate.providerThreadId !== null &&
412389
nativeThreads.has(candidate.providerThreadId) &&
413390
(previous === undefined || candidate.ordinal > previous.ordinal)
@@ -451,6 +428,7 @@ export const layer: Layer.Layer<
451428
signal: isEmptyCompaction ? "empty-compaction" : "provider-sign-out",
452429
status,
453430
now,
431+
startedAt: now,
454432
providerInstanceId: authInstanceId,
455433
itemProviderThreadId: nativeThread?.id ?? providerThread.id,
456434
item:
@@ -747,7 +725,7 @@ export const layer: Layer.Layer<
747725
coveredRunOrdinals: { from: 1, to: Math.max(1, run.ordinal - 1) },
748726
strategy: "full_thread_summary",
749727
runs: projection.runs,
750-
items: (yield* readHandoffHistory()).filter(
728+
items: (yield* projectionStore.getTurnStartHistory(input.threadId)).filter(
751729
(item) =>
752730
item.runId === null ||
753731
projection.runs.some(
@@ -859,36 +837,6 @@ export const layer: Layer.Layer<
859837
createdAt: providerThread.createdAt,
860838
updatedAt: now,
861839
};
862-
const nativeThreadId = runningProviderThread.nativeThreadRef?.nativeId;
863-
if (
864-
message.attachments.length === 0 &&
865-
message.text.trim().toLowerCase() === "/compact" &&
866-
effectiveHandoffs.some(
867-
(handoff) =>
868-
nativeThreadId === undefined ||
869-
handoff.delivery?.nativeThreadId !== nativeThreadId ||
870-
handoff.delivery.status === "pending",
871-
)
872-
) {
873-
yield* settleRunBeforeStart({
874-
signal: "handoff-replaces-compaction",
875-
status: "failed",
876-
now,
877-
providerInstanceId: run.providerInstanceId,
878-
itemProviderThreadId: providerThread.id,
879-
item: {
880-
type: "error",
881-
title: "Context handoff replaces compaction",
882-
failure: makeProviderFailure({
883-
class: "validation_error",
884-
message:
885-
"Context handoff replaces compaction. Send a message to the selected provider, or switch back to compact the current conversation.",
886-
}),
887-
},
888-
providerThreadUpdate: { ...runningProviderThread, status: "idle" },
889-
});
890-
return;
891-
}
892840
const runningRun: OrchestrationV2Run = {
893841
...run,
894842
status: "running",
@@ -1046,6 +994,9 @@ export const layer: Layer.Layer<
1046994
...deliveredItemIds,
1047995
...settledHandoffs.flatMap((handoff) => handoff.delivery?.omittedItemIds ?? []),
1048996
]);
997+
const deliveredAttemptIds = new Set(
998+
projection.providerTurns.map((turn) => turn.runAttemptId),
999+
);
10491000
const acceptedAttempts = projection.attempts.filter(
10501001
(source) =>
10511002
source.providerThreadId === providerThread.id && deliveredAttemptIds.has(source.id),
@@ -1120,36 +1071,29 @@ export const layer: Layer.Layer<
11201071
...runningProviderThread,
11211072
contextUsage: handoffUsage,
11221073
};
1123-
const undeliveredRuns = projection.runs.filter(
1074+
const missedRuns = projection.runs.filter(
11241075
(source) =>
11251076
source.ordinal < run.ordinal &&
11261077
source.providerThreadId === providerThread.id &&
11271078
(source.status === "failed" || source.status === "interrupted") &&
11281079
!deliveredAttemptIds.has(source.activeAttemptId),
11291080
);
1081+
const missedRunIds = new Set(missedRuns.map((source) => source.id));
11301082
const missedItems =
1131-
undeliveredRuns.length === 0
1083+
missedRunIds.size === 0
11321084
? []
1133-
: (yield* readHandoffHistory(undeliveredRuns.map((source) => source.id))).filter(
1134-
(item) => !coveredItemIds.has(item.id) && historicalMessage(item) !== null,
1085+
: (yield* projectionStore.getTurnStartHistory(input.threadId, [...missedRunIds])).filter(
1086+
(item) =>
1087+
item.runId !== null &&
1088+
missedRunIds.has(item.runId) &&
1089+
!coveredItemIds.has(item.id) &&
1090+
historicalMessage(item) !== null,
11351091
);
1136-
const missedRunIds = new Set(missedItems.map((item) => item.runId));
1137-
const missedRuns = undeliveredRuns.filter((source) => missedRunIds.has(source.id));
11381092
const startWithHandoffs = (
11391093
turnInput: Parameters<typeof session.startTurn>[0],
11401094
compact = false,
11411095
) =>
11421096
Effect.gen(function* () {
1143-
if (compact && missedItems.length > 0) {
1144-
return yield* new ProviderAdapter.ProviderAdapterTurnStartError({
1145-
driver: session.driver,
1146-
threadId: projection.thread.id,
1147-
providerThreadId: providerThread.id,
1148-
runId: run.id,
1149-
cause:
1150-
"Context handoff replaces compaction. Send a message to the selected provider, or switch back to compact the current conversation.",
1151-
});
1152-
}
11531097
// A failed turn/start can leave the requested turn absent from
11541098
// native history even when its preceding handoff was injected.
11551099
const retryHandoff =

0 commit comments

Comments
 (0)