Skip to content

Commit 7be6629

Browse files
committed
fix(opencode): harden session resume per review (perms, cwd, error class)
Addresses review feedback on #3617 (macroscope + Cursor Bugbot + a deep multi-agent review) without widening scope beyond the adapter: - Re-apply permissions on resume. `session.create` is the only place the runtimeMode permission ruleset is set, so re-adopting a session skipped it; the reactor restarts with the persisted cursor on a runtime-mode change, which would leave a resumed OpenCode session on stale (e.g. full-access) permissions. Resume now calls session.update with buildOpenCodePermissionRules(runtimeMode). - Don't resume into the wrong directory. OpenCode routes a prompt to the session's own stored directory, so reusing a session created under a different cwd would silently run there. Resume now starts a fresh session when the re-adopted session's directory differs from the requested cwd. - Distinguish "not found" from transient failures. The SDK client uses throwOnError:true, so session.get rejects on any non-2xx. Only a confirmed 404 / NotFoundError now falls back to creating a fresh session; transport/auth/server errors propagate instead of silently resetting a live thread to an empty session. Tests model throwOnError:true (session.get rejects) and add coverage for the permission re-application, cwd-mismatch fallback, and transient-error propagation paths.
1 parent 19e7282 commit 7be6629

2 files changed

Lines changed: 213 additions & 43 deletions

File tree

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

Lines changed: 104 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,9 @@ const runtimeMock = {
6565
subscribedEvents: [] as unknown[],
6666
sessionGetIds: [] as string[],
6767
missingSessionIds: new Set<string>(),
68+
transientErrorSessionIds: new Set<string>(),
69+
sessionDirectoryById: new Map<string, string>(),
70+
sessionUpdateCalls: [] as Array<{ sessionID: string; permission: unknown }>,
6871
},
6972
reset() {
7073
this.state.startCalls.length = 0;
@@ -80,6 +83,9 @@ const runtimeMock = {
8083
this.state.subscribedEvents = [];
8184
this.state.sessionGetIds.length = 0;
8285
this.state.missingSessionIds.clear();
86+
this.state.transientErrorSessionIds.clear();
87+
this.state.sessionDirectoryById.clear();
88+
this.state.sessionUpdateCalls.length = 0;
8389
},
8490
};
8591

@@ -135,12 +141,24 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
135141
},
136142
get: async ({ sessionID }: { sessionID: string }) => {
137143
runtimeMock.state.sessionGetIds.push(sessionID);
138-
// Model OpenCode's `session.get`: a known id returns the session,
139-
// an unknown/closed id resolves with no `data` (the SDK surfaces the
140-
// 404 as `{ data: undefined, error }` under ThrowOnError=false).
141-
return runtimeMock.state.missingSessionIds.has(sessionID)
142-
? { data: undefined }
143-
: { data: { id: sessionID } };
144+
// The real client is created with `throwOnError: true`, so a non-2xx
145+
// response REJECTS (it does not resolve to a tuple). Model that: a
146+
// transient error throws a non-404, a missing session throws a 404,
147+
// and success resolves with the session payload.
148+
if (runtimeMock.state.transientErrorSessionIds.has(sessionID)) {
149+
throw new Error("opencode server error", { cause: { status: 500 } });
150+
}
151+
if (runtimeMock.state.missingSessionIds.has(sessionID)) {
152+
throw new Error(`Session not found: ${sessionID}`, {
153+
cause: { status: 404, body: { name: "NotFoundError" } },
154+
});
155+
}
156+
const directory = runtimeMock.state.sessionDirectoryById.get(sessionID);
157+
return { data: { id: sessionID, ...(directory ? { directory } : {}) } };
158+
},
159+
update: async ({ sessionID, permission }: { sessionID: string; permission: unknown }) => {
160+
runtimeMock.state.sessionUpdateCalls.push({ sessionID, permission });
161+
return { data: { id: sessionID } };
144162
},
145163
abort: async ({ sessionID }: { sessionID: string }) => {
146164
runtimeMock.state.abortCalls.push(sessionID);
@@ -304,6 +322,10 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
304322
schemaVersion: 1,
305323
sessionId: "ses_persisted",
306324
});
325+
// Resume re-asserts the permission ruleset for the current runtimeMode.
326+
NodeAssert.equal(runtimeMock.state.sessionUpdateCalls.length, 1);
327+
NodeAssert.equal(runtimeMock.state.sessionUpdateCalls[0]?.sessionID, "ses_persisted");
328+
NodeAssert.equal(runtimeMock.state.sessionUpdateCalls[0]?.permission != null, true);
307329

308330
yield* adapter.stopSession(threadId);
309331
}),
@@ -395,6 +417,82 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
395417
}),
396418
);
397419

420+
it.effect("surfaces a non-not-found resume probe error instead of silently starting fresh", () =>
421+
Effect.gen(function* () {
422+
const adapter = yield* OpenCodeAdapter;
423+
const threadId = asThreadId("thread-opencode-transient");
424+
// session.get returns a 500 (not a 404) for this id.
425+
runtimeMock.state.transientErrorSessionIds.add("ses_transient");
426+
427+
const exit = yield* Effect.exit(
428+
adapter.startSession({
429+
provider: ProviderDriverKind.make("opencode"),
430+
threadId,
431+
runtimeMode: "full-access",
432+
resumeCursor: { schemaVersion: 1, sessionId: "ses_transient" },
433+
}),
434+
);
435+
436+
// A transient/transport/auth failure must propagate — NOT be masked as a
437+
// brand-new empty session (the #3604 class of silent context loss).
438+
NodeAssert.equal(Exit.isFailure(exit), true);
439+
NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, ["ses_transient"]);
440+
NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, []);
441+
}),
442+
);
443+
444+
it.effect("re-applies the current runtimeMode permissions when resuming", () =>
445+
Effect.gen(function* () {
446+
const adapter = yield* OpenCodeAdapter;
447+
const threadId = asThreadId("thread-opencode-perms");
448+
449+
yield* adapter.startSession({
450+
provider: ProviderDriverKind.make("opencode"),
451+
// A different runtimeMode than the original create — resume must not
452+
// leave the upstream session on stale permissions.
453+
runtimeMode: "approval-required",
454+
threadId,
455+
resumeCursor: { schemaVersion: 1, sessionId: "ses_perms" },
456+
});
457+
458+
NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, ["ses_perms"]);
459+
NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, []);
460+
NodeAssert.equal(runtimeMock.state.sessionUpdateCalls.length, 1);
461+
NodeAssert.equal(runtimeMock.state.sessionUpdateCalls[0]?.sessionID, "ses_perms");
462+
NodeAssert.equal(runtimeMock.state.sessionUpdateCalls[0]?.permission != null, true);
463+
464+
yield* adapter.stopSession(threadId);
465+
}),
466+
);
467+
468+
it.effect("starts fresh when the resumed session is bound to a different directory", () =>
469+
Effect.gen(function* () {
470+
const adapter = yield* OpenCodeAdapter;
471+
const threadId = asThreadId("thread-opencode-cwd");
472+
// The persisted session still exists but lives in another working dir.
473+
runtimeMock.state.sessionDirectoryById.set("ses_otherdir", "/some/other/worktree");
474+
475+
const session = yield* adapter.startSession({
476+
provider: ProviderDriverKind.make("opencode"),
477+
threadId,
478+
runtimeMode: "full-access",
479+
resumeCursor: { schemaVersion: 1, sessionId: "ses_otherdir" },
480+
});
481+
482+
// OpenCode routes prompts to the session's stored directory, so a cwd
483+
// change must NOT silently reuse the old-directory session — create fresh.
484+
NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, ["ses_otherdir"]);
485+
NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, ["http://127.0.0.1:9999"]);
486+
NodeAssert.deepEqual(runtimeMock.state.sessionUpdateCalls, []);
487+
NodeAssert.deepEqual(session.resumeCursor, {
488+
schemaVersion: 1,
489+
sessionId: "http://127.0.0.1:9999/session",
490+
});
491+
492+
yield* adapter.stopSession(threadId);
493+
}),
494+
);
495+
398496
it.effect("stops a configured-server session without trying to own server lifecycle", () =>
399497
Effect.gen(function* () {
400498
const adapter = yield* OpenCodeAdapter;

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

Lines changed: 109 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,40 @@ function parseOpenCodeResume(raw: unknown): { readonly sessionId: string } | und
8282
return { sessionId: record.sessionId.trim() };
8383
}
8484

85+
/**
86+
* Walk an error's `cause` chain for a definitive "session not found" signal —
87+
* an HTTP 404 or an OpenCode `NotFoundError`. The SDK client is configured
88+
* `throwOnError: true` (see `createOpenCodeSdkClient`), so `session.get` on a
89+
* missing/closed session rejects rather than resolving; `runOpenCodeSdk` then
90+
* surfaces it as a failed Effect whose cause wraps the original error (message
91+
* plus `{ body, status }`). Only a confirmed miss justifies silently starting a
92+
* fresh session — any other failure (transport, auth, server error) must
93+
* propagate, so a momentary blip can't quietly reset a live thread to an empty
94+
* session (the #3604 class of silent context loss).
95+
*/
96+
function isOpenCodeNotFound(cause: unknown): boolean {
97+
let current: unknown = cause;
98+
for (let depth = 0; depth < 6 && current !== null && typeof current === "object"; depth += 1) {
99+
const record = current as Record<string, unknown>;
100+
if (record.status === 404 || record.statusCode === 404) {
101+
return true;
102+
}
103+
const name = record.name;
104+
if (typeof name === "string" && name.toLowerCase().includes("notfound")) {
105+
return true;
106+
}
107+
const message = record.message;
108+
if (
109+
typeof message === "string" &&
110+
/\bnot found\b|no such session|unknown session|does not exist/i.test(message)
111+
) {
112+
return true;
113+
}
114+
current = record.cause;
115+
}
116+
return false;
117+
}
118+
85119
interface OpenCodeTurnSnapshot {
86120
readonly id: TurnId;
87121
readonly items: Array<unknown>;
@@ -1102,48 +1136,86 @@ export function makeOpenCodeAdapter(
11021136
}
11031137
// Resume path: when a durable cursor names a prior OpenCode
11041138
// session, re-adopt that `ses_…` instead of minting a new one.
1105-
// OpenCode scopes history by session id, so prompting the same
1106-
// id automatically restores the full prior conversation. We
1107-
// validate with `session.get` first; a missing/closed session
1108-
// (or any get failure) falls back to creating a fresh one so a
1109-
// stale cursor can never wedge the thread.
1110-
const resumedSession = resumeSessionId
1111-
? yield* runOpenCodeSdk("session.get", () =>
1112-
client.session.get({ sessionID: resumeSessionId }),
1113-
).pipe(
1114-
Effect.map((response) => response.data),
1115-
Effect.orElseSucceed(() => undefined),
1116-
)
1117-
: undefined;
1118-
const created = resumedSession === undefined;
1119-
const openCodeSession = yield* resumedSession
1120-
? Effect.succeed(resumedSession)
1121-
: Effect.gen(function* () {
1122-
if (resumeSessionId) {
1123-
yield* Effect.logWarning(
1124-
`OpenCode session '${resumeSessionId}' could not be resumed; starting a fresh session.`,
1125-
);
1126-
}
1127-
const createdSession = yield* runOpenCodeSdk("session.create", () =>
1128-
client.session.create({
1129-
title: `T3 Code ${input.threadId}`,
1130-
permission: buildOpenCodePermissionRules(input.runtimeMode),
1131-
}),
1132-
);
1133-
if (!createdSession.data) {
1134-
return yield* new OpenCodeRuntimeError({
1135-
operation: "session.create",
1136-
detail: "OpenCode session.create returned no session payload.",
1137-
});
1138-
}
1139-
return createdSession.data;
1139+
// OpenCode scopes history by session id, so prompting the same id
1140+
// restores the full prior conversation.
1141+
//
1142+
// The probe distinguishes three outcomes. A request that throws
1143+
// (transport/network) fails the Effect in `runOpenCodeSdk` and
1144+
// propagates — we never silently reset a live thread on a blip.
1145+
// A confirmed "not found" falls back to a fresh session. Any
1146+
// other error response (auth, bad request, server error) is
1147+
// surfaced rather than masked as a brand-new empty session.
1148+
const resolved = yield* Effect.gen(function* () {
1149+
// Probe the persisted session. With `throwOnError: true`,
1150+
// `session.get` rejects on any non-2xx; we recover ONLY a
1151+
// confirmed "not found" (the session is genuinely gone -> start
1152+
// fresh). A transport/auth/server error propagates instead of
1153+
// masquerading as a brand-new empty session (issue #3604).
1154+
const adopted = resumeSessionId
1155+
? yield* runOpenCodeSdk("session.get", () =>
1156+
client.session.get({ sessionID: resumeSessionId }),
1157+
).pipe(
1158+
Effect.map((response) => response.data),
1159+
Effect.catchIf(
1160+
(cause) => isOpenCodeNotFound(cause),
1161+
() => Effect.succeed(undefined),
1162+
),
1163+
)
1164+
: undefined;
1165+
1166+
// Reuse the upstream session only when it still matches the
1167+
// requested working directory. OpenCode routes a prompt to the
1168+
// session's OWN stored directory, so resuming a session created
1169+
// under a different cwd would silently run there — in that case
1170+
// start fresh in the requested directory instead.
1171+
const reusable =
1172+
adopted && (!adopted.directory || adopted.directory === directory)
1173+
? adopted
1174+
: undefined;
1175+
1176+
if (reusable) {
1177+
// `session.create` is skipped on resume, so re-assert the
1178+
// permission ruleset for the CURRENT runtimeMode — otherwise a
1179+
// runtime-mode change (the reactor restarts with the persisted
1180+
// cursor) would leave the re-adopted session on the
1181+
// permissions it was originally created with.
1182+
yield* runOpenCodeSdk("session.update", () =>
1183+
client.session.update({
1184+
sessionID: reusable.id,
1185+
permission: buildOpenCodePermissionRules(input.runtimeMode),
1186+
}),
1187+
);
1188+
return { openCodeSession: reusable, created: false };
1189+
}
1190+
1191+
if (resumeSessionId) {
1192+
yield* Effect.logWarning(
1193+
adopted !== undefined
1194+
? `OpenCode session '${resumeSessionId}' is bound to a different working directory; starting a fresh session.`
1195+
: `OpenCode session '${resumeSessionId}' no longer exists; starting a fresh session.`,
1196+
);
1197+
}
1198+
const createdSession = yield* runOpenCodeSdk("session.create", () =>
1199+
client.session.create({
1200+
title: `T3 Code ${input.threadId}`,
1201+
permission: buildOpenCodePermissionRules(input.runtimeMode),
1202+
}),
1203+
);
1204+
if (!createdSession.data) {
1205+
return yield* new OpenCodeRuntimeError({
1206+
operation: "session.create",
1207+
detail: "OpenCode session.create returned no session payload.",
11401208
});
1209+
}
1210+
return { openCodeSession: createdSession.data, created: true };
1211+
});
1212+
11411213
return {
11421214
sessionScope,
11431215
server,
11441216
client,
1145-
openCodeSession,
1146-
created,
1217+
openCodeSession: resolved.openCodeSession,
1218+
created: resolved.created,
11471219
};
11481220
}).pipe(Effect.provideService(Scope.Scope, sessionScope)),
11491221
);

0 commit comments

Comments
 (0)