Skip to content

Commit 9b21444

Browse files
committed
Fix OpenCode global event ingestion
1 parent 68c98af commit 9b21444

2 files changed

Lines changed: 176 additions & 11 deletions

File tree

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

Lines changed: 120 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ const runtimeMock = {
8080
},
8181
};
8282

83+
const waitForSubscribedEventPoll = () => Effect.runPromise(Effect.sleep("5 millis"));
84+
8385
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
8486
startOpenCodeServerProcess: ({ binaryPath }) =>
8587
Effect.gen(function* () {
@@ -162,8 +164,29 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
162164
event: {
163165
subscribe: async () => ({
164166
stream: (async function* () {
165-
for (const event of runtimeMock.state.subscribedEvents) {
166-
yield event;
167+
let index = 0;
168+
for (let idleCycles = 0; idleCycles < 100; idleCycles++) {
169+
if (index >= runtimeMock.state.subscribedEvents.length) {
170+
await waitForSubscribedEventPoll();
171+
continue;
172+
}
173+
idleCycles = 0;
174+
yield runtimeMock.state.subscribedEvents[index++];
175+
}
176+
})(),
177+
}),
178+
},
179+
global: {
180+
event: async () => ({
181+
stream: (async function* () {
182+
let index = 0;
183+
for (let idleCycles = 0; idleCycles < 100; idleCycles++) {
184+
if (index >= runtimeMock.state.subscribedEvents.length) {
185+
await waitForSubscribedEventPoll();
186+
continue;
187+
}
188+
idleCycles = 0;
189+
yield runtimeMock.state.subscribedEvents[index++];
167190
}
168191
})(),
169192
}),
@@ -744,6 +767,101 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
744767
}),
745768
);
746769

770+
it.effect("ingests assistant text and idle completion from global OpenCode events", () =>
771+
Effect.gen(function* () {
772+
const adapter = yield* OpenCodeAdapter;
773+
const threadId = asThreadId("thread-opencode-global-events");
774+
const sessionId = "http://127.0.0.1:9999/session";
775+
const assistantMessageId = "msg-global-assistant";
776+
const textPartId = "part-global-text";
777+
const eventsFiber = yield* adapter.streamEvents.pipe(
778+
Stream.filter((event) => event.threadId === threadId),
779+
Stream.take(6),
780+
Stream.runCollect,
781+
Effect.forkChild,
782+
);
783+
784+
yield* adapter.startSession({
785+
provider: ProviderDriverKind.make("opencode"),
786+
threadId,
787+
runtimeMode: "full-access",
788+
});
789+
790+
const started = yield* adapter.sendTurn({
791+
threadId,
792+
input: "Say pong",
793+
modelSelection: {
794+
instanceId: ProviderInstanceId.make("opencode"),
795+
model: "openai/gpt-5",
796+
},
797+
});
798+
799+
runtimeMock.state.subscribedEvents.push(
800+
{
801+
directory: "C:\\Users\\mike\\dev-stuff\\t3code",
802+
payload: {
803+
type: "message.updated",
804+
properties: {
805+
sessionID: sessionId,
806+
info: {
807+
id: assistantMessageId,
808+
role: "assistant",
809+
},
810+
},
811+
},
812+
},
813+
{
814+
directory: "C:\\Users\\mike\\dev-stuff\\t3code",
815+
payload: {
816+
type: "message.part.updated",
817+
properties: {
818+
sessionID: sessionId,
819+
part: {
820+
id: textPartId,
821+
sessionID: sessionId,
822+
messageID: assistantMessageId,
823+
type: "text",
824+
text: "pong",
825+
time: { start: 1, end: 2 },
826+
},
827+
time: 2,
828+
},
829+
},
830+
},
831+
{
832+
directory: "C:\\Users\\mike\\dev-stuff\\t3code",
833+
payload: {
834+
type: "session.idle",
835+
properties: {
836+
sessionID: sessionId,
837+
},
838+
},
839+
},
840+
);
841+
842+
const events = Array.from(yield* Fiber.join(eventsFiber).pipe(Effect.timeout("1 second")));
843+
const sessions = yield* adapter.listSessions();
844+
const session = sessions.find((entry) => entry.threadId === threadId);
845+
846+
assert.deepEqual(
847+
events.map((event) => event.type),
848+
[
849+
"session.started",
850+
"thread.started",
851+
"turn.started",
852+
"content.delta",
853+
"item.completed",
854+
"turn.completed",
855+
],
856+
);
857+
const delta = events.find((event) => event.type === "content.delta");
858+
assert.equal(delta?.type === "content.delta" ? delta.payload.delta : undefined, "pong");
859+
assert.equal(events.at(-1)?.turnId, started.turnId);
860+
assert.equal(session?.status, "ready");
861+
assert.equal(session?.activeTurnId, undefined);
862+
}),
863+
);
864+
747865
it.effect("writes provider-native observability records using the session thread id", () =>
748866
Effect.gen(function* () {
749867
const nativeEvents: Array<{

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

Lines changed: 56 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,13 @@ import * as Random from "effect/Random";
2121
import * as Ref from "effect/Ref";
2222
import * as Scope from "effect/Scope";
2323
import * as Stream from "effect/Stream";
24-
import type { OpencodeClient, Part, PermissionRequest, QuestionRequest } from "@opencode-ai/sdk/v2";
24+
import type {
25+
Event as OpenCodeEvent,
26+
OpencodeClient,
27+
Part,
28+
PermissionRequest,
29+
QuestionRequest,
30+
} from "@opencode-ai/sdk/v2";
2531
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
2632

2733
import { resolveAttachmentPath } from "../../attachmentStore.ts";
@@ -58,7 +64,7 @@ interface OpenCodeTurnSnapshot {
5864
}
5965

6066
type OpenCodeSubscribedEvent =
61-
Awaited<ReturnType<OpencodeClient["event"]["subscribe"]>> extends {
67+
Awaited<ReturnType<OpencodeClient["global"]["event"]>> extends {
6268
readonly stream: AsyncIterable<infer TEvent>;
6369
}
6470
? TEvent
@@ -89,7 +95,7 @@ interface OpenCodeSessionContext {
8995
/**
9096
* Sole lifecycle handle for the session. Closing this scope:
9197
* - aborts the `AbortController` registered as a finalizer
92-
* (cancels the in-flight `event.subscribe` fetch),
98+
* (cancels the in-flight `global.event` fetch),
9399
* - interrupts the event-pump and server-exit fibers forked
94100
* via `Effect.forkIn(sessionScope)`,
95101
* - tears down the OpenCode server process for scope-owned servers.
@@ -389,6 +395,24 @@ function toolStateCreatedAt(part: Extract<Part, { type: "tool" }>): string | und
389395
}
390396
}
391397

398+
function unwrapOpenCodeSubscribedEvent(
399+
raw: OpenCodeSubscribedEvent | OpenCodeEvent,
400+
): OpenCodeEvent | null {
401+
if (typeof raw !== "object" || raw === null) {
402+
return null;
403+
}
404+
if ("payload" in raw) {
405+
const payload = raw.payload;
406+
if (typeof payload === "object" && payload !== null && "type" in payload) {
407+
return payload as OpenCodeEvent;
408+
}
409+
}
410+
if ("type" in raw) {
411+
return raw as OpenCodeEvent;
412+
}
413+
return null;
414+
}
415+
392416
function sessionErrorMessage(error: unknown): string {
393417
if (!error || typeof error !== "object") {
394418
return "OpenCode session failed.";
@@ -634,7 +658,7 @@ export function makeOpenCodeAdapter(
634658

635659
const handleSubscribedEvent = Effect.fn("handleSubscribedEvent")(function* (
636660
context: OpenCodeSessionContext,
637-
event: OpenCodeSubscribedEvent,
661+
event: OpenCodeEvent,
638662
) {
639663
const payloadSessionId =
640664
"properties" in event ? (event.properties as { sessionID?: unknown }).sessionID : undefined;
@@ -863,6 +887,25 @@ export function makeOpenCodeAdapter(
863887
break;
864888
}
865889

890+
case "session.idle": {
891+
if (turnId) {
892+
context.activeTurnId = undefined;
893+
yield* updateProviderSession(context, { status: "ready" }, { clearActiveTurnId: true });
894+
yield* emit({
895+
...(yield* buildEventBase({
896+
threadId: context.session.threadId,
897+
turnId,
898+
raw: event,
899+
})),
900+
type: "turn.completed",
901+
payload: {
902+
state: "completed",
903+
},
904+
});
905+
}
906+
break;
907+
}
908+
866909
case "session.status": {
867910
if (event.properties.status.type === "busy") {
868911
yield* updateProviderSession(context, {
@@ -954,7 +997,7 @@ export function makeOpenCodeAdapter(
954997
const startEventPump = Effect.fn("startEventPump")(function* (context: OpenCodeSessionContext) {
955998
// One AbortController per session scope. The finalizer fires when
956999
// the scope closes (explicit stop, unexpected exit, or layer
957-
// shutdown) and cancels the in-flight `event.subscribe` fetch so
1000+
// shutdown) and cancels the in-flight `global.event` fetch so
9581001
// the async iterable unwinds cleanly.
9591002
const eventsAbortController = new AbortController();
9601003
yield* Scope.addFinalizer(
@@ -965,8 +1008,8 @@ export function makeOpenCodeAdapter(
9651008
// Fibers forked into `context.sessionScope` are interrupted
9661009
// automatically when the scope closes — no bookkeeping required.
9671010
yield* Effect.flatMap(
968-
runOpenCodeSdk("event.subscribe", () =>
969-
context.client.event.subscribe(undefined, {
1011+
runOpenCodeSdk("global.event", () =>
1012+
context.client.global.event({
9701013
signal: eventsAbortController.signal,
9711014
}),
9721015
),
@@ -975,11 +1018,15 @@ export function makeOpenCodeAdapter(
9751018
subscription.stream,
9761019
(cause) =>
9771020
new OpenCodeRuntimeError({
978-
operation: "event.subscribe",
1021+
operation: "global.event",
9791022
detail: openCodeRuntimeErrorDetail(cause),
9801023
cause,
9811024
}),
982-
).pipe(Stream.runForEach((event) => handleSubscribedEvent(context, event))),
1025+
).pipe(
1026+
Stream.map(unwrapOpenCodeSubscribedEvent),
1027+
Stream.filter((event): event is OpenCodeEvent => event !== null),
1028+
Stream.runForEach((event) => handleSubscribedEvent(context, event)),
1029+
),
9831030
).pipe(
9841031
Effect.exit,
9851032
Effect.flatMap((exit) =>

0 commit comments

Comments
 (0)