Skip to content

Commit f5a405c

Browse files
committed
fix(opencode): name OpenCode 2 sessions after their thread
OpenCode titles an untitled root session with its own model on the first prompt, so every T3 thread cost an extra model call and showed a different name in OpenCode than in T3. Create the session with the thread's title and rename it before a turn when the thread was renamed since.
1 parent 43f8a8d commit f5a405c

7 files changed

Lines changed: 121 additions & 14 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts‎

Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,11 @@ const mcpRules = [
8383
{ action: "t3-code-thread_opencode2-adapter_*", resource: "*", effect: "allow" },
8484
];
8585
const t3Rules = [{ action: "*", resource: "*", effect: "allow" }, ...mcpRules];
86+
/** The thread's title, which the recorded session already carries. */
87+
const TITLE = "Prime check";
8688
const sessionInfo = (overrides: Record<string, unknown> = {}) => ({
8789
id: SESSION,
90+
title: TITLE,
8891
permissions: t3Rules,
8992
projectID: "global",
9093
model: { id: "big-pickle", providerID: "opencode", variant: "default" },
@@ -230,7 +233,7 @@ const turnInput = (
230233
modelSelection: ModelSelection = bigPickle,
231234
runtimeMode: "full-access" | "approval-required" = "full-access",
232235
) => ({
233-
appThread: {} as OrchestrationV2AppThread,
236+
appThread: { title: TITLE } as OrchestrationV2AppThread,
234237
threadId,
235238
runId: RunId.make("run:opencode2-adapter"),
236239
runOrdinal: 1,
@@ -431,6 +434,66 @@ describe("OpenCode2 adapter", () => {
431434
}).pipe(Effect.scoped),
432435
);
433436

437+
it.effect("creates the session with the thread's title, so OpenCode generates none", () =>
438+
Effect.gen(function* () {
439+
const runtime = yield* openCode2ReplayRuntimeWithInstructions([
440+
...opening,
441+
out("session.create", {
442+
location: { directory: WORK },
443+
model: { providerID: "opencode", id: "big-pickle" },
444+
permissions: t3Rules,
445+
title: "Check whether 391 is prime",
446+
}),
447+
replyData("session.create", sessionInfo({ title: "Check whether 391 is prime" })),
448+
out("session.prompt", { sessionID: SESSION, text: "<any>" }),
449+
promptAccepted,
450+
event("session.execution.succeeded", { sessionID: SESSION }),
451+
]);
452+
const thread = yield* runtime.ensureThread({
453+
threadId,
454+
title: " Check whether 391 is prime ",
455+
modelSelection: bigPickle,
456+
runtimePolicy: policy(),
457+
});
458+
const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
459+
yield* runtime.startTurn({
460+
...turnInput(thread),
461+
appThread: { title: "Check whether 391 is prime" } as OrchestrationV2AppThread,
462+
});
463+
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
464+
}).pipe(Effect.scoped),
465+
);
466+
467+
it.effect("renames the session before the first turn after the thread was renamed", () =>
468+
Effect.gen(function* () {
469+
const { runtime, thread } = yield* resumed([
470+
out("session.update", { sessionID: SESSION, title: "Prime factors of 391" }),
471+
reply("session.update", null),
472+
out("session.prompt", { sessionID: SESSION, text: "<any>" }),
473+
promptAccepted,
474+
event("session.execution.succeeded", { sessionID: SESSION }),
475+
// Renamed once: the next turn under the same title sends no update.
476+
out("session.prompt", { sessionID: SESSION, text: "<any>" }),
477+
promptAccepted,
478+
event("session.execution.succeeded", { sessionID: SESSION }),
479+
]);
480+
const renamed = {
481+
...turnInput(thread),
482+
appThread: { title: "Prime factors of 391" } as OrchestrationV2AppThread,
483+
};
484+
const first = yield* terminalOf(runtime).pipe(Effect.forkScoped);
485+
yield* runtime.startTurn(renamed);
486+
assert.equal((yield* Fiber.join(first))?.status, "completed");
487+
const second = yield* terminalOf(runtime).pipe(Effect.forkScoped);
488+
yield* runtime.startTurn({
489+
...renamed,
490+
runId: RunId.make("run:opencode2-adapter:2"),
491+
attemptId: RunAttemptId.make("attempt:opencode2-adapter:2"),
492+
});
493+
assert.equal((yield* Fiber.join(second))?.status, "completed");
494+
}).pipe(Effect.scoped),
495+
);
496+
434497
it.effect("ends a turn on the provider thread it started on", () =>
435498
Effect.gen(function* () {
436499
const { runtime, thread } = yield* resumed([
@@ -629,6 +692,7 @@ describe("OpenCode2 adapter", () => {
629692
...turnInput(thread),
630693
appThread: {
631694
id: threadId,
695+
title: TITLE,
632696
lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
633697
} as OrchestrationV2AppThread,
634698
});

‎apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts‎

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -151,9 +151,10 @@ const planRules = (name: string) => [
151151
...mcpRules(name),
152152
];
153153

154-
const sessionInfo = (directory: string, permissions: ReadonlyArray<unknown>) => ({
154+
const sessionInfo = (directory: string, permissions: ReadonlyArray<unknown>, title: string) => ({
155155
data: {
156156
id: SESSION,
157+
title,
157158
projectID: "global",
158159
model: { id: "big-pickle", providerID: "opencode", variant: "default" },
159160
cost: 0,
@@ -235,8 +236,9 @@ const createdSession = (
235236
],
236237
}),
237238
...(narrows ? [out("agent.list", "<any>"), reply("agent.list", agentList(directory))] : []),
238-
out("session.create", { location: { directory }, model: "<any>", permissions }),
239-
reply("session.create", sessionInfo(directory, permissions)),
239+
// The thread's title, which is its name here.
240+
out("session.create", { location: { directory }, model: "<any>", permissions, title: name }),
241+
reply("session.create", sessionInfo(directory, permissions, name)),
240242
];
241243

242244
/** A recording with its scrubbed `<work>` directory replaced by `directory`. */
@@ -348,7 +350,7 @@ describe("OpenCode 2 through the orchestrator", () => {
348350
...answeredPrompt("FIRST"),
349351
// The next turn resumes the session at its new selection.
350352
out("session.get", { sessionID: SESSION }),
351-
reply("session.get", sessionInfo(cwd, t3Rules(name))),
353+
reply("session.get", sessionInfo(cwd, t3Rules(name), name)),
352354
out("session.switchModel", {
353355
sessionID: SESSION,
354356
model: { providerID: "opencode", id: "mimo-v2.6-flash-free" },
@@ -401,7 +403,7 @@ describe("OpenCode 2 through the orchestrator", () => {
401403
...answeredPrompt("FIRST"),
402404
...directoryModels(after),
403405
out("session.get", { sessionID: SESSION }),
404-
reply("session.get", sessionInfo(before, t3Rules(name))),
406+
reply("session.get", sessionInfo(before, t3Rules(name), name)),
405407
// The worktree change detached the thread, so its session is loaded afresh.
406408
...noOpenRequests,
407409
out("session.move", { sessionID: SESSION, directory: after }),
@@ -450,10 +452,14 @@ describe("OpenCode 2 through the orchestrator", () => {
450452
out("session.get", { sessionID: SESSION }),
451453
reply(
452454
"session.get",
453-
sessionInfo(before, [
454-
{ action: "*", resource: "*", effect: "allow" },
455-
{ action: "subagent", resource: "*", effect: "deny" },
456-
]),
455+
sessionInfo(
456+
before,
457+
[
458+
{ action: "*", resource: "*", effect: "allow" },
459+
{ action: "subagent", resource: "*", effect: "deny" },
460+
],
461+
name,
462+
),
457463
),
458464
...noOpenRequests,
459465
out("session.update", { sessionID: SESSION, permissions: t3Rules(name) }),
@@ -531,15 +537,15 @@ describe("OpenCode 2 through the orchestrator", () => {
531537
...answeredPrompt("FIRST"),
532538
// A mode change detaches nothing: the same session is resumed with the new rules.
533539
out("session.get", { sessionID: SESSION }),
534-
reply("session.get", sessionInfo(cwd, t3Rules(name))),
540+
reply("session.get", sessionInfo(cwd, t3Rules(name), name)),
535541
out("agent.list", "<any>"),
536542
reply("agent.list", agentList(cwd)),
537543
out("session.update", { sessionID: SESSION, permissions: autoEditRules(name) }),
538544
reply("session.update", null),
539545
...answeredPrompt("SECOND"),
540546
// Back to Full access: the narrowing rules go.
541547
out("session.get", { sessionID: SESSION }),
542-
reply("session.get", sessionInfo(cwd, autoEditRules(name))),
548+
reply("session.get", sessionInfo(cwd, autoEditRules(name), name)),
543549
out("session.update", { sessionID: SESSION, permissions: t3Rules(name) }),
544550
reply("session.update", null),
545551
...answeredPrompt("THIRD"),
@@ -577,7 +583,7 @@ describe("OpenCode 2 through the orchestrator", () => {
577583
...instructionsWritten,
578584
...answeredPrompt("PLANNED"),
579585
out("session.get", { sessionID: SESSION }),
580-
reply("session.get", sessionInfo(cwd, planRules(name))),
586+
reply("session.get", sessionInfo(cwd, planRules(name), name)),
581587
out("session.update", { sessionID: SESSION, permissions: t3Rules(name) }),
582588
reply("session.update", null),
583589
out("session.switchAgent", { sessionID: SESSION, agent: "build" }),

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -656,6 +656,7 @@ export const layer: Layer.Layer<
656656
return yield* loadFromProvider(
657657
session.ensureThread({
658658
threadId: projection.thread.id,
659+
title: projection.thread.title,
659660
modelSelection: run.modelSelection,
660661
runtimePolicy: resolvedRuntimePolicy,
661662
providerSessionId,
@@ -701,6 +702,7 @@ export const layer: Layer.Layer<
701702
const replacement = yield* loadFromProvider(
702703
session.ensureThread({
703704
threadId: projection.thread.id,
705+
title: projection.thread.title,
704706
modelSelection: run.modelSelection,
705707
runtimePolicy: resolvedRuntimePolicy,
706708
providerSessionId,

‎apps/server/src/orchestration-v2/testkit/fixtures/opencode2_fork/opencode_transcript.ndjson‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@
5050
{"type": "expect_outbound", "label": "session.update", "frame": {"type": "session.update", "input": {"sessionID": "ses_f1484db83ffeLGtrRCFimo1H0e", "permissions": [{"action": "*", "resource": "*", "effect": "allow"}, {"action": "t3-code-*", "resource": "*", "effect": "deny"}, {"action": "t3-code-thread_opencode2-fork_target_*", "resource": "*", "effect": "allow"}]}}}
5151
{"type": "emit_inbound", "label": "session.update.response", "frame": {"type": "sdk.response", "operation": "session.update", "data": null}}
5252
{"type": "emit_inbound", "label": "session.forked", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7b247d001fXzFroPg5P0bps", "created": 1790657111165, "type": "session.forked", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f1484db83ffeLGtrRCFimo1H0e", "parentID": "ses_f1484ea8affe5aTo8CcgbGIszj", "boundary": {"type": "before", "messageID": "msg_0eb7b1f9f001g95Bduh3bi8syS"}, "instructions": {"core/environment": "db4a793a05fec32fdfa985a3432125a86d6cb42debc8b9ee8f6a99fbfcf2f93b", "core/date": "bf08b8486572ab3eef677a3c9ee12468e411ae41a8f4d2fb6cf02a6ca73f1986", "core/codemode": "616a7ad8b8e40e8a71eab238dfbbe9eaf0f4a9e6fdad853226d075bfe602e1e6", "core/skill-guidance": "0d001919496102654717308c72635523bf7c3cd99c81e058cc79f2947104f9a5"}, "instructionEntries": []}, "durable": {"aggregateID": "ses_f1484db83ffeLGtrRCFimo1H0e", "seq": 0, "version": 2}}}}
53+
{"type": "expect_outbound", "label": "session.update.title", "frame": {"type": "session.update", "input": {"sessionID": "ses_f1484db83ffeLGtrRCFimo1H0e", "title": "<any>"}}}
54+
{"type": "emit_inbound", "label": "session.update.title.response", "frame": {"type": "sdk.response", "operation": "session.update", "data": null}}
5355
{"type": "expect_outbound", "label": "session.instructions.entry.put.2", "frame": {"type": "session.instructions.entry.put", "input": {"sessionID": "ses_f1484db83ffeLGtrRCFimo1H0e", "key": "t3-code", "value": "<any>"}}}
5456
{"type": "emit_inbound", "label": "session.instructions.entry.put.response.2", "frame": {"type": "sdk.response", "operation": "session.instructions.entry.put", "data": null}}
5557
{"type": "expect_outbound", "label": "session.prompt.3", "frame": {"type": "session.prompt", "input": {"sessionID": "ses_f1484db83ffeLGtrRCFimo1H0e", "id": "msg_0eb7b2493001nZTYCniIjU5Y65", "text": "<any>"}}}

‎apps/server/src/orchestration-v2/testkit/fixtures/opencode2_switch/opencode_transcript.ndjson‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,8 @@
5959
{"type": "emit_inbound", "label": "session.switchAgent.response.2", "frame": {"type": "sdk.response", "operation": "session.switchAgent", "data": null}}
6060
{"type": "emit_inbound", "label": "session.agent.selected.2", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7eef80001lOHUbFIwlg7iap", "created": 1790657359744, "type": "session.agent.selected", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f14812197ffeCbw641wM2r3ZmP", "agent": "build", "previous": "plan"}, "durable": {"aggregateID": "ses_f14812197ffeCbw641wM2r3ZmP", "seq": 16, "version": 1}}}}
6161
{"type": "emit_inbound", "label": "session.inbox.enqueued.3", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7eef830020JKd2UmFNPZ8vu", "created": 1790657359747, "type": "session.inbox.enqueued", "location": {"directory": "<work>"}, "data": {"inboxID": "msg_0eb7eef83001M1o8rpSkbKzlf5", "sessionID": "ses_f14812197ffeCbw641wM2r3ZmP", "item": {"type": "synthetic", "payload": {"text": "<system-reminder>\nYou are NO LONGER in Plan mode. The previous Plan restrictions no longer apply. Any Plan mode instructions from earlier in this conversation are no longer active.\n</system-reminder>"}, "delivery": "steer"}}, "durable": {"aggregateID": "ses_f14812197ffeCbw641wM2r3ZmP", "seq": 17, "version": 1}}}}
62+
{"type": "expect_outbound", "label": "session.update.title", "frame": {"type": "session.update", "input": {"sessionID": "ses_f14812197ffeCbw641wM2r3ZmP", "title": "<any>"}}}
63+
{"type": "emit_inbound", "label": "session.update.title.response", "frame": {"type": "sdk.response", "operation": "session.update", "data": null}}
6264
{"type": "expect_outbound", "label": "session.switchModel", "frame": {"type": "session.switchModel", "input": {"sessionID": "ses_f14812197ffeCbw641wM2r3ZmP", "model": {"providerID": "opencode", "id": "nemotron-3.5-lightning-free"}}}}
6365
{"type": "emit_inbound", "label": "session.switchModel.response", "frame": {"type": "sdk.response", "operation": "session.switchModel", "data": null}}
6466
{"type": "emit_inbound", "label": "session.model.selected", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7eef8d001Yy5fmSDr6nQ8OS", "created": 1790657359757, "type": "session.model.selected", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f14812197ffeCbw641wM2r3ZmP", "model": {"id": "nemotron-3.5-lightning-free", "providerID": "opencode"}, "previous": {"id": "big-pickle", "providerID": "opencode", "variant": "default"}}, "durable": {"aggregateID": "ses_f14812197ffeCbw641wM2r3ZmP", "seq": 18, "version": 1}}}}

‎packages/provider-core/src/server/ProviderAdapter.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,8 @@ export interface ProviderAdapterV2OpenSessionInput {
394394

395395
export interface ProviderAdapterV2EnsureThreadInput {
396396
readonly threadId: ThreadId;
397+
/** The app thread's title, for providers that name their native sessions. */
398+
readonly title?: string;
397399
readonly modelSelection: ModelSelection;
398400
readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
399401
readonly providerSessionId?: ProviderSessionId;

‎packages/provider-opencode/src/server/v2/adapter.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,8 @@ interface ThreadState {
345345
* rules stay in force, and a changed mode switches it before prompting.
346346
*/
347347
agent: string;
348+
/** The native session's title as T3 last read or wrote it. */
349+
title: string | undefined;
348350
/** The native session's rules as T3 last read or wrote them, and the policy they are for. */
349351
rules: ReadonlyArray<Rule> | undefined;
350352
policy: RulesPolicy;
@@ -933,6 +935,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
933935
unsettled: false,
934936
directory,
935937
agent: "build",
938+
title: undefined,
936939
rules: undefined,
937940
policy: input.runtimePolicy,
938941
grants: [],
@@ -3011,12 +3014,22 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
30113014
state.policy = policy;
30123015
});
30133016

3017+
/** Names the session after its thread when they differ. */
3018+
const writeTitle = Effect.fnUntraced(function* (state: ThreadState, title: string) {
3019+
const next = title.trim();
3020+
// An empty title asks OpenCode to generate one.
3021+
if (next === "" || next === state.title) return;
3022+
yield* client.session.update({ sessionID: Session.ID.make(state.sessionId), title: next });
3023+
state.title = next;
3024+
});
3025+
30143026
const register = (
30153027
providerThread: OrchestrationV2ProviderThread,
30163028
native: {
30173029
readonly id: string;
30183030
readonly model?: ModelRef | undefined;
30193031
readonly agent?: string | undefined;
3032+
readonly title?: string | undefined;
30203033
readonly permissions?: ReadonlyArray<Rule> | undefined;
30213034
},
30223035
directory: string,
@@ -3028,12 +3041,14 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
30283041
existing.model = native.model;
30293042
existing.directory = directory;
30303043
existing.agent = native.agent ?? existing.agent;
3044+
existing.title = native.title;
30313045
existing.rules = native.permissions;
30323046
return existing;
30333047
}
30343048
const state = newThreadState(native.id, providerThread, directory, undefined);
30353049
state.model = native.model;
30363050
state.agent = native.agent ?? state.agent;
3051+
state.title = native.title;
30373052
state.rules = native.permissions;
30383053
threads.set(native.id, state);
30393054
return state;
@@ -3614,10 +3629,13 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
36143629
policy,
36153630
threadInput.threadId,
36163631
);
3632+
const title = threadInput.title?.trim() || undefined;
3633+
// A session created with a title is never titled by OpenCode's own model.
36173634
const created = yield* client.session.create({
36183635
location: Location.PublicRef.make({ directory: AbsolutePath.make(directory) }),
36193636
model,
36203637
permissions,
3638+
...(title === undefined ? {} : { title }),
36213639
});
36223640
const createdAt = yield* DateTime.now;
36233641
const providerThread: OrchestrationV2ProviderThread = {
@@ -3641,7 +3659,13 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
36413659
};
36423660
const state = register(
36433661
providerThread,
3644-
{ id: created.id, model: created.model, agent: created.agent, permissions },
3662+
{
3663+
id: created.id,
3664+
model: created.model,
3665+
agent: created.agent,
3666+
title: title ?? created.title,
3667+
permissions,
3668+
},
36453669
directory,
36463670
);
36473671
state.policy = policy;
@@ -3800,6 +3824,11 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
38003824
// and its subagents still running hold the rules they started with.
38013825
// Those run on whether or not this turn starts, so theirs are best effort.
38023826
yield* writeRules(state, turnInput.runtimePolicy);
3827+
// A thread renamed since the last turn, or titled after its first prompt.
3828+
yield* writeTitle(state, turnInput.appThread.title).pipe(
3829+
Effect.timeout(REQUEST_REPLY_TIMEOUT),
3830+
Effect.ignore({ log: true }),
3831+
);
38033832
for (const call of runningCalls(state)) {
38043833
if (call.child === undefined) continue;
38053834
yield* writeRules(call.child, turnInput.runtimePolicy).pipe(

0 commit comments

Comments
 (0)