Skip to content

Commit f4137b5

Browse files
committed
Fix OpenCode event session routing
1 parent b793401 commit f4137b5

2 files changed

Lines changed: 130 additions & 15 deletions

File tree

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

Lines changed: 113 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,9 @@ const runtimeMock = {
6363
closeError: null as Error | null,
6464
messages: [] as MessageEntry[],
6565
subscribedEvents: [] as unknown[],
66+
subscribedEventDirectory: process.cwd(),
67+
globalEventCalls: 0,
68+
keepSubscriptionOpen: false,
6669
},
6770
reset() {
6871
this.state.startCalls.length = 0;
@@ -76,9 +79,21 @@ const runtimeMock = {
7679
this.state.closeError = null;
7780
this.state.messages = [];
7881
this.state.subscribedEvents = [];
82+
this.state.subscribedEventDirectory = process.cwd();
83+
this.state.globalEventCalls = 0;
84+
this.state.keepSubscriptionOpen = false;
7985
},
8086
};
8187

88+
function toGlobalEvent(event: unknown, directory: string): unknown {
89+
return event && typeof event === "object" && "payload" in event
90+
? event
91+
: {
92+
directory,
93+
payload: event,
94+
};
95+
}
96+
8297
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
8398
startOpenCodeServerProcess: ({ binaryPath }) =>
8499
Effect.gen(function* () {
@@ -158,14 +173,33 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
158173
: runtimeMock.state.messages;
159174
},
160175
},
176+
global: {
177+
event: async (options?: { signal?: AbortSignal }) => {
178+
runtimeMock.state.globalEventCalls += 1;
179+
return {
180+
stream: (async function* () {
181+
let index = 0;
182+
while (!options?.signal?.aborted) {
183+
if (index < runtimeMock.state.subscribedEvents.length) {
184+
yield toGlobalEvent(
185+
runtimeMock.state.subscribedEvents[index++],
186+
runtimeMock.state.subscribedEventDirectory,
187+
);
188+
continue;
189+
}
190+
if (!runtimeMock.state.keepSubscriptionOpen) {
191+
break;
192+
}
193+
await Effect.runPromise(Effect.sleep("5 millis"));
194+
}
195+
})(),
196+
};
197+
},
198+
},
161199
event: {
162-
subscribe: async () => ({
163-
stream: (async function* () {
164-
for (const event of runtimeMock.state.subscribedEvents) {
165-
yield event;
166-
}
167-
})(),
168-
}),
200+
subscribe: async () => {
201+
throw new Error("OpenCodeAdapter should use global.event for runtime events");
202+
},
169203
},
170204
}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
171205
loadOpenCodeInventory: () =>
@@ -654,6 +688,78 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
654688
}),
655689
);
656690

691+
it.effect("streams current OpenCode global event payloads for the session directory", () =>
692+
Effect.gen(function* () {
693+
const adapter = yield* OpenCodeAdapter;
694+
const threadId = asThreadId("thread-opencode-current-event-shape");
695+
runtimeMock.state.keepSubscriptionOpen = true;
696+
runtimeMock.state.subscribedEventDirectory = "/repo/current-event-shape";
697+
const eventsFiber = yield* adapter.streamEvents.pipe(
698+
Stream.filter((event) => event.threadId === threadId),
699+
Stream.filter((event) => event.type === "content.delta"),
700+
Stream.take(1),
701+
Stream.runCollect,
702+
Effect.forkChild,
703+
);
704+
705+
yield* adapter.startSession({
706+
provider: ProviderDriverKind.make("opencode"),
707+
threadId,
708+
cwd: "/repo/current-event-shape",
709+
runtimeMode: "full-access",
710+
});
711+
const turn = yield* adapter.sendTurn({
712+
threadId,
713+
input: "Fix it",
714+
modelSelection: {
715+
instanceId: ProviderInstanceId.make("opencode"),
716+
model: "openai/gpt-5",
717+
},
718+
});
719+
720+
runtimeMock.state.subscribedEvents.push(
721+
{
722+
type: "message.updated",
723+
properties: {
724+
sessionID: "http://127.0.0.1:9999/session",
725+
info: {
726+
id: "msg-assistant-current-shape",
727+
role: "assistant",
728+
},
729+
},
730+
},
731+
{
732+
type: "message.part.updated",
733+
properties: {
734+
sessionID: "http://127.0.0.1:9999/session",
735+
part: {
736+
id: "prt-assistant-current-shape",
737+
sessionID: "http://127.0.0.1:9999/session",
738+
messageID: "msg-assistant-current-shape",
739+
type: "text",
740+
text: "Hello",
741+
time: {
742+
start: 1_778_000_000_000,
743+
},
744+
},
745+
},
746+
},
747+
);
748+
749+
const events = Array.from(yield* Fiber.join(eventsFiber).pipe(Effect.timeout("1 second")));
750+
assert.deepEqual(
751+
events.map((event) => event.type),
752+
["content.delta"],
753+
);
754+
assert.equal(runtimeMock.state.globalEventCalls, 1);
755+
const delta = events.find((event) => event.type === "content.delta");
756+
assert.equal(delta?.turnId, turn.turnId);
757+
if (delta?.type === "content.delta") {
758+
assert.equal(delta.payload.delta, "Hello");
759+
}
760+
}),
761+
);
762+
657763
it.effect("writes provider-native observability records using the session thread id", () =>
658764
Effect.gen(function* () {
659765
const nativeEvents: Array<{

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

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,12 @@ interface OpenCodeTurnSnapshot {
5858
}
5959

6060
type OpenCodeSubscribedEvent =
61-
Awaited<ReturnType<OpencodeClient["event"]["subscribe"]>> extends {
61+
Awaited<ReturnType<OpencodeClient["global"]["event"]>> extends {
6262
readonly stream: AsyncIterable<infer TEvent>;
6363
}
64-
? TEvent
64+
? TEvent extends { readonly payload: infer TPayload }
65+
? TPayload
66+
: never
6567
: never;
6668

6769
interface OpenCodeSessionContext {
@@ -89,7 +91,7 @@ interface OpenCodeSessionContext {
8991
/**
9092
* Sole lifecycle handle for the session. Closing this scope:
9193
* - aborts the `AbortController` registered as a finalizer
92-
* (cancels the in-flight `event.subscribe` fetch),
94+
* (cancels the in-flight `global.event` fetch),
9395
* - interrupts the event-pump and server-exit fibers forked
9496
* via `Effect.forkIn(sessionScope)`,
9597
* - tears down the OpenCode server process for scope-owned servers.
@@ -954,7 +956,7 @@ export function makeOpenCodeAdapter(
954956
const startEventPump = Effect.fn("startEventPump")(function* (context: OpenCodeSessionContext) {
955957
// One AbortController per session scope. The finalizer fires when
956958
// the scope closes (explicit stop, unexpected exit, or layer
957-
// shutdown) and cancels the in-flight `event.subscribe` fetch so
959+
// shutdown) and cancels the in-flight `global.event` fetch so
958960
// the async iterable unwinds cleanly.
959961
const eventsAbortController = new AbortController();
960962
yield* Scope.addFinalizer(
@@ -965,8 +967,8 @@ export function makeOpenCodeAdapter(
965967
// Fibers forked into `context.sessionScope` are interrupted
966968
// automatically when the scope closes — no bookkeeping required.
967969
yield* Effect.flatMap(
968-
runOpenCodeSdk("event.subscribe", () =>
969-
context.client.event.subscribe(undefined, {
970+
runOpenCodeSdk("global.event", () =>
971+
context.client.global.event({
970972
signal: eventsAbortController.signal,
971973
}),
972974
),
@@ -975,11 +977,18 @@ export function makeOpenCodeAdapter(
975977
subscription.stream,
976978
(cause) =>
977979
new OpenCodeRuntimeError({
978-
operation: "event.subscribe",
980+
operation: "global.event",
979981
detail: openCodeRuntimeErrorDetail(cause),
980982
cause,
981983
}),
982-
).pipe(Stream.runForEach((event) => handleSubscribedEvent(context, event))),
984+
).pipe(
985+
Stream.runForEach((event) => {
986+
if (!("directory" in event) || event.directory !== context.directory) {
987+
return Effect.void;
988+
}
989+
return handleSubscribedEvent(context, event.payload);
990+
}),
991+
),
983992
).pipe(
984993
Effect.exit,
985994
Effect.flatMap((exit) =>

0 commit comments

Comments
 (0)