Skip to content

Commit 8894d8c

Browse files
t3dotggclaude
andcommitted
fix: side chat review round 4
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 6cad857 commit 8894d8c

17 files changed

Lines changed: 252 additions & 62 deletions

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,11 @@ export const isCheckpointRestoreIsolated = Effect.fn("orchestrationV2.isCheckpoi
4949
for (const otherThread of [...shell.threads, ...shell.archivedThreads]) {
5050
if (otherThread.id === thread.id || otherThread.deletedAt !== null) continue;
5151
// An idle side chat that only answered questions never touched the shared worktree.
52-
if (otherThread.lineage.sideChat === true && otherThread.activeRunId === null) {
52+
if (
53+
otherThread.lineage.sideChat === true &&
54+
otherThread.activeRunId === null &&
55+
otherThread.worktreePath === worktreePath
56+
) {
5357
const { turnItems } = yield* projections.getThreadRecords(
5458
otherThread.id,
5559
["turnItems"],

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,26 @@ function compactText(text: string, maxLength = 240): string {
108108
return `${compacted.slice(0, maxLength - 3)}...`;
109109
}
110110

111+
export function visibleDeltaRunOrdinals(
112+
projection: { readonly runs: ReadonlyArray<Pick<OrchestrationV2Run, "id" | "ordinal">> },
113+
items: ReadonlyArray<OrchestrationV2TurnItem>,
114+
): OrchestrationV2ContextHandoff["coveredRunOrdinals"] {
115+
const ordinals = items.flatMap((item) => {
116+
if (item.runId === null) {
117+
return [];
118+
}
119+
const run = projection.runs.find((candidate) => candidate.id === item.runId);
120+
return run === undefined ? [] : [run.ordinal];
121+
});
122+
if (ordinals.length === 0) {
123+
return { from: 1, to: 1 };
124+
}
125+
return {
126+
from: Math.min(...ordinals),
127+
to: Math.max(...ordinals),
128+
};
129+
}
130+
111131
export function summarizeDeltaItem(item: OrchestrationV2TurnItem): string | null {
112132
switch (item.type) {
113133
case "user_message":

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

Lines changed: 22 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ import {
5959
latestProviderTurnForAttempt,
6060
parseGoalCommand,
6161
orchestrationV2RunWorkStartedAt,
62+
orchestrationV2WorktreePending,
6263
ProviderInstanceId,
6364
ProviderInteractionMode,
6465
resolveProviderInstanceEnabled,
@@ -103,7 +104,7 @@ import {
103104
resolveMessageDispatchIntent,
104105
} from "./CommandPolicy.ts";
105106
import { CommandReceiptStoreV2 } from "./CommandReceiptStore.ts";
106-
import { ContextHandoffServiceV2 } from "./ContextHandoffService.ts";
107+
import { ContextHandoffServiceV2, visibleDeltaRunOrdinals } from "./ContextHandoffService.ts";
107108
import { notificationTurnItem } from "@t3tools/provider-core/server/notification";
108109
import {
109110
cancelledBeforeStart,
@@ -896,26 +897,6 @@ function latestContextTransfer(
896897
}, undefined);
897898
}
898899

899-
function visibleDeltaRunOrdinals(
900-
projection: Pick<OrchestrationV2ThreadProjection, "runs">,
901-
items: ReadonlyArray<OrchestrationV2TurnItem>,
902-
): OrchestrationV2ContextHandoff["coveredRunOrdinals"] {
903-
const ordinals = items.flatMap((item) => {
904-
if (item.runId === null) {
905-
return [];
906-
}
907-
const run = projection.runs.find((candidate) => candidate.id === item.runId);
908-
return run === undefined ? [] : [run.ordinal];
909-
});
910-
if (ordinals.length === 0) {
911-
return { from: 1, to: 1 };
912-
}
913-
return {
914-
from: Math.min(...ordinals),
915-
to: Math.max(...ordinals),
916-
};
917-
}
918-
919900
export function shouldPrepareLegacyImportHandoff(input: {
920901
readonly hasCompletedRun: boolean;
921902
readonly historyOrigin: OrchestrationV2AppThread["historyOrigin"];
@@ -4151,6 +4132,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
41514132
cause: `Thread ${command.sourceThreadId} was deleted.`,
41524133
});
41534134
}
4135+
// The fork would copy no worktree path and run in the project checkout.
4136+
if (
4137+
command.sideChat === true &&
4138+
orchestrationV2WorktreePending(sourceProjection.thread.worktreePath, sourceProjection.runs)
4139+
) {
4140+
return yield* new OrchestratorDispatchError({
4141+
commandId: command.commandId,
4142+
commandType: command.type,
4143+
cause: `Thread ${command.sourceThreadId} is still preparing its worktree. Start the side chat once it is ready.`,
4144+
});
4145+
}
41544146
if ((yield* findThread(command.targetThreadId)) !== null) {
41554147
return yield* new OrchestratorThreadAlreadyExistsError({
41564148
commandId: command.commandId,
@@ -6546,13 +6538,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
65466538
}),
65476539
),
65486540
);
6541+
// Without a source run the digest covers the parent's whole history, imported items included.
6542+
const sideChatParentRunIds = [
6543+
...sourceRunsAfterFork.map((run) => run.id),
6544+
...(sourceRun === null && sourceProjection?.thread.historyOrigin === "v1_import"
6545+
? [null]
6546+
: []),
6547+
];
65496548
const sideChatParentItems =
6550-
!sideChatFork || sourceRunsAfterFork.length === 0 || sourceProjection === null
6549+
!sideChatFork || sideChatParentRunIds.length === 0 || sourceProjection === null
65516550
? []
6552-
: yield* readHandoffItems(
6553-
sourceProjection.thread.id,
6554-
sourceRunsAfterFork.map((run) => run.id),
6555-
);
6551+
: yield* readHandoffItems(sourceProjection.thread.id, sideChatParentRunIds);
65566552
// The framing note goes in even when the parent has no activity after the fork point.
65576553
const sideChatContextHandoff =
65586554
!sideChatFork || pendingForkTransfer === undefined || sourceProjection === null

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

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1191,11 +1191,16 @@ effectIt.effect.each([
11911191
);
11921192

11931193
effectIt.effect.each([
1194-
{ nativeForkFrom: "idle", forks: true, transferStatus: "consumed" },
1195-
{ nativeForkFrom: "busy", forks: false, transferStatus: "resolved_portable" },
1194+
{ nativeForkFrom: "idle", forks: true, transferStatus: "consumed", handoffIds: [] },
1195+
{
1196+
nativeForkFrom: "busy",
1197+
forks: false,
1198+
transferStatus: "resolved_portable",
1199+
handoffIds: ["side-chat-fork-context"],
1200+
},
11961201
] as const)(
11971202
"runs a planned native side chat fork when the parent is $nativeForkFrom",
1198-
({ nativeForkFrom, forks, transferStatus }) =>
1203+
({ nativeForkFrom, forks, transferStatus, handoffIds }) =>
11991204
Effect.gen(function* () {
12001205
const harness = makeLocalCommandHarness({
12011206
text: "What is the main thread doing?",
@@ -1211,6 +1216,7 @@ effectIt.effect.each([
12111216
expect(harness.startTurn.mock.calls[0]?.[0].message.text.includes("PARENT_HISTORY")).toBe(
12121217
!forks,
12131218
);
1219+
expect(harness.projection().providerThreads[0]?.handoffIds).toEqual(handoffIds);
12141220
}),
12151221
);
12161222

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

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1046,7 +1046,7 @@ export const layer: Layer.Layer<
10461046
};
10471047
let resumedRetryHandoff: ReadonlyArray<OrchestrationV2ContextHandoff> | undefined;
10481048
let resumedHandoffContext: ReturnType<typeof handoffContextForThread> | undefined;
1049-
let forkFellBackToPortable = false;
1049+
let portableForkFallback: OrchestrationV2ContextHandoff | undefined;
10501050
const loadedProviderThread = yield* Effect.gen(function* () {
10511051
if (nativeForkTransfer !== undefined) {
10521052
const sourceProjection = yield* projectionStore.getThreadRecords(
@@ -1118,7 +1118,10 @@ export const layer: Layer.Layer<
11181118
toProviderThreadId: providerThread.id,
11191119
fromProviderInstanceId: sourceRun.providerInstanceId,
11201120
toProviderInstanceId: run.providerInstanceId,
1121-
coveredRunOrdinals: { from: 1, to: sourceRun.ordinal },
1121+
coveredRunOrdinals: ContextHandoffService.visibleDeltaRunOrdinals(
1122+
sourceProjection,
1123+
sourceItems,
1124+
),
11221125
strategy: "full_thread_summary",
11231126
items: sourceItems,
11241127
runs: sourceProjection.runs,
@@ -1135,7 +1138,7 @@ export const layer: Layer.Layer<
11351138
}),
11361139
);
11371140
if (loaded === undefined) return undefined;
1138-
forkFellBackToPortable = true;
1141+
portableForkFallback = handoff;
11391142
effectiveHandoffs = [handoff, ...effectiveHandoffs];
11401143
yield* eventSink.write({
11411144
events: [
@@ -1356,8 +1359,11 @@ export const layer: Layer.Layer<
13561359
ownerNodeId: providerThread.ownerNodeId,
13571360
firstRunOrdinal: providerThread.firstRunOrdinal ?? run.ordinal,
13581361
lastRunOrdinal: run.ordinal,
1359-
handoffIds: providerThread.handoffIds,
1360-
forkedFrom: forkFellBackToPortable ? null : providerThread.forkedFrom,
1362+
handoffIds:
1363+
portableForkFallback === undefined
1364+
? providerThread.handoffIds
1365+
: [...providerThread.handoffIds, portableForkFallback.id],
1366+
forkedFrom: portableForkFallback === undefined ? providerThread.forkedFrom : null,
13611367
status: "active",
13621368
createdAt: providerThread.createdAt,
13631369
updatedAt: now,
@@ -1403,7 +1409,7 @@ export const layer: Layer.Layer<
14031409
payload: runningProviderThread,
14041410
},
14051411
...(nativeForkTransfer === undefined ||
1406-
forkFellBackToPortable ||
1412+
portableForkFallback !== undefined ||
14071413
runningProviderThread.nativeThreadRef === null
14081414
? []
14091415
: [

‎apps/server/src/orchestration-v2/ThreadFork.execution.test.ts‎

Lines changed: 76 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -613,7 +613,7 @@ const writeParentRun = (input: {
613613
readonly threadId: ThreadId;
614614
readonly runId: RunId;
615615
readonly ordinal: number;
616-
readonly status: "running" | "completed";
616+
readonly status: "preparing" | "running" | "completed";
617617
readonly text: string;
618618
/** A checkpointed run on a native provider thread, which `latest_stable` forks start from. */
619619
readonly stable?: boolean;
@@ -682,6 +682,9 @@ const writeParentRun = (input: {
682682
completedAt: input.status === "completed" ? now : null,
683683
checkpointId: input.stable ? CheckpointId.make(`${input.runId}:checkpoint`) : null,
684684
contextHandoffId: null,
685+
...(input.status === "preparing"
686+
? { workspacePreparation: { type: "worktree" as const, baseRef: "main" } }
687+
: {}),
685688
},
686689
},
687690
{
@@ -718,6 +721,55 @@ const writeParentRun = (input: {
718721
});
719722
});
720723

724+
/** Marks `threadId` as imported from V1 and gives it one runless imported user message. */
725+
const writeImportedHistory = (threadId: ThreadId, text: string) =>
726+
Effect.gen(function* () {
727+
const orchestrator = yield* Orchestrator.OrchestratorV2;
728+
const eventSink = yield* EventSink.EventSinkV2;
729+
const now = yield* DateTime.now;
730+
const { thread } = yield* orchestrator.getThreadProjection(threadId);
731+
yield* eventSink.write({
732+
events: [
733+
{
734+
id: EventId.make(`${threadId}:imported`),
735+
type: "thread.metadata-updated",
736+
threadId,
737+
occurredAt: now,
738+
payload: { ...thread, historyOrigin: "v1_import" },
739+
},
740+
{
741+
id: EventId.make(`${threadId}:imported-item`),
742+
type: "turn-item.updated",
743+
threadId,
744+
occurredAt: now,
745+
payload: {
746+
id: TurnItemId.make(`${threadId}:imported-item`),
747+
threadId,
748+
runId: null,
749+
nodeId: null,
750+
providerThreadId: null,
751+
providerTurnId: null,
752+
nativeItemRef: null,
753+
parentItemId: null,
754+
ordinal: 1,
755+
status: "completed",
756+
title: null,
757+
startedAt: now,
758+
completedAt: now,
759+
updatedAt: now,
760+
type: "user_message",
761+
createdBy: "user",
762+
creationSource: "web",
763+
inputIntent: "turn_start",
764+
messageId: MessageId.make(`${threadId}:imported-message`),
765+
text,
766+
attachments: [],
767+
},
768+
},
769+
],
770+
});
771+
});
772+
721773
const createParent = (threadId: ThreadId) =>
722774
Effect.gen(function* () {
723775
const orchestrator = yield* Orchestrator.OrchestratorV2;
@@ -797,6 +849,27 @@ it.effect("a side chat of an idle parent still starts with the framing note", ()
797849
}).pipe(Effect.provide(forkCases[0]!.layer)),
798850
);
799851

852+
it.effect("a side chat waits for the parent's new worktree", () =>
853+
Effect.gen(function* () {
854+
const parentId = ThreadId.make("side-chat-worktree-parent");
855+
yield* createParent(parentId);
856+
yield* writeParentRun({
857+
threadId: parentId,
858+
runId: RunId.make("side-chat-worktree-parent-run"),
859+
ordinal: 1,
860+
status: "preparing",
861+
text: "Parent work",
862+
});
863+
864+
const rejected = yield* forkSideChat(
865+
"side-chat-worktree-fork",
866+
parentId,
867+
ThreadId.make("side-chat-worktree-child"),
868+
).pipe(Effect.flip);
869+
assert.include(String(rejected.cause), "still preparing its worktree");
870+
}).pipe(Effect.provide(forkCases[0]!.layer)),
871+
);
872+
800873
it.effect("closing a side chat deletes it only while unused; a deleted parent takes no more", () =>
801874
Effect.gen(function* () {
802875
const orchestrator = yield* Orchestrator.OrchestratorV2;
@@ -849,6 +922,7 @@ it.effect("a side chat opened during the parent's first turn starts from a diges
849922
const parentId = ThreadId.make("side-chat-busy-parent");
850923
const sideChatId = ThreadId.make("side-chat-busy-child");
851924
yield* createParent(parentId);
925+
yield* writeImportedHistory(parentId, "PARENT_IMPORTED_MARKER");
852926
yield* writeParentRun({
853927
threadId: parentId,
854928
runId: RunId.make("side-chat-busy-parent-run"),
@@ -934,6 +1008,7 @@ it.effect("a side chat opened during the parent's first turn starts from a diges
9341008
contextHandoffId: handoff!.id,
9351009
});
9361010
assert.include(handoff!.summaryText, "You are in a side chat beside the main thread.");
1011+
assert.include(handoff!.summaryText, "- User: PARENT_IMPORTED_MARKER");
9371012
assert.include(handoff!.summaryText, "- User: PARENT_RUNNING_MARKER");
9381013
assert.include(handoff!.summaryText, `t3_thread_read on thread ${parentId}`);
9391014
assert.equal(

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,5 +270,19 @@ it.effect("marks only requested forks as supervised side chats", () =>
270270
Effect.flip,
271271
);
272272
assert.equal(nested.cause, "A side chat cannot start another side chat.");
273+
274+
const subagentSource = makeSourceProjection(sourceRun);
275+
const fromSubagent = yield* planFork(
276+
sourceRun,
277+
{
278+
...subagentSource,
279+
thread: {
280+
...subagentSource.thread,
281+
lineage: { ...subagentSource.thread.lineage, relationshipToParent: "subagent" },
282+
},
283+
},
284+
{ sideChat: true },
285+
).pipe(Effect.flip);
286+
assert.equal(fromSubagent.cause, "A subagent cannot start a side chat.");
273287
}),
274288
);

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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,11 +76,17 @@ export const layer: Layer.Layer<ThreadForkServiceV2> = Layer.succeed(
7676
ThreadForkServiceV2.of({
7777
plan: Effect.fn("ThreadForkService.plan")(function* (input) {
7878
const { sourceRun } = input;
79-
if (input.sideChat && input.sourceProjection.thread.lineage.sideChat) {
79+
const sourceLineage = input.sourceProjection.thread.lineage;
80+
if (
81+
input.sideChat &&
82+
(sourceLineage.sideChat || sourceLineage.relationshipToParent === "subagent")
83+
) {
8084
return yield* new ThreadForkPlanError({
8185
sourceThreadId: input.sourceProjection.thread.id,
8286
targetThreadId: input.targetThreadId,
83-
cause: "A side chat cannot start another side chat.",
87+
cause: sourceLineage.sideChat
88+
? "A side chat cannot start another side chat."
89+
: "A subagent cannot start a side chat.",
8490
});
8591
}
8692
if (sourceRun !== null && !isForkableSourceRunStatus(sourceRun.status)) {

‎apps/server/src/serverRuntimeStartup.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
DEFAULT_MODEL,
44
DEFAULT_PROVIDER_INTERACTION_MODE,
55
DEFAULT_SERVER_SETTINGS,
6+
isListedThreadLineage,
67
type ModelSelection,
78
type Project,
89
ProjectId,
@@ -281,8 +282,7 @@ const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
281282
});
282283
const shell = yield* threads.getShellSnapshot();
283284
const existingThread = shell.threads.find(
284-
(thread) =>
285-
thread.projectId === project.id && thread.lineage.relationshipToParent !== "subagent",
285+
(thread) => thread.projectId === project.id && isListedThreadLineage(thread.lineage),
286286
);
287287
if (existingThread === undefined) {
288288
const serverSettings = yield* ServerSettings.ServerSettingsService;

0 commit comments

Comments
 (0)