Skip to content

Commit 0024505

Browse files
vdmkotaicodex
authored andcommitted
fix(opencode): resume the OpenCode session on follow-ups instead of starting an empty one
The OpenCode adapter always called session.create and never read or emitted a resume cursor, so the upstream ses_… id lived only in memory. When that in-memory binding was lost — the ProviderSessionReaper stopping an idle session (~30 min) or an app/server restart — the next follow-up in the same visible thread was sent to a brand-new, empty OpenCode session. t3code kept rendering its own projection DB, so the user still saw the full history while the model had no context (issue pingdotgg#3604). Mirror the Grok/Cursor/Codex resume pattern, entirely within the adapter: - Emit resumeCursor { schemaVersion, sessionId } on the started ProviderSession (and echo it from sendTurn) so ProviderService persists it into provider_session_runtime.resume_cursor_json. - On startSession, when a cursor is present, validate the id with session.get and re-adopt that session instead of creating a new one. OpenCode scopes history by session id, so prompting the same id restores the full prior conversation. A missing/closed session (or any get failure) falls back to a fresh session so a stale cursor can't wedge the thread. - Only abort the upstream session in the start race-cleanup when we actually created it; never abort a session we merely resumed. The persistence/recovery plumbing is provider-agnostic and already feeds a persisted cursor back into startSession on a reaped/restarted follow-up (ProviderService falls back to the stored binding cursor when the reactor passes none), so no changes outside the adapter are needed. Adds regression tests: fresh-session cursor emission, resume re-adopting the persisted id (no create), follow-up turns targeting the resumed id, stale-cursor fallback to create, and malformed-cursor rejection. Fixes pingdotgg#3604 Co-authored-by: codex <[email protected]>
1 parent 8e3467f commit 0024505

2 files changed

Lines changed: 245 additions & 19 deletions

File tree

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

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,8 @@ const runtimeMock = {
6464
closeError: null as Error | null,
6565
messages: [] as MessageEntry[],
6666
subscribedEvents: [] as unknown[],
67+
sessionGetIds: [] as string[],
68+
missingSessionIds: new Set<string>(),
6769
},
6870
reset() {
6971
this.state.startCalls.length = 0;
@@ -78,6 +80,8 @@ const runtimeMock = {
7880
this.state.closeError = null;
7981
this.state.messages = [];
8082
this.state.subscribedEvents = [];
83+
this.state.sessionGetIds.length = 0;
84+
this.state.missingSessionIds.clear();
8185
},
8286
};
8387

@@ -132,6 +136,15 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
132136
);
133137
return { data: { id: `${baseUrl}/session` } };
134138
},
139+
get: async ({ sessionID }: { sessionID: string }) => {
140+
runtimeMock.state.sessionGetIds.push(sessionID);
141+
// Model OpenCode's `session.get`: a known id returns the session,
142+
// an unknown/closed id resolves with no `data` (the SDK surfaces the
143+
// 404 as `{ data: undefined, error }` under ThrowOnError=false).
144+
return runtimeMock.state.missingSessionIds.has(sessionID)
145+
? { data: undefined }
146+
: { data: { id: sessionID } };
147+
},
135148
abort: async ({ sessionID }: { sessionID: string }) => {
136149
runtimeMock.state.abortCalls.push(sessionID);
137150
},
@@ -251,6 +264,140 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
251264
}),
252265
);
253266

267+
it.effect("returns a durable resume cursor for a freshly created session", () =>
268+
Effect.gen(function* () {
269+
const adapter = yield* OpenCodeAdapter;
270+
const threadId = asThreadId("thread-opencode-cursor");
271+
272+
const session = yield* adapter.startSession({
273+
provider: ProviderDriverKind.make("opencode"),
274+
threadId,
275+
runtimeMode: "full-access",
276+
});
277+
278+
// Without a persisted cursor, a session is created and its id is
279+
// surfaced as a resume cursor so the upper layer can persist it.
280+
NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, []);
281+
NodeAssert.deepEqual(session.resumeCursor, {
282+
schemaVersion: 1,
283+
sessionId: "http://127.0.0.1:9999/session",
284+
});
285+
286+
yield* adapter.stopSession(threadId);
287+
}),
288+
);
289+
290+
it.effect("resumes the persisted OpenCode session instead of creating a new one", () =>
291+
Effect.gen(function* () {
292+
const adapter = yield* OpenCodeAdapter;
293+
const threadId = asThreadId("thread-opencode-resume");
294+
295+
const session = yield* adapter.startSession({
296+
provider: ProviderDriverKind.make("opencode"),
297+
threadId,
298+
runtimeMode: "full-access",
299+
resumeCursor: { schemaVersion: 1, sessionId: "ses_persisted" },
300+
});
301+
302+
// The adapter validates the persisted id with session.get and re-adopts
303+
// it — no new session is minted (issue #3604).
304+
NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, ["ses_persisted"]);
305+
NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, []);
306+
NodeAssert.deepEqual(session.resumeCursor, {
307+
schemaVersion: 1,
308+
sessionId: "ses_persisted",
309+
});
310+
311+
yield* adapter.stopSession(threadId);
312+
}),
313+
);
314+
315+
it.effect("sends follow-up turns to the resumed session id", () =>
316+
Effect.gen(function* () {
317+
const adapter = yield* OpenCodeAdapter;
318+
const threadId = asThreadId("thread-opencode-resume-turn");
319+
320+
yield* adapter.startSession({
321+
provider: ProviderDriverKind.make("opencode"),
322+
threadId,
323+
runtimeMode: "full-access",
324+
resumeCursor: { schemaVersion: 1, sessionId: "ses_persisted" },
325+
});
326+
327+
const result = yield* adapter.sendTurn({
328+
threadId,
329+
input: "continue where we left off",
330+
modelSelection: createModelSelection(
331+
ProviderInstanceId.make("opencode"),
332+
"anthropic/sonnet",
333+
),
334+
});
335+
336+
// The prompt targets the resumed id, and the turn re-surfaces the cursor.
337+
NodeAssert.deepEqual(
338+
(runtimeMock.state.promptCalls[0] as { sessionID: string }).sessionID,
339+
"ses_persisted",
340+
);
341+
NodeAssert.deepEqual(result.resumeCursor, {
342+
schemaVersion: 1,
343+
sessionId: "ses_persisted",
344+
});
345+
346+
yield* adapter.stopSession(threadId);
347+
}),
348+
);
349+
350+
it.effect("falls back to a fresh session when the persisted session is gone", () =>
351+
Effect.gen(function* () {
352+
const adapter = yield* OpenCodeAdapter;
353+
const threadId = asThreadId("thread-opencode-stale");
354+
runtimeMock.state.missingSessionIds.add("ses_stale");
355+
356+
const session = yield* adapter.startSession({
357+
provider: ProviderDriverKind.make("opencode"),
358+
threadId,
359+
runtimeMode: "full-access",
360+
resumeCursor: { schemaVersion: 1, sessionId: "ses_stale" },
361+
});
362+
363+
// get probed the stale id, found nothing, then created a new session and
364+
// emitted a fresh cursor rather than wedging the thread.
365+
NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, ["ses_stale"]);
366+
NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, ["http://127.0.0.1:9999"]);
367+
NodeAssert.deepEqual(session.resumeCursor, {
368+
schemaVersion: 1,
369+
sessionId: "http://127.0.0.1:9999/session",
370+
});
371+
372+
yield* adapter.stopSession(threadId);
373+
}),
374+
);
375+
376+
it.effect("ignores a malformed or wrong-version resume cursor", () =>
377+
Effect.gen(function* () {
378+
const adapter = yield* OpenCodeAdapter;
379+
const threadId = asThreadId("thread-opencode-badcursor");
380+
381+
const session = yield* adapter.startSession({
382+
provider: ProviderDriverKind.make("opencode"),
383+
threadId,
384+
runtimeMode: "full-access",
385+
resumeCursor: { schemaVersion: 99, sessionId: "ses_persisted" },
386+
});
387+
388+
// A foreign/stale-shaped cursor is treated as "no resume": never probed,
389+
// a fresh session is created.
390+
NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, []);
391+
NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, ["http://127.0.0.1:9999"]);
392+
NodeAssert.deepEqual(session.resumeCursor, {
393+
schemaVersion: 1,
394+
sessionId: "http://127.0.0.1:9999/session",
395+
});
396+
397+
yield* adapter.stopSession(threadId);
398+
}),
399+
);
400+
254401
it.effect("fails sendTurn for missing sessions through the typed error channel", () =>
255402
Effect.gen(function* () {
256403
const adapter = yield* OpenCodeAdapter;

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

Lines changed: 98 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,35 @@ import * as Option from "effect/Option";
5353

5454
const PROVIDER = ProviderDriverKind.make("opencode");
5555

56+
/**
57+
* Version tag stamped into the OpenCode resume cursor. Bump if the cursor
58+
* shape changes so stale-shaped cursors written by older builds are ignored
59+
* rather than misread (mirrors GROK_RESUME_VERSION / CURSOR_RESUME_VERSION).
60+
*/
61+
const OPENCODE_RESUME_VERSION = 1 as const;
62+
63+
/**
64+
* Decode a persisted OpenCode resume cursor back into the upstream `ses_…`
65+
* id. Returns `undefined` for anything that isn't a current-version cursor
66+
* carrying a non-empty session id, so a malformed or foreign cursor simply
67+
* means "no resume" instead of throwing. OpenCode has no dedicated resume
68+
* RPC — re-adopting the same session id *is* the resume mechanism, because
69+
* the server scopes a conversation's history by session id.
70+
*/
71+
function parseOpenCodeResume(raw: unknown): { readonly sessionId: string } | undefined {
72+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
73+
return undefined;
74+
}
75+
const record = raw as Record<string, unknown>;
76+
if (record.schemaVersion !== OPENCODE_RESUME_VERSION) {
77+
return undefined;
78+
}
79+
if (typeof record.sessionId !== "string" || record.sessionId.trim().length === 0) {
80+
return undefined;
81+
}
82+
return { sessionId: record.sessionId.trim() };
83+
}
84+
5685
interface OpenCodeTurnSnapshot {
5786
readonly id: TurnId;
5887
readonly items: Array<unknown>;
@@ -1076,6 +1105,7 @@ export function makeOpenCodeAdapter(
10761105
const serverUrl = openCodeSettings.serverUrl;
10771106
const serverPassword = openCodeSettings.serverPassword;
10781107
const directory = input.cwd ?? serverConfig.cwd;
1108+
const resumeSessionId = parseOpenCodeResume(input.resumeCursor)?.sessionId;
10791109
const existing = sessions.get(input.threadId);
10801110
if (existing) {
10811111
yield* stopOpenCodeContext(existing);
@@ -1115,22 +1145,50 @@ export function makeOpenCodeAdapter(
11151145
}),
11161146
);
11171147
}
1118-
const openCodeSession = yield* runOpenCodeSdk("session.create", () =>
1119-
client.session.create({
1120-
permission: buildOpenCodePermissionRules(input.runtimeMode),
1121-
}),
1122-
);
1123-
if (!openCodeSession.data) {
1124-
return yield* new OpenCodeRuntimeError({
1125-
operation: "session.create",
1126-
detail: "OpenCode session.create returned no session payload.",
1127-
});
1128-
}
1148+
// Resume path: when a durable cursor names a prior OpenCode
1149+
// session, re-adopt that `ses_…` instead of minting a new one.
1150+
// OpenCode scopes history by session id, so prompting the same
1151+
// id automatically restores the full prior conversation. We
1152+
// validate with `session.get` first; a missing/closed session
1153+
// (or any get failure) falls back to creating a fresh one so a
1154+
// stale cursor can never wedge the thread.
1155+
const resumedSession = resumeSessionId
1156+
? yield* runOpenCodeSdk("session.get", () =>
1157+
client.session.get({ sessionID: resumeSessionId }),
1158+
).pipe(
1159+
Effect.map((response) => response.data),
1160+
Effect.orElseSucceed(() => undefined),
1161+
)
1162+
: undefined;
1163+
const created = resumedSession === undefined;
1164+
const openCodeSession = yield* resumedSession
1165+
? Effect.succeed(resumedSession)
1166+
: Effect.gen(function* () {
1167+
if (resumeSessionId) {
1168+
yield* Effect.logWarning(
1169+
`OpenCode session '${resumeSessionId}' could not be resumed; starting a fresh session.`,
1170+
);
1171+
}
1172+
const createdSession = yield* runOpenCodeSdk("session.create", () =>
1173+
client.session.create({
1174+
title: `T3 Code ${input.threadId}`,
1175+
permission: buildOpenCodePermissionRules(input.runtimeMode),
1176+
}),
1177+
);
1178+
if (!createdSession.data) {
1179+
return yield* new OpenCodeRuntimeError({
1180+
operation: "session.create",
1181+
detail: "OpenCode session.create returned no session payload.",
1182+
});
1183+
}
1184+
return createdSession.data;
1185+
});
11291186
return {
11301187
sessionScope,
11311188
server,
11321189
client,
1133-
openCodeSession: openCodeSession.data,
1190+
openCodeSession,
1191+
created,
11341192
};
11351193
}).pipe(Effect.provideService(Scope.Scope, sessionScope)),
11361194
);
@@ -1145,13 +1203,19 @@ export function makeOpenCodeAdapter(
11451203
// and already inserted a session while we were awaiting async work.
11461204
const raceWinner = sessions.get(input.threadId);
11471205
if (raceWinner) {
1148-
// Another call won the race – clean up the session we just created
1149-
// (including the remote SDK session) and return the existing one.
1150-
yield* runOpenCodeSdk("session.abort", () =>
1151-
started.client.session.abort({
1152-
sessionID: started.openCodeSession.id,
1153-
}),
1154-
).pipe(Effect.ignore);
1206+
// Another call won the race – clean up the session we just started
1207+
// and return the existing one. Only abort the remote SDK session if
1208+
// we *created* it here; a session we merely resumed is shared upstream
1209+
// state the race winner is now using, so aborting it would interrupt
1210+
// them (and `session.abort` is otherwise the wrong tool — it cancels
1211+
// an in-flight turn rather than disowning a session).
1212+
if (started.created) {
1213+
yield* runOpenCodeSdk("session.abort", () =>
1214+
started.client.session.abort({
1215+
sessionID: started.openCodeSession.id,
1216+
}),
1217+
).pipe(Effect.ignore);
1218+
}
11551219
yield* Scope.close(started.sessionScope, Exit.void).pipe(Effect.ignore);
11561220
return raceWinner.session;
11571221
}
@@ -1165,6 +1229,16 @@ export function makeOpenCodeAdapter(
11651229
cwd: directory,
11661230
...(input.modelSelection ? { model: input.modelSelection.model } : {}),
11671231
threadId: input.threadId,
1232+
// Durable binding to the upstream OpenCode session. ProviderService
1233+
// persists this into provider_session_runtime.resume_cursor_json and
1234+
// feeds it back into `startSession` on the next turn after the
1235+
// in-memory session is lost (reaper / app or server restart), which
1236+
// is what lets a follow-up continue the same conversation instead of
1237+
// silently landing in a new, empty session (issue #3604).
1238+
resumeCursor: {
1239+
schemaVersion: OPENCODE_RESUME_VERSION,
1240+
sessionId: started.openCodeSession.id,
1241+
},
11681242
createdAt,
11691243
updatedAt: createdAt,
11701244
};
@@ -1330,6 +1404,11 @@ export function makeOpenCodeAdapter(
13301404
return {
13311405
threadId: input.threadId,
13321406
turnId,
1407+
// Re-surface the durable cursor on every turn so the persisted binding
1408+
// is refreshed alongside last-seen/runtime state (mirrors Grok/Codex).
1409+
...(context.session.resumeCursor !== undefined
1410+
? { resumeCursor: context.session.resumeCursor }
1411+
: {}),
13331412
};
13341413
});
13351414

0 commit comments

Comments
 (0)