Skip to content

Commit 0596dc4

Browse files
jmfrank63claude
andcommitted
fix(server): open a new OpenCode turn after the provider goes idle
`sendTurn` decided steer-vs-new-turn from the cached `activeTurnId`, which the event pump clears asynchronously once native idle evidence is processed. A follow-up submitted during that gap reused the finished turn's id, skipped `turn.started`, and accrued its tokens to the previous turn, so the message could look like it did nothing. Confirm the native session status before reusing `activeTurnId`, but only where an idle reading is authoritative for that turn. It is not authoritative while idle evidence is deliberately withheld — admission, post-interruption, and reconciliation each mean a known-stale idle is in flight and the prompt is a genuine mid-turn steer — nor before OpenCode has reported the turn busy, since it then describes the state before the turn started. An unavailable or undecodable status keeps the previous behavior. Completing a turn from the preflight leaves the native idle it stood in for still in flight, so arm idle reconciliation: the next idle is checked against live status instead of trusted, and retires the turn it belongs to rather than the turn the follow-up just opened. The status request is itself a suspension point, so re-read `activeTurnId` after it rather than trusting the id captured before it: the pump can retire the turn while the request is in flight, and that is exactly the race being fixed. Fixes #10973 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
1 parent d29c56a commit 0596dc4

2 files changed

Lines changed: 330 additions & 1 deletion

File tree

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

Lines changed: 263 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1627,6 +1627,269 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
16271627
}),
16281628
);
16291629

1630+
it.effect("opens a new turn when the follow-up arrives before the idle event is processed", () =>
1631+
Effect.gen(function* () {
1632+
const adapter = yield* OpenCodeAdapter;
1633+
const threadId = asThreadId("thread-stale-active-turn");
1634+
const sessionID = "http://127.0.0.1:9999/session";
1635+
let nativeIdle = false;
1636+
const busyEvent = promiseWithResolvers<unknown>();
1637+
const retryEvent = promiseWithResolvers<unknown>();
1638+
const heldIdleEvent = promiseWithResolvers<unknown>();
1639+
const retryAfterIdle = promiseWithResolvers<unknown>();
1640+
runtimeMock.state.subscribedEvents = [
1641+
busyEvent.promise,
1642+
retryEvent.promise,
1643+
heldIdleEvent.promise,
1644+
retryAfterIdle.promise,
1645+
];
1646+
runtimeMock.state.sessionStatusImplementation = async () => ({
1647+
data: nativeIdle ? {} : { [sessionID]: { type: "busy" as const } },
1648+
});
1649+
1650+
// `streamEvents` is a shared queue, so subscribers compete for events. Take
1651+
// one phase at a time; anything emitted between phases waits in the queue.
1652+
const startedFiber = yield* adapter.streamEvents.pipe(
1653+
Stream.filter(
1654+
(event) =>
1655+
event.threadId === threadId &&
1656+
(event.type === "turn.started" || event.type === "runtime.warning"),
1657+
),
1658+
Stream.take(2),
1659+
Stream.runCollect,
1660+
Effect.forkChild,
1661+
);
1662+
yield* adapter.startSession({
1663+
provider: ProviderDriverKind.make("opencode"),
1664+
threadId,
1665+
runtimeMode: "full-access",
1666+
});
1667+
const firstTurn = yield* adapter.sendTurn({
1668+
threadId,
1669+
input: "First task",
1670+
modelSelection: createModelSelection(
1671+
ProviderInstanceId.make("opencode"),
1672+
"opencode/kimi-k3",
1673+
),
1674+
});
1675+
busyEvent.resolve({
1676+
id: "evt-busy",
1677+
type: "session.status",
1678+
properties: { sessionID, status: { type: "busy" } },
1679+
});
1680+
// The retry event sits behind the busy event in the same queue, so observing
1681+
// its warning proves the busy status was already applied to the turn.
1682+
retryEvent.resolve({
1683+
id: "evt-retry",
1684+
type: "session.status",
1685+
properties: { sessionID, status: { type: "retry", attempt: 1, message: "transient" } },
1686+
});
1687+
const started = yield* Fiber.join(startedFiber).pipe(Effect.timeout("5 seconds"));
1688+
NodeAssert.deepEqual(
1689+
started.map((event) => event.type),
1690+
["turn.started", "runtime.warning"],
1691+
);
1692+
1693+
const followUpFiber = yield* adapter.streamEvents.pipe(
1694+
Stream.filter(
1695+
(event) =>
1696+
event.threadId === threadId &&
1697+
(event.type === "turn.started" || event.type === "turn.completed"),
1698+
),
1699+
Stream.take(2),
1700+
Stream.runCollect,
1701+
Effect.forkChild,
1702+
);
1703+
// OpenCode has finished the turn, but its idle event is still queued behind
1704+
// the pump, so `activeTurnId` still names the finished turn.
1705+
nativeIdle = true;
1706+
const secondTurn = yield* adapter.sendTurn({
1707+
threadId,
1708+
input: "Second task",
1709+
modelSelection: createModelSelection(
1710+
ProviderInstanceId.make("opencode"),
1711+
"opencode/kimi-k3",
1712+
),
1713+
});
1714+
// OpenCode picks the follow-up up and runs again.
1715+
nativeIdle = false;
1716+
1717+
NodeAssert.notEqual(String(secondTurn.turnId), String(firstTurn.turnId));
1718+
const followUp = yield* Fiber.join(followUpFiber).pipe(Effect.timeout("5 seconds"));
1719+
NodeAssert.deepEqual(
1720+
followUp.map((event) => [event.type, String(event.turnId)]),
1721+
[
1722+
["turn.completed", String(firstTurn.turnId)],
1723+
["turn.started", String(secondTurn.turnId)],
1724+
],
1725+
);
1726+
1727+
// Draining the now-stale idle must not retire the turn it raced. The retry
1728+
// behind it warns only after the idle was handled, so a completion for the
1729+
// second turn would have to arrive first.
1730+
const drainedFiber = yield* adapter.streamEvents.pipe(
1731+
Stream.filter(
1732+
(event) =>
1733+
event.threadId === threadId &&
1734+
(event.type === "turn.completed" || event.type === "runtime.warning"),
1735+
),
1736+
Stream.runHead,
1737+
Effect.forkChild,
1738+
);
1739+
heldIdleEvent.resolve({
1740+
id: "evt-idle-held",
1741+
type: "session.status",
1742+
properties: { sessionID, status: { type: "idle" } },
1743+
});
1744+
retryAfterIdle.resolve({
1745+
id: "evt-retry-after-idle",
1746+
type: "session.status",
1747+
properties: { sessionID, status: { type: "retry", attempt: 2, message: "transient" } },
1748+
});
1749+
const drained = Option.getOrUndefined(
1750+
yield* Fiber.join(drainedFiber).pipe(Effect.timeout("5 seconds")),
1751+
);
1752+
NodeAssert.equal(drained?.type, "runtime.warning");
1753+
1754+
const sessions = yield* adapter.listSessions();
1755+
const session = sessions.find((candidate) => candidate.threadId === threadId);
1756+
NodeAssert.equal(session?.status, "running");
1757+
NodeAssert.equal(String(session?.activeTurnId), String(secondTurn.turnId));
1758+
1759+
// The second turn is intentionally left running; stop the session so its
1760+
// admission recovery loop cannot poll status into the next test.
1761+
yield* adapter.stopSession(threadId);
1762+
}),
1763+
);
1764+
1765+
it.effect("opens a new turn when the idle event lands during the status preflight", () =>
1766+
Effect.gen(function* () {
1767+
const adapter = yield* OpenCodeAdapter;
1768+
const threadId = asThreadId("thread-idle-during-preflight");
1769+
const sessionID = "http://127.0.0.1:9999/session";
1770+
const busyEvent = promiseWithResolvers<unknown>();
1771+
const retryEvent = promiseWithResolvers<unknown>();
1772+
const idleEvent = promiseWithResolvers<unknown>();
1773+
const openEvent = promiseWithResolvers<unknown>();
1774+
const statusStarted = promiseWithResolvers<void>();
1775+
const statusRelease = promiseWithResolvers<void>();
1776+
let statusPhase: "busy" | "preflight" | "done" = "busy";
1777+
runtimeMock.state.subscribedEvents = [
1778+
busyEvent.promise,
1779+
retryEvent.promise,
1780+
idleEvent.promise,
1781+
// Never resolves; keeps the native event stream open until stopSession.
1782+
openEvent.promise,
1783+
];
1784+
// Exactly one status call, the follow-up's preflight, is suspended and
1785+
// answers idle. Every other call reports the session busy.
1786+
runtimeMock.state.sessionStatusImplementation = async () => {
1787+
if (statusPhase !== "preflight") {
1788+
return { data: { [sessionID]: { type: "busy" as const } } };
1789+
}
1790+
statusPhase = "done";
1791+
statusStarted.resolve(undefined);
1792+
await statusRelease.promise;
1793+
return { data: {} };
1794+
};
1795+
1796+
// `streamEvents` is a shared queue, so subscribers compete for events. Take
1797+
// one phase at a time; anything emitted between phases waits in the queue.
1798+
const startedFiber = yield* adapter.streamEvents.pipe(
1799+
Stream.filter(
1800+
(event) =>
1801+
event.threadId === threadId &&
1802+
(event.type === "turn.started" || event.type === "runtime.warning"),
1803+
),
1804+
Stream.take(2),
1805+
Stream.runCollect,
1806+
Effect.forkChild,
1807+
);
1808+
yield* adapter.startSession({
1809+
provider: ProviderDriverKind.make("opencode"),
1810+
threadId,
1811+
runtimeMode: "full-access",
1812+
});
1813+
const firstTurn = yield* adapter.sendTurn({
1814+
threadId,
1815+
input: "First task",
1816+
modelSelection: createModelSelection(
1817+
ProviderInstanceId.make("opencode"),
1818+
"opencode/kimi-k3",
1819+
),
1820+
});
1821+
busyEvent.resolve({
1822+
id: "evt-busy",
1823+
type: "session.status",
1824+
properties: { sessionID, status: { type: "busy" } },
1825+
});
1826+
// The retry event sits behind the busy event in the same queue, so observing
1827+
// its warning proves the busy status was already applied to the turn.
1828+
retryEvent.resolve({
1829+
id: "evt-retry",
1830+
type: "session.status",
1831+
properties: { sessionID, status: { type: "retry", attempt: 1, message: "transient" } },
1832+
});
1833+
const started = yield* Fiber.join(startedFiber).pipe(Effect.timeout("5 seconds"));
1834+
NodeAssert.deepEqual(
1835+
started.map((event) => event.type),
1836+
["turn.started", "runtime.warning"],
1837+
);
1838+
1839+
// Suspend the follow-up inside its preflight, then let the real idle event
1840+
// retire the first turn while that status request is still in flight.
1841+
const completedFiber = yield* adapter.streamEvents.pipe(
1842+
Stream.filter((event) => event.threadId === threadId && event.type === "turn.completed"),
1843+
Stream.runHead,
1844+
Effect.forkChild,
1845+
);
1846+
statusPhase = "preflight";
1847+
const followUpFiber = yield* adapter
1848+
.sendTurn({
1849+
threadId,
1850+
input: "Second task",
1851+
modelSelection: createModelSelection(
1852+
ProviderInstanceId.make("opencode"),
1853+
"opencode/kimi-k3",
1854+
),
1855+
})
1856+
.pipe(Effect.forkChild);
1857+
yield* Effect.promise(() => statusStarted.promise);
1858+
idleEvent.resolve({
1859+
id: "evt-idle-during-preflight",
1860+
type: "session.status",
1861+
properties: { sessionID, status: { type: "idle" } },
1862+
});
1863+
const completed = Option.getOrUndefined(
1864+
yield* Fiber.join(completedFiber).pipe(Effect.timeout("5 seconds")),
1865+
);
1866+
NodeAssert.equal(String(completed?.turnId), String(firstTurn.turnId));
1867+
1868+
// The turn the follow-up captured before the preflight is gone, so resuming
1869+
// it must open a new one rather than steer into the finished turn.
1870+
const secondStartedFiber = yield* adapter.streamEvents.pipe(
1871+
Stream.filter((event) => event.threadId === threadId && event.type === "turn.started"),
1872+
Stream.runHead,
1873+
Effect.forkChild,
1874+
);
1875+
statusRelease.resolve(undefined);
1876+
const secondTurn = yield* Fiber.join(followUpFiber).pipe(Effect.timeout("5 seconds"));
1877+
NodeAssert.notEqual(String(secondTurn.turnId), String(firstTurn.turnId));
1878+
const secondStarted = Option.getOrUndefined(
1879+
yield* Fiber.join(secondStartedFiber).pipe(Effect.timeout("5 seconds")),
1880+
);
1881+
NodeAssert.equal(String(secondStarted?.turnId), String(secondTurn.turnId));
1882+
1883+
const sessions = yield* adapter.listSessions();
1884+
const session = sessions.find((candidate) => candidate.threadId === threadId);
1885+
NodeAssert.equal(String(session?.activeTurnId), String(secondTurn.turnId));
1886+
1887+
// The second turn is intentionally left running; stop the session so its
1888+
// admission recovery loop cannot poll status into the next test.
1889+
yield* adapter.stopSession(threadId);
1890+
}),
1891+
);
1892+
16301893
it.effect("waits for steer admission before accepting the only idle event", () =>
16311894
Effect.gen(function* () {
16321895
const adapter = yield* OpenCodeAdapter;

0 commit comments

Comments
 (0)