Skip to content

Commit a2fef89

Browse files
vdmkotaicodex
authored andcommitted
fix(opencode): fork the session on a cwd change instead of dropping context
The directory-mismatch guard added while hardening this PR started a fresh, EMPTY session whenever the resumed session's stored directory differed from the requested cwd. Its stated rationale -- "OpenCode routes a prompt to the session's own stored directory, so resuming under a different cwd would run in the wrong tree" -- does not hold: OpenCode resolves tool execution, snapshots and file ops from the per-request directory param (instance context), not from session.info.directory. So the guard solved a non-problem and introduced a real one: any time a thread's cwd changes (most commonly when it moves from the project root into a git worktree between turns) the whole conversation was stranded in the old session and the follow-up landed in an empty one -- the exact pingdotgg#3604 symptom this PR set out to fix. Fix: when the persisted session exists but was created under a different directory, fork it INTO the requested directory (client.session.fork({ sessionID, directory })) instead of creating an empty session. OpenCode clones the full message history into a new session bound to the requested worktree, so the follow-up keeps its context and tools still run on the correct tree. The fork id becomes the durable resume cursor. A genuinely missing (404) session still starts fresh, unchanged. Verified against the OpenCode source that fork copies all messages/parts with fresh ids and stamps the new session's directory/path from the request context. Test: the former "starts fresh on directory mismatch" case now asserts the session is forked with history (fork called, no session.create, cursor -> fork id) via a new fork mock; the not-found path still starts fresh. Co-authored-by: codex <[email protected]>
1 parent fa26ab3 commit a2fef89

2 files changed

Lines changed: 81 additions & 31 deletions

File tree

‎apps/server/src/provider/Layers/OpenCodeAdapter.test.ts‎

Lines changed: 45 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ const runtimeMock = {
7070
transientErrorSessionIds: new Set<string>(),
7171
sessionDirectoryById: new Map<string, string>(),
7272
sessionUpdateCalls: [] as Array<{ sessionID: string; permission: unknown }>,
73+
forkCalls: [] as Array<{ sessionID: string; directory?: string }>,
7374
},
7475
reset() {
7576
this.state.startCalls.length = 0;
@@ -89,6 +90,7 @@ const runtimeMock = {
8990
this.state.transientErrorSessionIds.clear();
9091
this.state.sessionDirectoryById.clear();
9192
this.state.sessionUpdateCalls.length = 0;
93+
this.state.forkCalls.length = 0;
9294
},
9395
};
9496

@@ -164,6 +166,16 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
164166
runtimeMock.state.sessionUpdateCalls.push({ sessionID, permission });
165167
return { data: { id: sessionID } };
166168
},
169+
fork: async ({ sessionID, directory }: { sessionID: string; directory?: string }) => {
170+
// Model OpenCode fork: clones history into a NEW session bound to the
171+
// requested directory (all prior messages carried over upstream).
172+
const forkedId = `${sessionID}_fork`;
173+
runtimeMock.state.forkCalls.push({ sessionID, ...(directory ? { directory } : {}) });
174+
if (directory) {
175+
runtimeMock.state.sessionDirectoryById.set(forkedId, directory);
176+
}
177+
return { data: { id: forkedId, ...(directory ? { directory } : {}) } };
178+
},
167179
abort: async ({ sessionID }: { sessionID: string }) => {
168180
runtimeMock.state.abortCalls.push(sessionID);
169181
},
@@ -469,32 +481,42 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
469481
}),
470482
);
471483

472-
it.effect("starts fresh when the resumed session is bound to a different directory", () =>
473-
Effect.gen(function* () {
474-
const adapter = yield* OpenCodeAdapter;
475-
const threadId = asThreadId("thread-opencode-cwd");
476-
// The persisted session still exists but lives in another working dir.
477-
runtimeMock.state.sessionDirectoryById.set("ses_otherdir", "/some/other/worktree");
484+
it.effect(
485+
"forks the resumed session into the requested directory instead of losing context",
486+
() =>
487+
Effect.gen(function* () {
488+
const adapter = yield* OpenCodeAdapter;
489+
const threadId = asThreadId("thread-opencode-cwd");
490+
// The persisted session still exists but was created in another working dir
491+
// (e.g. the thread moved from the project root into a git worktree).
492+
runtimeMock.state.sessionDirectoryById.set("ses_otherdir", "/some/other/worktree");
478493

479-
const session = yield* adapter.startSession({
480-
provider: ProviderDriverKind.make("opencode"),
481-
threadId,
482-
runtimeMode: "full-access",
483-
resumeCursor: { schemaVersion: 1, sessionId: "ses_otherdir" },
484-
});
494+
const session = yield* adapter.startSession({
495+
provider: ProviderDriverKind.make("opencode"),
496+
threadId,
497+
runtimeMode: "full-access",
498+
resumeCursor: { schemaVersion: 1, sessionId: "ses_otherdir" },
499+
});
485500

486-
// OpenCode routes prompts to the session's stored directory, so a cwd
487-
// change must NOT silently reuse the old-directory session — create fresh.
488-
NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, ["ses_otherdir"]);
489-
NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, ["http://127.0.0.1:9999"]);
490-
NodeAssert.deepEqual(runtimeMock.state.sessionUpdateCalls, []);
491-
NodeAssert.deepEqual(session.resumeCursor, {
492-
schemaVersion: 1,
493-
sessionId: "http://127.0.0.1:9999/session",
494-
});
501+
// A cwd change must NOT mint an empty session and drop context. OpenCode routes
502+
// tools by the request directory, so the adapter FORKS the persisted session into
503+
// the requested cwd — carrying all prior messages forward — instead of session.create.
504+
NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, ["ses_otherdir"]);
505+
NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, []);
506+
NodeAssert.equal(runtimeMock.state.forkCalls.length, 1);
507+
NodeAssert.equal(runtimeMock.state.forkCalls[0]?.sessionID, "ses_otherdir");
508+
NodeAssert.equal(typeof runtimeMock.state.forkCalls[0]?.directory, "string");
509+
// Permission ruleset re-asserted on the fork for the current runtimeMode.
510+
NodeAssert.equal(runtimeMock.state.sessionUpdateCalls.length, 1);
511+
NodeAssert.equal(runtimeMock.state.sessionUpdateCalls[0]?.sessionID, "ses_otherdir_fork");
512+
// Durable cursor now points at the history-complete fork in the new directory.
513+
NodeAssert.deepEqual(session.resumeCursor, {
514+
schemaVersion: 1,
515+
sessionId: "ses_otherdir_fork",
516+
});
495517

496-
yield* adapter.stopSession(threadId);
497-
}),
518+
yield* adapter.stopSession(threadId);
519+
}),
498520
);
499521

500522
it.effect("fails sendTurn for missing sessions through the typed error channel", () =>

‎apps/server/src/provider/Layers/OpenCodeAdapter.ts‎

Lines changed: 36 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1230,11 +1230,10 @@ export function makeOpenCodeAdapter(
12301230
)
12311231
: undefined;
12321232

1233-
// Reuse the upstream session only when it still matches the
1234-
// requested working directory. OpenCode routes a prompt to the
1235-
// session's OWN stored directory, so resuming a session created
1236-
// under a different cwd would silently run there — in that case
1237-
// start fresh in the requested directory instead.
1233+
// Reuse the upstream session as-is only when it still matches the
1234+
// requested working directory. When the cwd changed (e.g. the thread
1235+
// moved from the project root into a git worktree), the session is
1236+
// forked into the new directory below rather than reused in place.
12381237
const reusable =
12391238
adopted && (!adopted.directory || adopted.directory === directory)
12401239
? adopted
@@ -1255,11 +1254,40 @@ export function makeOpenCodeAdapter(
12551254
return { openCodeSession: reusable, created: false };
12561255
}
12571256

1257+
// The persisted session exists but was created under a DIFFERENT working
1258+
// directory (e.g. the thread moved from the project root into a git worktree
1259+
// between turns). OpenCode routes tool execution by the per-request `directory`,
1260+
// NOT the session's stored directory, so resuming under a new cwd does not run
1261+
// in the wrong tree. Fork the session INTO the requested directory instead of
1262+
// minting an empty one: this carries the full message history forward and binds
1263+
// the fork to the correct worktree, so the follow-up keeps its context (issue
1264+
// #3604, worktree cwd-change facet). Only a genuinely missing session starts fresh.
1265+
if (adopted) {
1266+
yield* Effect.logInfo(
1267+
`OpenCode session '${adopted.id}' was created under a different working directory; forking into '${directory}' to preserve conversation history.`,
1268+
);
1269+
const forkedSession = yield* runOpenCodeSdk("session.fork", () =>
1270+
client.session.fork({ sessionID: adopted.id, directory }),
1271+
);
1272+
const forked = forkedSession.data;
1273+
if (!forked) {
1274+
return yield* new OpenCodeRuntimeError({
1275+
operation: "session.fork",
1276+
detail: "OpenCode session.fork returned no session payload.",
1277+
});
1278+
}
1279+
yield* runOpenCodeSdk("session.update", () =>
1280+
client.session.update({
1281+
sessionID: forked.id,
1282+
permission: buildOpenCodePermissionRules(input.runtimeMode),
1283+
}),
1284+
);
1285+
return { openCodeSession: forked, created: true };
1286+
}
1287+
12581288
if (resumeSessionId) {
12591289
yield* Effect.logWarning(
1260-
adopted !== undefined
1261-
? `OpenCode session '${resumeSessionId}' is bound to a different working directory; starting a fresh session.`
1262-
: `OpenCode session '${resumeSessionId}' no longer exists; starting a fresh session.`,
1290+
`OpenCode session '${resumeSessionId}' no longer exists; starting a fresh session.`,
12631291
);
12641292
}
12651293
const createdSession = yield* runOpenCodeSdk("session.create", () =>

0 commit comments

Comments
 (0)