Compare commits

...
51 changed files with 5910 additions and 2340 deletions

No files matched your search

+5
View File
@@ -22,6 +22,7 @@ const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION ===
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
const promptDelayMs = Number(process.env.T3_ACP_PROMPT_DELAY_MS ?? "0");
const permissionOptionIds = {
allowOnce: process.env.T3_ACP_ALLOW_ONCE_OPTION_ID ?? "allow-once",
allowAlways: process.env.T3_ACP_ALLOW_ALWAYS_OPTION_ID ?? "allow-always",
@@ -364,6 +365,10 @@ const program = Effect.gen(function* () {
Effect.gen(function* () {
const requestedSessionId = String(request.sessionId ?? sessionId);
if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
yield* Effect.sleep(`${promptDelayMs} millis`);
}
if (emitInterleavedAssistantToolCalls) {
const toolCallId = "tool-call-1";
+22
View File
@@ -0,0 +1,22 @@
import { assert, it } from "@effect/vitest";
import { ProviderInstanceId } from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import { getCodexServiceTierOptionValue } from "./codexModelOptions.ts";
it("returns the selected Codex service tier id", () => {
const selection = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.5", [
{ id: "serviceTier", value: "flex" },
]);
assert.equal(getCodexServiceTierOptionValue(selection), "flex");
});
it("keeps legacy persisted fast mode selections working", () => {
const selection = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
{ id: "fastMode", value: true },
]);
assert.equal(getCodexServiceTierOptionValue(selection), "fast");
});
+14
View File
@@ -0,0 +1,14 @@
import type { ModelSelection } from "@t3tools/contracts";
import {
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
} from "@t3tools/shared/model";
export function getCodexServiceTierOptionValue(
modelSelection: ModelSelection | null | undefined,
): string | undefined {
return (
getModelSelectionStringOptionValue(modelSelection, "serviceTier") ??
(getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true ? "fast" : undefined)
);
}
+1 -1
View File
@@ -747,7 +747,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
);
const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (cwd: string) {
const details = yield* gitCore
.statusDetails(cwd)
.statusDetailsRemote(cwd)
.pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null)));
if (details === null || !details.isRepo) {
return null;
@@ -1232,6 +1232,227 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
}),
);
it.effect("keeps the turn running across interim assistant messages until the session ends", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = "2026-01-01T00:00:00.000Z";
const threadId = ThreadId.make("thread-turn-lifecycle");
const turnId = TurnId.make("turn-lifecycle-1");
yield* eventStore.append({
type: "thread.created",
eventId: EventId.make("evt-tl1"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-tl1"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-tl1"),
metadata: {},
payload: {
threadId,
projectId: ProjectId.make("project-turn-lifecycle"),
title: "Turn lifecycle",
modelSelection: {
instanceId: ProviderInstanceId.make("claude"),
model: "claude-opus",
},
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
yield* eventStore.append({
type: "thread.session-set",
eventId: EventId.make("evt-tl2"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-01-01T00:00:01.000Z",
commandId: CommandId.make("cmd-tl2"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-tl2"),
metadata: {},
payload: {
threadId,
session: {
threadId,
status: "running",
providerName: "claude",
runtimeMode: "full-access",
activeTurnId: turnId,
lastError: null,
updatedAt: "2026-01-01T00:00:01.000Z",
},
},
});
// Interim assistant message completes mid-turn (commentary between
// tool calls) — the turn must stay running and unsettled.
yield* eventStore.append({
type: "thread.message-sent",
eventId: EventId.make("evt-tl3"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-01-01T00:00:05.000Z",
commandId: CommandId.make("cmd-tl3"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-tl3"),
metadata: {},
payload: {
threadId,
messageId: MessageId.make("message-tl-interim"),
role: "assistant",
text: "interim commentary",
turnId,
streaming: false,
createdAt: "2026-01-01T00:00:05.000Z",
updatedAt: "2026-01-01T00:00:05.000Z",
},
});
yield* projectionPipeline.bootstrap;
const runningRows = yield* sql<{
readonly state: string;
readonly completedAt: string | null;
}>`
SELECT state, completed_at AS "completedAt"
FROM projection_turns
WHERE thread_id = ${threadId} AND turn_id = ${turnId}
`;
assert.deepEqual(runningRows, [{ state: "running", completedAt: null }]);
// The session leaving "running" is the turn-end signal.
yield* eventStore.append({
type: "thread.session-set",
eventId: EventId.make("evt-tl4"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-01-01T00:01:00.000Z",
commandId: CommandId.make("cmd-tl4"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-tl4"),
metadata: {},
payload: {
threadId,
session: {
threadId,
status: "ready",
providerName: "claude",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: "2026-01-01T00:01:00.000Z",
},
},
});
yield* projectionPipeline.bootstrap;
const settledRows = yield* sql<{
readonly state: string;
readonly completedAt: string | null;
}>`
SELECT state, completed_at AS "completedAt"
FROM projection_turns
WHERE thread_id = ${threadId} AND turn_id = ${turnId}
`;
assert.deepEqual(settledRows, [
{ state: "completed", completedAt: "2026-01-01T00:01:00.000Z" },
]);
}),
);
it.effect("settles a superseded running turn when a new turn becomes active", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = "2026-01-01T00:00:00.000Z";
const threadId = ThreadId.make("thread-turn-supersede");
const oldTurnId = TurnId.make("turn-superseded");
const newTurnId = TurnId.make("turn-steer");
yield* eventStore.append({
type: "thread.created",
eventId: EventId.make("evt-ts1"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-ts1"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-ts1"),
metadata: {},
payload: {
threadId,
projectId: ProjectId.make("project-turn-supersede"),
title: "Turn supersede",
modelSelection: {
instanceId: ProviderInstanceId.make("opencode"),
model: "big-pickle",
},
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
const appendRunningSessionSet = (eventId: string, turnId: TurnId, updatedAt: string) =>
eventStore.append({
type: "thread.session-set",
eventId: EventId.make(eventId),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: updatedAt,
commandId: CommandId.make(`cmd-${eventId}`),
causationEventId: null,
correlationId: CorrelationId.make(`cmd-${eventId}`),
metadata: {},
payload: {
threadId,
session: {
threadId,
status: "running",
providerName: "opencode",
runtimeMode: "full-access",
activeTurnId: turnId,
lastError: null,
updatedAt,
},
},
});
yield* appendRunningSessionSet("evt-ts2", oldTurnId, "2026-01-01T00:00:01.000Z");
// A steer: a new turn becomes active without the provider ever
// completing the previous one.
yield* appendRunningSessionSet("evt-ts3", newTurnId, "2026-01-01T00:00:30.000Z");
yield* projectionPipeline.bootstrap;
const rows = yield* sql<{
readonly turnId: string;
readonly state: string;
readonly completedAt: string | null;
}>`
SELECT turn_id AS "turnId", state, completed_at AS "completedAt"
FROM projection_turns
WHERE thread_id = ${threadId}
ORDER BY requested_at
`;
assert.deepEqual(rows, [
{ turnId: oldTurnId, state: "completed", completedAt: "2026-01-01T00:00:30.000Z" },
{ turnId: newTurnId, state: "running", completedAt: null },
]);
}),
);
it.effect("keeps accumulated assistant text when completion payload text is empty", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
@@ -2,6 +2,7 @@ import {
ApprovalRequestId,
type ChatAttachment,
type OrchestrationEvent,
type OrchestrationSessionStatus,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
@@ -69,6 +70,29 @@ export const ORCHESTRATION_PROJECTOR_NAMES = {
type ProjectorName =
(typeof ORCHESTRATION_PROJECTOR_NAMES)[keyof typeof ORCHESTRATION_PROJECTOR_NAMES];
/**
* Turn state to settle still-running turns with when their session leaves the
* "running" status, or null while the session is (re)starting or running and
* turns must stay unsettled.
*/
function settledTurnStateForSessionStatus(
status: OrchestrationSessionStatus,
): "completed" | "interrupted" | "error" | null {
switch (status) {
case "idle":
case "ready":
return "completed";
case "error":
return "error";
case "interrupted":
case "stopped":
return "interrupted";
case "starting":
case "running":
return null;
}
}
interface ProjectorDefinition {
readonly name: ProjectorName;
readonly apply: (
@@ -999,9 +1023,57 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
case "thread.session-set": {
const turnId = event.payload.session.activeTurnId;
if (turnId === null || event.payload.session.status !== "running") {
// Leaving the "running" session status is the turn-end signal:
// settle still-running turns so their duration reflects the whole
// turn rather than the last assistant message.
const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);
if (settledTurnState === null) {
return;
}
const existingTurns = yield* projectionTurnRepository.listByThreadId({
threadId: event.payload.threadId,
});
yield* Effect.forEach(
existingTurns.filter((turn) => turn.turnId !== null && turn.state === "running"),
(turn) =>
turn.turnId === null
? Effect.void
: projectionTurnRepository.upsertByTurnId({
...turn,
turnId: turn.turnId,
state: settledTurnState,
// A running turn's completedAt can only hold a mid-turn
// placeholder checkpoint timestamp — the session leaving
// "running" is the authoritative turn end.
completedAt: event.payload.session.updatedAt,
}),
{ concurrency: 1 },
);
return;
}
// A new active turn supersedes any still-running turn on the same
// thread — steering can open a new turn without the provider ever
// completing the previous one.
const otherRunningTurns = yield* projectionTurnRepository.listByThreadId({
threadId: event.payload.threadId,
});
yield* Effect.forEach(
otherRunningTurns.filter(
(turn) => turn.turnId !== null && turn.turnId !== turnId && turn.state === "running",
),
(turn) =>
turn.turnId === null
? Effect.void
: projectionTurnRepository.upsertByTurnId({
...turn,
turnId: turn.turnId,
state: "completed",
completedAt: event.payload.session.updatedAt,
}),
{ concurrency: 1 },
);
const existingTurn = yield* projectionTurnRepository.getByTurnId({
threadId: event.payload.threadId,
turnId,
@@ -1080,6 +1152,19 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
if (event.payload.turnId === null || event.payload.role !== "assistant") {
return;
}
// A completed assistant message only settles the turn once the
// session is no longer running it — providers may emit several
// assistant messages per turn (commentary between tool calls), and
// the turn must stay unsettled until the provider reports turn end
// (projected as thread.session-set leaving the "running" status).
const session = yield* projectionThreadSessionRepository.getByThreadId({
threadId: event.payload.threadId,
});
const turnStillRunning =
Option.isSome(session) &&
session.value.status === "running" &&
session.value.activeTurnId === event.payload.turnId;
const settlesTurn = !event.payload.streaming && !turnStillRunning;
const existingTurn = yield* projectionTurnRepository.getByTurnId({
threadId: event.payload.threadId,
turnId: event.payload.turnId,
@@ -1088,16 +1173,16 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionTurnRepository.upsertByTurnId({
...existingTurn.value,
assistantMessageId: event.payload.messageId,
state: event.payload.streaming
? existingTurn.value.state
: existingTurn.value.state === "interrupted"
state: settlesTurn
? existingTurn.value.state === "interrupted"
? "interrupted"
: existingTurn.value.state === "error"
? "error"
: "completed",
completedAt: event.payload.streaming
? existingTurn.value.completedAt
: (existingTurn.value.completedAt ?? event.payload.updatedAt),
: "completed"
: existingTurn.value.state,
completedAt: settlesTurn
? (existingTurn.value.completedAt ?? event.payload.updatedAt)
: existingTurn.value.completedAt,
startedAt: existingTurn.value.startedAt ?? event.payload.createdAt,
requestedAt: existingTurn.value.requestedAt ?? event.payload.createdAt,
});
@@ -1110,10 +1195,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
sourceProposedPlanThreadId: null,
sourceProposedPlanId: null,
assistantMessageId: event.payload.messageId,
state: event.payload.streaming ? "running" : "completed",
state: settlesTurn ? "completed" : "running",
requestedAt: event.payload.createdAt,
startedAt: event.payload.createdAt,
completedAt: event.payload.streaming ? null : event.payload.updatedAt,
completedAt: settlesTurn ? event.payload.updatedAt : null,
checkpointTurnCount: null,
checkpointRef: null,
checkpointStatus: null,
@@ -1160,6 +1245,15 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
}
case "thread.turn-diff-completed": {
// Mid-turn diff updates produce placeholder checkpoints; record the
// checkpoint, but don't settle a turn its session is still running.
const session = yield* projectionThreadSessionRepository.getByThreadId({
threadId: event.payload.threadId,
});
const turnStillRunning =
Option.isSome(session) &&
session.value.status === "running" &&
session.value.activeTurnId === event.payload.turnId;
const existingTurn = yield* projectionTurnRepository.getByTurnId({
threadId: event.payload.threadId,
turnId: event.payload.turnId,
@@ -1175,7 +1269,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionTurnRepository.upsertByTurnId({
...existingTurn.value,
assistantMessageId: event.payload.assistantMessageId,
state: nextState,
state: turnStillRunning ? existingTurn.value.state : nextState,
checkpointTurnCount: event.payload.checkpointTurnCount,
checkpointRef: event.payload.checkpointRef,
checkpointStatus: event.payload.status,
@@ -1193,7 +1287,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
sourceProposedPlanThreadId: null,
sourceProposedPlanId: null,
assistantMessageId: event.payload.assistantMessageId,
state: nextState,
state: turnStillRunning ? "running" : nextState,
requestedAt: event.payload.completedAt,
startedAt: event.payload.completedAt,
completedAt: event.payload.completedAt,
@@ -1117,39 +1117,39 @@ describe("ProviderRuntimeIngestion", () => {
const createdAt = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create-plan-source-guarded"),
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: "plan",
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-plan-source-guarded"),
threadId: sourceThreadId,
session: {
Effect.andThen(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create-plan-source-guarded"),
threadId: sourceThreadId,
status: "ready",
providerName: "codex",
projectId: asProjectId("project-1"),
title: "Plan Source",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: "plan",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
branch: null,
worktreePath: null,
createdAt,
}),
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-plan-source-guarded"),
threadId: sourceThreadId,
session: {
threadId: sourceThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
),
);
harness.setProviderSession({
provider: ProviderDriverKind.make("codex"),
@@ -1260,6 +1260,92 @@ describe("ProviderRuntimeIngestion", () => {
expect(targetThreadAfterRejectedStart?.session?.activeTurnId).toBe(activeTurnId);
});
it("accepts a conflicting turn.started for a pending turn start when the provider expects that turn", async () => {
// Steering a running turn: the server requests a new turn while the old
// one is still active, and providers like opencode open the new turn
// without ever completing the superseded one. The new turn.started must
// replace the active turn instead of being rejected as stale.
const harness = await createHarness();
const threadId = asThreadId("thread-1");
const oldTurnId = asTurnId("turn-steered-over");
const newTurnId = asTurnId("turn-from-steer");
const createdAt = "2026-01-01T00:00:00.000Z";
harness.setProviderSession({
provider: ProviderDriverKind.make("codex"),
status: "running",
runtimeMode: "approval-required",
threadId,
createdAt,
updatedAt: createdAt,
activeTurnId: oldTurnId,
});
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-steered-over"),
provider: ProviderDriverKind.make("codex"),
createdAt,
threadId,
turnId: oldTurnId,
});
await waitForThread(
harness.readModel,
(thread) =>
thread.session?.status === "running" && thread.session?.activeTurnId === oldTurnId,
2_000,
threadId,
);
// The steer: a user-requested turn start while the old turn still runs.
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-steer"),
threadId,
message: {
messageId: asMessageId("msg-steer"),
role: "user",
text: "actually, do 15 instead",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt,
}),
);
// The provider session tracks the new turn before emitting turn.started
// (sendTurn updates the session first).
harness.setProviderSession({
provider: ProviderDriverKind.make("codex"),
status: "running",
runtimeMode: "approval-required",
threadId,
createdAt,
updatedAt: createdAt,
activeTurnId: newTurnId,
});
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-from-steer"),
provider: ProviderDriverKind.make("codex"),
createdAt,
threadId,
turnId: newTurnId,
});
const threadAfterSteer = await waitForThread(
harness.readModel,
(thread) =>
thread.session?.status === "running" && thread.session?.activeTurnId === newTurnId,
2_000,
threadId,
);
expect(threadAfterSteer.session?.activeTurnId).toBe(newTurnId);
expect(threadAfterSteer.latestTurn?.turnId).toBe(newTurnId);
expect(threadAfterSteer.latestTurn?.state).toBe("running");
});
it("does not mark the source proposed plan implemented for an unrelated turn.started when no thread active turn is tracked", async () => {
const harness = await createHarness();
const sourceThreadId = asThreadId("thread-plan");
@@ -1226,6 +1226,22 @@ const make = Effect.gen(function* () {
activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined;
// A turn.started that conflicts with the active turn is legitimate when
// the server itself has a turn start pending for this thread AND the
// provider session already tracks the event's turn as its active turn:
// steering a running turn makes some providers (e.g. opencode) open a
// new turn without ever completing the superseded one. A stale
// turn.started for some other turn id still gets rejected.
const conflictingTurnStartIsPendingTurnStart =
event.type === "turn.started" && conflictsWithActiveTurn
? sameId(yield* getExpectedProviderTurnIdForThread(thread.id), eventTurnId) &&
Option.isSome(
yield* projectionTurnRepository.getPendingTurnStartByThreadId({
threadId: thread.id,
}),
)
: false;
const shouldApplyThreadLifecycle = (() => {
if (!STRICT_PROVIDER_LIFECYCLE_GUARD) {
return true;
@@ -1237,7 +1253,7 @@ const make = Effect.gen(function* () {
case "thread.started":
return true;
case "turn.started":
return !conflictsWithActiveTurn;
return !conflictsWithActiveTurn || conflictingTurnStartIsPendingTurnStart;
case "turn.completed":
if (conflictsWithActiveTurn || missingTurnForActiveTurn) {
return false;
+62 -23
View File
@@ -267,37 +267,76 @@ describe("orchestration projector", () => {
),
);
const afterRunning = await Effect.runPromise(
projectEvent(
afterCreate,
makeEvent({
sequence: 2,
type: "thread.session-set",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: startedAt,
commandId: "cmd-running",
payload: {
threadId: "thread-1",
session: {
const settledAt = "2026-02-23T08:01:00.000Z";
const [afterRunning, afterReady] = await Effect.runPromise(
Effect.flatMap(
projectEvent(
afterCreate,
makeEvent({
sequence: 2,
type: "thread.session-set",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: startedAt,
commandId: "cmd-running",
payload: {
threadId: "thread-1",
status: "running",
providerName: "codex",
providerSessionId: "session-1",
providerThreadId: "provider-thread-1",
runtimeMode: "approval-required",
activeTurnId: "turn-1",
lastError: null,
updatedAt: startedAt,
session: {
threadId: "thread-1",
status: "running",
providerName: "codex",
providerSessionId: "session-1",
providerThreadId: "provider-thread-1",
runtimeMode: "approval-required",
activeTurnId: "turn-1",
lastError: null,
updatedAt: startedAt,
},
},
},
}),
}),
),
(running) =>
Effect.map(
projectEvent(
running,
makeEvent({
sequence: 3,
type: "thread.session-set",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: settledAt,
commandId: "cmd-ready",
payload: {
threadId: "thread-1",
session: {
threadId: "thread-1",
status: "ready",
providerName: "codex",
providerSessionId: "session-1",
providerThreadId: "provider-thread-1",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: settledAt,
},
},
}),
),
(ready) => [running, ready] as const,
),
),
);
const thread = afterRunning.threads[0];
expect(thread?.latestTurn?.turnId).toBe("turn-1");
expect(thread?.session?.status).toBe("running");
// Leaving the "running" session status settles the running turn with the
// session timestamp as the turn end.
const settledThread = afterReady.threads[0];
expect(settledThread?.latestTurn?.turnId).toBe("turn-1");
expect(settledThread?.latestTurn?.state).toBe("completed");
expect(settledThread?.latestTurn?.completedAt).toBe(settledAt);
});
it("updates canonical thread runtime mode from thread.runtime-mode-set", async () => {
+59 -15
View File
@@ -38,6 +38,29 @@ function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error"
return "completed" as const;
}
/**
* Turn state to settle a still-running latest turn with when its session
* leaves the "running" status, or null while the session is (re)starting or
* running and the turn must stay unsettled.
*/
function settledTurnStateForSessionStatus(
status: OrchestrationSession["status"],
): "completed" | "interrupted" | "error" | null {
switch (status) {
case "idle":
case "ready":
return "completed";
case "error":
return "error";
case "interrupted":
case "stopped":
return "interrupted";
case "starting":
case "running":
return null;
}
}
function updateThread(
threads: ReadonlyArray<OrchestrationThread>,
threadId: ThreadId,
@@ -438,6 +461,9 @@ export function projectEvent(
"session",
);
// Leaving the "running" session status is the turn-end signal: settle
// a still-running latest turn so its duration reflects the whole turn.
const settledTurnState = settledTurnStateForSessionStatus(session.status);
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
@@ -461,7 +487,18 @@ export function projectEvent(
? thread.latestTurn.assistantMessageId
: null,
}
: thread.latestTurn,
: thread.latestTurn !== null &&
thread.latestTurn.state === "running" &&
settledTurnState !== null
? {
...thread.latestTurn,
state: settledTurnState,
// A running turn's completedAt can only hold a mid-turn
// placeholder checkpoint timestamp — the session leaving
// "running" is the authoritative turn end.
completedAt: session.updatedAt,
}
: thread.latestTurn,
updatedAt: event.occurredAt,
}),
};
@@ -544,24 +581,31 @@ export function projectEvent(
.toSorted((left, right) => left.checkpointTurnCount - right.checkpointTurnCount)
.slice(-MAX_THREAD_CHECKPOINTS);
// Mid-turn diff updates produce placeholder checkpoints; record the
// checkpoint, but don't settle a turn its session is still running.
const turnStillRunning =
thread.session?.status === "running" && thread.session.activeTurnId === payload.turnId;
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
checkpoints,
latestTurn: {
turnId: payload.turnId,
state: checkpointStatusToLatestTurnState(payload.status),
requestedAt:
thread.latestTurn?.turnId === payload.turnId
? thread.latestTurn.requestedAt
: payload.completedAt,
startedAt:
thread.latestTurn?.turnId === payload.turnId
? (thread.latestTurn.startedAt ?? payload.completedAt)
: payload.completedAt,
completedAt: payload.completedAt,
assistantMessageId: payload.assistantMessageId,
},
latestTurn: turnStillRunning
? thread.latestTurn
: {
turnId: payload.turnId,
state: checkpointStatusToLatestTurnState(payload.status),
requestedAt:
thread.latestTurn?.turnId === payload.turnId
? thread.latestTurn.requestedAt
: payload.completedAt,
startedAt:
thread.latestTurn?.turnId === payload.turnId
? (thread.latestTurn.startedAt ?? payload.completedAt)
: payload.completedAt,
completedAt: payload.completedAt,
assistantMessageId: payload.assistantMessageId,
},
updatedAt: event.occurredAt,
}),
};
@@ -890,6 +890,73 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEventsFiber = yield* Stream.takeUntil(
adapter.streamEvents,
(event) => event.type === "turn.completed",
).pipe(Stream.runCollect, Effect.forkChild);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "run 5 commands",
attachments: [],
});
// Steer: a second sendTurn while the turn is still running continues
// the same turn — the message is queued into the live agent loop.
const steeredTurn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "actually run 15",
attachments: [],
});
assert.equal(String(steeredTurn.turnId), String(turn.turnId));
harness.query.emit({
type: "assistant",
session_id: "sdk-session-steer",
uuid: "assistant-steer-1",
parent_tool_use_id: null,
message: {
id: "assistant-message-steer-1",
content: [{ type: "text", text: "Adjusting to 15." }],
},
} as unknown as SDKMessage);
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
session_id: "sdk-session-steer",
uuid: "result-steer-1",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
const turnStartedEvents = runtimeEvents.filter((event) => event.type === "turn.started");
const turnCompletedEvents = runtimeEvents.filter((event) => event.type === "turn.completed");
// One turn boundary for the whole run: the steer produced no
// turn.completed/turn.started pair.
assert.equal(turnStartedEvents.length, 1);
assert.equal(String(turnStartedEvents[0]?.turnId), String(turn.turnId));
assert.equal(turnCompletedEvents.length, 1);
assert.equal(String(turnCompletedEvents[0]?.turnId), String(turn.turnId));
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("maps Claude reasoning deltas, streamed tool inputs, and tool results", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -122,6 +122,13 @@ interface ClaudeResumeState {
interface ClaudeTurnState {
readonly turnId: TurnId;
readonly startedAt: string;
/**
* True for turns auto-started by assistant output arriving without an
* active turn (background agent/subagent responses between user prompts).
* Synthetic turns are auto-closed by the next sendTurn; real turns are
* steered instead (the queued message continues the same turn).
*/
readonly synthetic?: boolean;
readonly items: Array<unknown>;
readonly assistantTextBlocks: Map<number, AssistantTextBlockState>;
readonly assistantTextBlockOrder: Array<AssistantTextBlockState>;
@@ -2486,6 +2493,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
context.turnState = {
turnId,
startedAt,
synthetic: true,
items: [],
assistantTextBlocks: new Map(),
assistantTextBlockOrder: [],
@@ -3629,9 +3637,14 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
? input.modelSelection
: undefined;
if (context.turnState) {
// Auto-close a stale synthetic turn (from background agent responses
// between user prompts) to prevent blocking the user's next turn.
// A sendTurn while a real turn is running is a steer: the message is
// queued into the live SDK agent loop and the work continues as the same
// turn — no synthetic turn boundary. Stale synthetic turns (from
// background agent responses between user prompts) are auto-closed
// instead, so they don't block the user's next turn.
const steeringTurnState =
context.turnState && context.turnState.synthetic !== true ? context.turnState : null;
if (context.turnState && steeringTurnState === null) {
yield* completeTurn(context, "completed");
}
@@ -3666,37 +3679,39 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
}
const turnId = TurnId.make(yield* randomUUIDv4);
const turnState: ClaudeTurnState = {
turnId,
startedAt: yield* nowIso,
items: [],
assistantTextBlocks: new Map(),
assistantTextBlockOrder: [],
capturedProposedPlanKeys: new Set(),
nextSyntheticAssistantBlockIndex: -1,
};
const turnId = steeringTurnState?.turnId ?? TurnId.make(yield* randomUUIDv4);
if (steeringTurnState === null) {
const turnState: ClaudeTurnState = {
turnId,
startedAt: yield* nowIso,
items: [],
assistantTextBlocks: new Map(),
assistantTextBlockOrder: [],
capturedProposedPlanKeys: new Set(),
nextSyntheticAssistantBlockIndex: -1,
};
const updatedAt = yield* nowIso;
context.turnState = turnState;
context.session = {
...context.session,
status: "running",
activeTurnId: turnId,
updatedAt,
};
const updatedAt = yield* nowIso;
context.turnState = turnState;
context.session = {
...context.session,
status: "running",
activeTurnId: turnId,
updatedAt,
};
const turnStartedStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "turn.started",
eventId: turnStartedStamp.eventId,
provider: PROVIDER,
createdAt: turnStartedStamp.createdAt,
threadId: context.session.threadId,
turnId,
payload: modelSelection?.model ? { model: modelSelection.model } : {},
providerRefs: {},
});
const turnStartedStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "turn.started",
eventId: turnStartedStamp.eventId,
provider: PROVIDER,
createdAt: turnStartedStamp.createdAt,
threadId: context.session.threadId,
turnId,
payload: modelSelection?.model ? { model: modelSelection.model } : {},
providerRefs: {},
});
}
const message = yield* buildUserMessageEffect(input, {
fileSystem,
@@ -271,7 +271,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "fastMode", value: true },
{ id: "serviceTier", value: "priority" },
]),
runtimeMode: "full-access",
});
@@ -281,7 +281,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
cwd: process.cwd(),
model: "gpt-5.3-codex",
providerInstanceId: ProviderInstanceId.make("codex"),
serviceTier: "fast",
serviceTier: "priority",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
});
@@ -344,7 +344,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
input: "hello",
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
{ id: "serviceTier", value: "priority" },
]),
attachments: [],
}),
@@ -354,7 +354,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
input: "hello",
model: "gpt-5.3-codex",
effort: "high",
serviceTier: "fast",
serviceTier: "priority",
});
}),
);
@@ -398,7 +398,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
"gpt-5.3-codex",
[
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
{ id: "serviceTier", value: "flex" },
],
),
attachments: [],
@@ -409,7 +409,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
input: "hello",
model: "gpt-5.3-codex",
effort: "high",
serviceTier: "fast",
serviceTier: "flex",
});
}).pipe(Effect.provide(customLayer));
});
+10 -11
View File
@@ -37,10 +37,8 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import * as CodexErrors from "effect-codex-app-server/errors";
import * as EffectCodexSchema from "effect-codex-app-server/schema";
import {
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
} from "@t3tools/shared/model";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { getCodexServiceTierOptionValue } from "../../codexModelOptions.ts";
import {
ProviderAdapterRequestError,
@@ -1380,6 +1378,10 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
yield* Effect.suspend(() => stopSessionInternal(existing));
}
const serviceTier =
input.modelSelection?.instanceId === boundInstanceId
? getCodexServiceTierOptionValue(input.modelSelection)
: undefined;
const runtimeInput: CodexSessionRuntimeOptions = {
threadId: input.threadId,
providerInstanceId: boundInstanceId,
@@ -1394,10 +1396,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
...(input.modelSelection?.instanceId === boundInstanceId
? { model: input.modelSelection.model }
: {}),
...(input.modelSelection?.instanceId === boundInstanceId &&
getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode") === true
? { serviceTier: "fast" }
: {}),
...(serviceTier ? { serviceTier } : {}),
};
const sessionScope = yield* Scope.make("sequential");
let sessionScopeTransferred = false;
@@ -1513,9 +1512,9 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
input.modelSelection?.instanceId === boundInstanceId
? getModelSelectionStringOptionValue(input.modelSelection, "reasoningEffort")
: undefined;
const fastMode =
const serviceTier =
input.modelSelection?.instanceId === boundInstanceId
? getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode")
? getCodexServiceTierOptionValue(input.modelSelection)
: undefined;
return yield* session.runtime
.sendTurn({
@@ -1528,7 +1527,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
effort: reasoningEffort as EffectCodexSchema.V2TurnStartParams__ReasoningEffort,
}
: {}),
...(fastMode === true ? { serviceTier: "fast" } : {}),
...(serviceTier ? { serviceTier } : {}),
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),
})
@@ -0,0 +1,104 @@
import { assert, it } from "@effect/vitest";
import { mapCodexModelCapabilities } from "./CodexProvider.ts";
it("maps current Codex model capability fields", () => {
const capabilities = mapCodexModelCapabilities({
additionalSpeedTiers: [],
defaultReasoningEffort: "super-high",
description: "Test model",
displayName: "GPT Test",
hidden: false,
id: "gpt-test",
isDefault: true,
model: "gpt-test",
defaultServiceTier: "flex",
serviceTiers: [
{
id: "priority",
name: "Fast",
description: "Lower latency responses.",
},
{
id: "flex",
name: "Flex",
description: "Lower-cost asynchronous routing.",
},
],
supportedReasoningEfforts: [
{
description: "Maximum reasoning",
reasoningEffort: "super-high",
},
],
});
assert.deepStrictEqual(capabilities.optionDescriptors, [
{
id: "reasoningEffort",
label: "Reasoning",
type: "select",
options: [{ id: "super-high", label: "super-high", isDefault: true }],
currentValue: "super-high",
},
{
id: "serviceTier",
label: "Service Tier",
type: "select",
options: [
{ id: "default", label: "Standard" },
{
id: "priority",
label: "Fast",
description: "Lower latency responses.",
},
{
id: "flex",
label: "Flex",
description: "Lower-cost asynchronous routing.",
isDefault: true,
},
],
currentValue: "flex",
},
]);
});
it("uses standard routing when the catalog has no default service tier", () => {
const capabilities = mapCodexModelCapabilities({
additionalSpeedTiers: ["fast"],
defaultReasoningEffort: "medium",
defaultServiceTier: null,
description: "Test model",
displayName: "GPT Test",
hidden: false,
id: "gpt-test",
isDefault: true,
model: "gpt-test",
serviceTiers: [
{
id: "priority",
name: "Fast",
description: "1.5x speed, increased usage",
},
],
supportedReasoningEfforts: [],
});
assert.deepStrictEqual(capabilities.optionDescriptors, [
{
id: "serviceTier",
label: "Service Tier",
type: "select",
options: [
{ id: "default", label: "Standard", isDefault: true },
{
id: "priority",
label: "Fast",
description: "1.5x speed, increased usage",
},
],
currentValue: "default",
},
]);
});
@@ -17,6 +17,7 @@ import type {
ServerProvider,
ServerProviderState,
ModelCapabilities,
ProviderOptionDescriptor,
ServerProviderModel,
ServerProviderSkill,
} from "@t3tools/contracts";
@@ -44,7 +45,7 @@ export interface CodexAppServerProviderSnapshot {
readonly skills: ReadonlyArray<ServerProviderSkill>;
}
const REASONING_EFFORT_LABELS: Record<CodexSchema.V2ModelListResponse__ReasoningEffort, string> = {
const REASONING_EFFORT_LABELS: Readonly<Record<string, string>> = {
none: "None",
minimal: "Minimal",
low: "Low",
@@ -53,6 +54,12 @@ const REASONING_EFFORT_LABELS: Record<CodexSchema.V2ModelListResponse__Reasoning
xhigh: "Extra High",
};
const DEFAULT_SERVICE_TIER_ID = "default";
function reasoningEffortLabel(reasoningEffort: string): string {
return REASONING_EFFORT_LABELS[reasoningEffort] ?? reasoningEffort;
}
function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["account"]) {
if (!account) return undefined;
if (account.type === "apiKey") return "OpenAI API Key";
@@ -93,46 +100,71 @@ function codexAccountEmail(account: CodexSchema.V2GetAccountResponse["account"])
return account.email;
}
function mapCodexModelCapabilities(
export function mapCodexModelCapabilities(
model: CodexSchema.V2ModelListResponse__Model,
): ModelCapabilities {
const reasoningOptions = model.supportedReasoningEfforts.map(({ reasoningEffort }) =>
reasoningEffort === model.defaultReasoningEffort
? {
id: reasoningEffort,
label: REASONING_EFFORT_LABELS[reasoningEffort],
label: reasoningEffortLabel(reasoningEffort),
isDefault: true,
}
: {
id: reasoningEffort,
label: REASONING_EFFORT_LABELS[reasoningEffort],
label: reasoningEffortLabel(reasoningEffort),
},
);
const defaultReasoning = reasoningOptions.find((option) => option.isDefault)?.id;
const supportsFastMode = (model.additionalSpeedTiers ?? []).includes("fast");
const serviceTiers =
model.serviceTiers && model.serviceTiers.length > 0
? model.serviceTiers
: (model.additionalSpeedTiers ?? []).map((id) => ({
id,
name: id === "fast" ? "Fast" : id,
description: "",
}));
const catalogDefaultServiceTier = serviceTiers.some(
(tier) => tier.id === model.defaultServiceTier,
)
? model.defaultServiceTier
: null;
const defaultServiceTier = catalogDefaultServiceTier ?? DEFAULT_SERVICE_TIER_ID;
const optionDescriptors: ProviderOptionDescriptor[] = [];
if (reasoningOptions.length > 0) {
optionDescriptors.push({
id: "reasoningEffort",
label: "Reasoning",
type: "select",
options: reasoningOptions,
...(defaultReasoning ? { currentValue: defaultReasoning } : {}),
});
}
if (serviceTiers.length > 0) {
optionDescriptors.push({
id: "serviceTier",
label: "Service Tier",
type: "select",
options: [
{
id: DEFAULT_SERVICE_TIER_ID,
label: "Standard",
...(defaultServiceTier === DEFAULT_SERVICE_TIER_ID ? { isDefault: true } : {}),
},
...serviceTiers.map((tier) => ({
id: tier.id,
label: tier.name,
...(tier.description ? { description: tier.description } : {}),
...(defaultServiceTier === tier.id ? { isDefault: true } : {}),
})),
],
currentValue: defaultServiceTier,
});
}
return createModelCapabilities({
optionDescriptors: [
...(reasoningOptions.length > 0
? [
{
id: "reasoningEffort",
label: "Reasoning",
type: "select" as const,
options: reasoningOptions,
...(defaultReasoning ? { currentValue: defaultReasoning } : {}),
},
]
: []),
...(supportsFastMode
? [
{
id: "fastMode",
label: "Fast Mode",
type: "boolean" as const,
},
]
: []),
],
optionDescriptors,
});
}
@@ -13,6 +13,7 @@ import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { createModelSelection } from "@t3tools/shared/model";
import {
@@ -232,6 +233,82 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
}),
);
it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const settings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-steer-thread");
// Keep the first prompt in flight long enough for the steer to land.
const wrapperPath = yield* Effect.promise(() =>
makeMockAgentWrapper({ T3_ACP_PROMPT_DELAY_MS: "1500" }),
);
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
const runtimeEventsFiber = yield* adapter.streamEvents.pipe(
Stream.filter((event) => event.threadId === threadId),
Stream.takeUntil((event) => event.type === "turn.completed"),
Stream.runCollect,
Effect.forkChild,
);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
});
const firstTurnFiber = yield* adapter
.sendTurn({
threadId,
input: "run 5 commands",
attachments: [],
})
.pipe(Effect.forkChild);
// Poll until the first prompt is in flight — sendTurn binds the active
// turn id before prompting. The mock agent runs on the real clock, so
// each TestClock.adjust just provides the scheduler hops for its stdio
// responses to land.
yield* Effect.gen(function* () {
for (let attempt = 0; attempt < 200; attempt += 1) {
const sessions = yield* adapter.listSessions();
const session = sessions.find((entry) => entry.threadId === threadId);
if (session?.activeTurnId !== undefined) {
return;
}
yield* TestClock.adjust("10 millis");
}
throw new Error("Timed out waiting for the first prompt to be in flight.");
});
// Steer: a second sendTurn while the first prompt is still in flight
// continues the same turn.
const steeredTurn = yield* adapter.sendTurn({
threadId,
input: "actually run 15",
attachments: [],
});
const firstTurn = yield* Fiber.join(firstTurnFiber);
assert.equal(String(steeredTurn.turnId), String(firstTurn.turnId));
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
const turnStartedEvents = runtimeEvents.filter((event) => event.type === "turn.started");
const turnCompletedEvents = runtimeEvents.filter((event) => event.type === "turn.completed");
// One turn boundary for the whole run: the superseded first prompt
// resolving must not settle the merged turn.
assert.equal(turnStartedEvents.length, 1);
assert.equal(String(turnStartedEvents[0]?.turnId), String(firstTurn.turnId));
assert.equal(turnCompletedEvents.length, 1);
assert.equal(String(turnCompletedEvents[0]?.turnId), String(firstTurn.turnId));
yield* adapter.stopSession(threadId);
}),
);
it.effect("closes the ACP child process when a session stops", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
+142 -106
View File
@@ -132,6 +132,10 @@ interface CursorSessionContext {
readonly turns: Array<{ id: TurnId; items: Array<unknown> }>;
lastPlanFingerprint: string | undefined;
activeTurnId: TurnId | undefined;
/** Number of sendTurn prompts currently in flight or being prepared.
* >0 means a turn is actively running, so a new sendTurn is a steer that
* continues it, and only the last remaining prompt settles the turn. */
promptsInFlight: number;
stopped: boolean;
}
@@ -754,6 +758,7 @@ export function makeCursorAdapter(
turns: [],
lastPlanFingerprint: undefined,
activeTurnId: undefined,
promptsInFlight: 0,
stopped: false,
};
@@ -882,121 +887,152 @@ export function makeCursorAdapter(
const sendTurn: CursorAdapterShape["sendTurn"] = (input) =>
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
const turnId = TurnId.make(yield* randomUUIDv4);
const turnModelSelection =
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
const model = turnModelSelection?.model ?? ctx.session.model;
const resolvedModel = resolveCursorAcpBaseModelId(model);
yield* applyRequestedSessionConfiguration({
runtime: ctx.acp,
runtimeMode: ctx.session.runtimeMode,
interactionMode: input.interactionMode,
modelSelection:
model === undefined
? undefined
: {
model,
options: turnModelSelection?.options,
},
mapError: ({ cause, method }) =>
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
});
ctx.activeTurnId = turnId;
ctx.lastPlanFingerprint = undefined;
ctx.session = {
...ctx.session,
activeTurnId: turnId,
updatedAt: yield* nowIso,
};
// A sendTurn while a prompt is in flight is a steer: the agent folds
// the new prompt into the ongoing work, so the active turn id is
// reused instead of opening a new turn.
const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;
const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);
// Count this prompt immediately so a superseded in-flight prompt
// resolving from here on does not settle the turn; the matching
// decrement is the `ensuring` below.
ctx.promptsInFlight += 1;
yield* offerRuntimeEvent({
type: "turn.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: { model: resolvedModel },
});
return yield* Effect.gen(function* () {
const turnModelSelection =
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
const model = turnModelSelection?.model ?? ctx.session.model;
const resolvedModel = resolveCursorAcpBaseModelId(model);
yield* applyRequestedSessionConfiguration({
runtime: ctx.acp,
runtimeMode: ctx.session.runtimeMode,
interactionMode: input.interactionMode,
modelSelection:
model === undefined
? undefined
: {
model,
options: turnModelSelection?.options,
},
mapError: ({ cause, method }) =>
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
});
ctx.activeTurnId = turnId;
if (steeringTurnId === undefined) {
ctx.lastPlanFingerprint = undefined;
}
ctx.session = {
...ctx.session,
activeTurnId: turnId,
updatedAt: yield* nowIso,
};
const promptParts: Array<EffectAcpSchema.ContentBlock> = [];
if (input.input?.trim()) {
promptParts.push({ type: "text", text: input.input.trim() });
}
if (input.attachments && input.attachments.length > 0) {
for (const attachment of input.attachments) {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
if (!attachmentPath) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: `Invalid attachment id '${attachment.id}'.`,
});
}
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: cause.message,
cause,
}),
),
);
promptParts.push({
type: "image",
data: Buffer.from(bytes).toString("base64"),
mimeType: attachment.mimeType,
if (steeringTurnId === undefined) {
yield* offerRuntimeEvent({
type: "turn.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: { model: resolvedModel },
});
}
}
if (promptParts.length === 0) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "sendTurn",
issue: "Turn requires non-empty text or attachments.",
});
}
const promptParts: Array<EffectAcpSchema.ContentBlock> = [];
if (input.input?.trim()) {
promptParts.push({ type: "text", text: input.input.trim() });
}
if (input.attachments && input.attachments.length > 0) {
for (const attachment of input.attachments) {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
if (!attachmentPath) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: `Invalid attachment id '${attachment.id}'.`,
});
}
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: cause.message,
cause,
}),
),
);
promptParts.push({
type: "image",
data: Buffer.from(bytes).toString("base64"),
mimeType: attachment.mimeType,
});
}
}
const result = yield* ctx.acp
.prompt({
prompt: promptParts,
})
.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
),
);
if (promptParts.length === 0) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "sendTurn",
issue: "Turn requires non-empty text or attachments.",
});
}
ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] });
ctx.session = {
...ctx.session,
activeTurnId: turnId,
updatedAt: yield* nowIso,
model: resolvedModel,
};
const result = yield* ctx.acp
.prompt({
prompt: promptParts,
})
.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
),
);
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: {
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
stopReason: result.stopReason ?? null,
},
});
const turnRecord = ctx.turns.find((turn) => turn.id === turnId);
if (turnRecord) {
turnRecord.items.push({ prompt: promptParts, result });
} else {
ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] });
}
ctx.session = {
...ctx.session,
activeTurnId: turnId,
updatedAt: yield* nowIso,
model: resolvedModel,
};
return {
threadId: input.threadId,
turnId,
resumeCursor: ctx.session.resumeCursor,
};
// Only the last remaining prompt settles the turn — a steer-
// superseded prompt resolving (usually cancelled) while another is
// in flight or pending must leave the merged turn running.
if (ctx.promptsInFlight === 1) {
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: {
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
stopReason: result.stopReason ?? null,
},
});
}
return {
threadId: input.threadId,
turnId,
resumeCursor: ctx.session.resumeCursor,
};
}).pipe(
Effect.ensuring(
Effect.sync(() => {
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
}),
),
);
});
const interruptTurn: CursorAdapterShape["interruptTurn"] = (threadId) =>
+190 -136
View File
@@ -107,6 +107,10 @@ interface GrokSessionContext {
turns: Array<{ id: TurnId; items: Array<unknown> }>;
lastPlanFingerprint: string | undefined;
activeTurnId: TurnId | undefined;
/** Number of sendTurn prompts currently in flight or being prepared.
* >0 means a turn is actively running, so a new sendTurn is a steer that
* continues it, and only the last remaining prompt settles the turn. */
promptsInFlight: number;
currentModelId: string | undefined;
stopped: boolean;
}
@@ -555,6 +559,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
turns: [],
lastPlanFingerprint: undefined,
activeTurnId: undefined,
promptsInFlight: 0,
currentModelId: boundModelId,
stopped: false,
};
@@ -664,150 +669,199 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
input.threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
const turnId = TurnId.make(yield* randomUUIDv4);
const turnModelSelection =
input.modelSelection?.instanceId === boundInstanceId
? input.modelSelection
: undefined;
const requestedTurnModelId = turnModelSelection?.model
? resolveGrokAcpBaseModelId(turnModelSelection.model)
: undefined;
const currentModelId = yield* applyGrokAcpModelSelection({
runtime: ctx.acp,
currentModelId: ctx.currentModelId,
requestedModelId: requestedTurnModelId,
mapError: (cause) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
});
// A sendTurn while a prompt is in flight is a steer: the agent
// folds the new prompt into the ongoing work, so the active turn
// id is reused instead of opening a new turn.
const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;
const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);
// Count this prompt immediately so a superseded in-flight prompt
// resolving from here on does not settle the turn; decremented on
// preparation failure here, and after the prompt below otherwise.
ctx.promptsInFlight += 1;
const text = input.input?.trim();
const imagePromptParts = yield* Effect.forEach(input.attachments ?? [], (attachment) =>
Effect.gen(function* () {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
if (!attachmentPath) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: `Invalid attachment id '${attachment.id}'.`,
});
}
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
return yield* Effect.gen(function* () {
const turnModelSelection =
input.modelSelection?.instanceId === boundInstanceId
? input.modelSelection
: undefined;
const requestedTurnModelId = turnModelSelection?.model
? resolveGrokAcpBaseModelId(turnModelSelection.model)
: undefined;
const currentModelId = yield* applyGrokAcpModelSelection({
runtime: ctx.acp,
currentModelId: ctx.currentModelId,
requestedModelId: requestedTurnModelId,
mapError: (cause) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
});
const text = input.input?.trim();
const imagePromptParts = yield* Effect.forEach(
input.attachments ?? [],
(attachment) =>
Effect.gen(function* () {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
if (!attachmentPath) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: cause.message,
cause,
}),
),
);
return {
type: "image",
data: Buffer.from(bytes).toString("base64"),
mimeType: attachment.mimeType,
} satisfies EffectAcpSchema.ContentBlock;
}),
detail: `Invalid attachment id '${attachment.id}'.`,
});
}
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: cause.message,
cause,
}),
),
);
return {
type: "image",
data: Buffer.from(bytes).toString("base64"),
mimeType: attachment.mimeType,
} satisfies EffectAcpSchema.ContentBlock;
}),
);
const promptParts: Array<EffectAcpSchema.ContentBlock> = [
...(text ? [{ type: "text" as const, text }] : []),
...imagePromptParts,
];
if (promptParts.length === 0) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "sendTurn",
issue: "Turn requires non-empty text or attachments.",
});
}
ctx.currentModelId = currentModelId;
const displayModel = currentModelId
? resolveGrokAcpBaseModelId(currentModelId)
: undefined;
ctx.activeTurnId = turnId;
if (steeringTurnId === undefined) {
ctx.lastPlanFingerprint = undefined;
}
ctx.session = {
...ctx.session,
activeTurnId: turnId,
updatedAt: yield* nowIso,
...(displayModel ? { model: displayModel } : {}),
};
if (steeringTurnId === undefined) {
yield* offerRuntimeEvent({
type: "turn.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: displayModel ? { model: displayModel } : {},
});
}
return {
acp: ctx.acp,
acpSessionId: ctx.acpSessionId,
displayModel,
promptParts,
turnId,
};
}).pipe(
Effect.tapCause(() =>
Effect.sync(() => {
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
}),
),
);
const promptParts: Array<EffectAcpSchema.ContentBlock> = [
...(text ? [{ type: "text" as const, text }] : []),
...imagePromptParts,
];
if (promptParts.length === 0) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "sendTurn",
issue: "Turn requires non-empty text or attachments.",
});
}
ctx.currentModelId = currentModelId;
const displayModel = currentModelId
? resolveGrokAcpBaseModelId(currentModelId)
: undefined;
ctx.activeTurnId = turnId;
ctx.lastPlanFingerprint = undefined;
ctx.session = {
...ctx.session,
activeTurnId: turnId,
updatedAt: yield* nowIso,
...(displayModel ? { model: displayModel } : {}),
};
yield* offerRuntimeEvent({
type: "turn.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: displayModel ? { model: displayModel } : {},
});
return {
acp: ctx.acp,
acpSessionId: ctx.acpSessionId,
displayModel,
promptParts,
turnId,
};
}),
);
const result = yield* prepared.acp
.prompt({
prompt: prepared.promptParts,
})
.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
),
return yield* Effect.gen(function* () {
const result = yield* prepared.acp
.prompt({
prompt: prepared.promptParts,
})
.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
),
);
return yield* withThreadLock(
input.threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
if (ctx.acpSessionId !== prepared.acpSessionId) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: "Grok session changed before the turn completed.",
});
}
const existingTurnRecord = ctx.turns.find((turn) => turn.id === prepared.turnId);
ctx.turns = existingTurnRecord
? ctx.turns.map((turn) =>
turn.id === prepared.turnId
? {
...turn,
items: [...turn.items, { prompt: prepared.promptParts, result }],
}
: turn,
)
: [
...ctx.turns,
{ id: prepared.turnId, items: [{ prompt: prepared.promptParts, result }] },
];
ctx.session = {
...ctx.session,
activeTurnId: prepared.turnId,
updatedAt: yield* nowIso,
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
};
// Only the last remaining prompt settles the turn — a steer-
// superseded prompt resolving (usually cancelled) while another
// is in flight or pending must leave the merged turn running.
if (ctx.promptsInFlight === 1) {
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: prepared.turnId,
payload: {
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
stopReason: result.stopReason ?? null,
},
});
}
return {
threadId: input.threadId,
turnId: prepared.turnId,
resumeCursor: ctx.session.resumeCursor,
};
}),
);
return yield* withThreadLock(
input.threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
if (ctx.acpSessionId !== prepared.acpSessionId) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: "Grok session changed before the turn completed.",
});
}
ctx.turns = [
...ctx.turns,
{ id: prepared.turnId, items: [{ prompt: prepared.promptParts, result }] },
];
ctx.session = {
...ctx.session,
activeTurnId: prepared.turnId,
updatedAt: yield* nowIso,
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
};
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: prepared.turnId,
payload: {
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
stopReason: result.stopReason ?? null,
},
});
return {
threadId: input.threadId,
turnId: prepared.turnId,
resumeCursor: ctx.session.resumeCursor,
};
}),
}).pipe(
Effect.ensuring(
Effect.sync(() => {
const liveCtx = sessions.get(input.threadId);
if (liveCtx) {
liveCtx.promptsInFlight = Math.max(0, liveCtx.promptsInFlight - 1);
}
}),
),
);
});
@@ -395,6 +395,85 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
}),
);
it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const threadId = asThreadId("thread-steer");
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
threadId,
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId,
input: "run 5 commands",
modelSelection: {
instanceId: ProviderInstanceId.make("opencode"),
model: "openai/gpt-5",
},
});
// Steer: OpenCode queues the prompt into the busy session, so the
// active turn id is reused instead of opening a new turn.
const steeredTurn = yield* adapter.sendTurn({
threadId,
input: "actually run 15",
modelSelection: {
instanceId: ProviderInstanceId.make("opencode"),
model: "openai/gpt-5",
},
});
assert.equal(String(steeredTurn.turnId), String(turn.turnId));
const sessions = yield* adapter.listSessions();
const session = sessions.find((entry) => entry.threadId === threadId);
assert.equal(session?.status, "running");
assert.equal(String(session?.activeTurnId), String(turn.turnId));
assert.equal(runtimeMock.state.promptCalls.length, 2);
}),
);
it.effect("keeps the running turn when a steer prompt fails", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const threadId = asThreadId("thread-steer-failure");
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
threadId,
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId,
input: "run 5 commands",
modelSelection: {
instanceId: ProviderInstanceId.make("opencode"),
model: "openai/gpt-5",
},
});
runtimeMock.state.promptAsyncError = new Error("steer failed");
const error = yield* adapter
.sendTurn({
threadId,
input: "actually run 15",
modelSelection: {
instanceId: ProviderInstanceId.make("opencode"),
model: "openai/gpt-5",
},
})
.pipe(Effect.flip);
// The original turn keeps running — only the steer prompt failed.
assert.equal(error._tag, "ProviderAdapterRequestError");
const sessions = yield* adapter.listSessions();
const session = sessions.find((entry) => entry.threadId === threadId);
assert.equal(session?.status, "running");
assert.equal(String(session?.activeTurnId), String(turn.turnId));
}),
);
it.effect("passes agent and variant options for the adapter's bound custom instance id", () => {
const instanceId = ProviderInstanceId.make("opencode_zen");
const adapterLayer = Layer.effect(
@@ -1151,7 +1151,11 @@ export function makeOpenCodeAdapter(
const sendTurn: OpenCodeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {
const context = ensureSessionContext(sessions, input.threadId);
const turnId = TurnId.make(`opencode-turn-${yield* randomUUIDv4}`);
// A sendTurn while a turn is active is a steer: OpenCode queues the
// prompt into the busy session and the work continues as one turn, so
// the active turn id is reused instead of opening a new turn.
const steeringTurnId = context.activeTurnId;
const turnId = steeringTurnId ?? TurnId.make(`opencode-turn-${yield* randomUUIDv4}`);
const modelSelection =
input.modelSelection ??
(context.session.model
@@ -1206,14 +1210,16 @@ export function makeOpenCodeAdapter(
{ clearLastError: true },
);
yield* emit({
...(yield* buildEventBase({ threadId: input.threadId, turnId })),
type: "turn.started",
payload: {
model: modelSelection?.model ?? context.session.model,
...(variant ? { effort: variant } : {}),
},
});
if (steeringTurnId === undefined) {
yield* emit({
...(yield* buildEventBase({ threadId: input.threadId, turnId })),
type: "turn.started",
payload: {
model: modelSelection?.model ?? context.session.model,
...(variant ? { effort: variant } : {}),
},
});
}
yield* runOpenCodeSdk("session.promptAsync", () =>
context.client.session.promptAsync({
@@ -1225,35 +1231,38 @@ export function makeOpenCodeAdapter(
}),
).pipe(
Effect.mapError(toRequestError),
// On failure: clear active-turn state, flip the session back to ready
// with lastError set, emit turn.aborted, then let the typed error
// propagate. We don't need to rebuild the error here — `toRequestError`
// already produced the right shape.
// On failure of a fresh turn: clear active-turn state, flip the
// session back to ready with lastError set, emit turn.aborted, then
// let the typed error propagate. We don't need to rebuild the error
// here — `toRequestError` already produced the right shape. A failed
// steer leaves the still-running original turn untouched.
Effect.tapError((requestError) =>
Effect.gen(function* () {
context.activeTurnId = undefined;
context.activeAgent = undefined;
context.activeVariant = undefined;
yield* updateProviderSession(
context,
{
status: "ready",
model: modelSelection?.model ?? context.session.model,
lastError: requestError.detail,
},
{ clearActiveTurnId: true },
);
yield* emit({
...(yield* buildEventBase({
threadId: input.threadId,
turnId,
})),
type: "turn.aborted",
payload: {
reason: requestError.detail,
},
});
}),
steeringTurnId !== undefined
? Effect.void
: Effect.gen(function* () {
context.activeTurnId = undefined;
context.activeAgent = undefined;
context.activeVariant = undefined;
yield* updateProviderSession(
context,
{
status: "ready",
model: modelSelection?.model ?? context.session.model,
lastError: requestError.detail,
},
{ clearActiveTurnId: true },
);
yield* emit({
...(yield* buildEventBase({
threadId: input.threadId,
turnId,
})),
type: "turn.aborted",
payload: {
reason: requestError.detail,
},
});
}),
),
);
@@ -594,6 +594,77 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
]);
});
it.effect("does not run provider probes during layer construction", () =>
Effect.gen(function* () {
const codexDriver = ProviderDriverKind.make("codex");
const codexInstanceId = ProviderInstanceId.make("codex");
const initialProvider = {
instanceId: codexInstanceId,
driver: codexDriver,
status: "warning",
enabled: true,
installed: false,
auth: { status: "unknown" },
checkedAt: "2026-06-10T00:00:00.000Z",
version: null,
message: "Checking Codex provider status.",
models: [],
slashCommands: [],
skills: [],
} as const satisfies ServerProvider;
const refreshCalls = yield* Ref.make(0);
const instance = {
instanceId: codexInstanceId,
driverKind: codexDriver,
continuationIdentity: {
driverKind: codexDriver,
continuationKey: "codex:instance:codex",
},
displayName: undefined,
enabled: true,
snapshot: {
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
provider: codexDriver,
packageName: null,
}),
getSnapshot: Effect.succeed(initialProvider),
refresh: Ref.update(refreshCalls, (count) => count + 1).pipe(
Effect.andThen(Effect.never),
),
streamChanges: Stream.empty,
},
adapter: {} as ProviderInstance["adapter"],
textGeneration: {} as ProviderInstance["textGeneration"],
} satisfies ProviderInstance;
const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {
getInstance: (instanceId) =>
Effect.succeed(instanceId === codexInstanceId ? instance : undefined),
listInstances: Effect.succeed([instance]),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.empty,
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), PubSub.subscribe),
});
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const runtimeServices = yield* Layer.build(
ProviderRegistryLive.pipe(
Layer.provideMerge(instanceRegistryLayer),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-background-refresh-",
}),
),
Layer.provideMerge(NodeServices.layer),
),
).pipe(Scope.provide(scope));
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry;
assert.deepStrictEqual(yield* registry.getProviders, [initialProvider]);
assert.strictEqual(yield* Ref.get(refreshCalls), 0);
}).pipe(Effect.provide(runtimeServices));
}),
);
it("persists merged provider snapshots for the providers that were refreshed", () => {
const previousProviders = [
{
@@ -1042,7 +1113,17 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry;
const providers = yield* registry.getProviders;
let providers = yield* registry.getProviders;
for (
let attempts = 0;
attempts < 50 &&
providers.find((provider) => provider.instanceId === "codex_personal")?.status !==
"error";
attempts += 1
) {
yield* Effect.yieldNow;
providers = yield* registry.getProviders;
}
const codexPersonal = providers.find(
(provider) => provider.instanceId === "codex_personal",
);
@@ -1072,9 +1153,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
// instance and rebuild it so a fresh probe runs with the new binary.
// This test drives the real settings stream → registry reconcile →
// aggregator sync pipeline and asserts that `getProviders` reflects
// the new probe's outcome. If `syncLiveSources` stops awaiting the
// rebuilt instance's refresh (previous bug mode), the aggregator
// keeps the old snapshot and this test fails.
// the new background probe's outcome.
//
it.effect("re-probes when settings change the codex binaryPath", () =>
Effect.gen(function* () {
@@ -1124,7 +1203,18 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
// the two probe runs is `checkedAt` — each probe stamps a
// fresh DateTime, so we capture it and assert it advances
// after the settings mutation.
const initialProviders = yield* registry.getProviders;
let initialProviders = yield* registry.getProviders;
for (
let attempts = 0;
attempts < 50 &&
initialProviders.find((provider) => provider.instanceId === "codex")?.status !==
"error";
attempts += 1
) {
yield* TestClock.adjust("10 millis");
yield* Effect.yieldNow;
initialProviders = yield* registry.getProviders;
}
const initialCodex = initialProviders.find(
(provider) => provider.instanceId === "codex",
);
@@ -1144,8 +1234,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
// envelope changed because `binaryPath` differs → `entryEqual`
// is false). The registry's `Stream.runForEach(
// instanceRegistry.streamChanges, () => syncLiveSources)`
// fires `syncLiveSources`, which subscribes + awaits a fresh
// refresh on the rebuilt instance.
// fires `syncLiveSources`, which subscribes and launches a fresh
// background refresh on the rebuilt instance.
yield* serverSettings.updateSettings({
providers: {
codex: { enabled: true, binaryPath: secondMissing },
@@ -1158,7 +1248,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
for (let attempts = 0; attempts < 60; attempts += 1) {
const providers = yield* registry.getProviders;
const codex = providers.find((provider) => provider.instanceId === "codex");
if (codex !== undefined && codex.checkedAt !== initialCheckedAt) {
if (
codex !== undefined &&
codex.status === "error" &&
codex.checkedAt !== initialCheckedAt
) {
return providers;
}
yield* TestClock.adjust("50 millis");
@@ -492,16 +492,15 @@ export const ProviderRegistryLive = Layer.effect(
* - subscribe to each newly-added or rebuilt instance's
* `streamChanges` (so periodic + enrichment refreshes land in
* `providersRef`);
* - force-refresh each newly-added/rebuilt instance and feed the
* result directly into `providersRef`, bypassing the PubSub
* attachment race that otherwise drops the initial probe;
* - read each newly-added/rebuilt instance's current snapshot after
* subscribing, closing the race with its independently-running
* background startup probe;
* - prune `providersRef` of instances that no longer exist.
*
* Initial refreshes are awaited in parallel rather than forked, so
* callers (layer build; `streamChanges` watcher) see fully-probed
* state on return. This matters for layer build in particular:
* consumers reading `getProviders` immediately after layer build
* expect the probe to have already landed.
* Provider refreshes are owned by each managed provider and never run
* on this layer's construction path. Consumers see cached or pending
* snapshots immediately, then receive live probe results through the
* already-attached change stream.
*
* Per-instance subscription fibers are not tracked explicitly. When
* a rebuilt instance's old child scope closes, its PubSub shuts
@@ -543,27 +542,31 @@ export const ProviderRegistryLive = Layer.effect(
}
// Fork long-lived subscriptions to each new/rebuilt instance's
// change stream BEFORE kicking off refreshes — if the driver's
// own initial probe (line 140 in `makeManagedServerProvider`)
// wins the refreshSemaphore race, its PubSub publish must land
// in an active subscriber or the result is dropped.
// change stream before reading its current snapshot. If the
// driver's own initial probe finishes during this sync, either
// the current read or the active subscriber observes the result.
for (const [, instance] of newlyAdded) {
const source = buildSnapshotSource(instance);
yield* Stream.runForEach(source.streamChanges, (provider) =>
correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),
).pipe(Effect.forkScoped);
}
yield* Effect.yieldNow;
// Force-refresh every new/rebuilt instance in parallel and wait
// for them all to complete. The refresh's result is piped
// directly into `syncProvider`, so `providersRef` is populated
// deterministically by the time this block returns — regardless
// of PubSub subscription timing. Failures are logged and
// swallowed so one bad driver can't wedge the whole registry.
// Snapshot current state without starting a probe. Managed providers
// launch their startup refresh independently, so this closes the
// subscription race without putting external work on the registry
// or HTTP server construction path.
yield* Effect.forEach(
newlyAdded,
([, instance]) =>
refreshOneSource(buildSnapshotSource(instance)).pipe(Effect.ignoreCause({ log: true })),
Effect.gen(function* () {
const source = buildSnapshotSource(instance);
const provider = yield* source.getSnapshot;
yield* correlateSnapshotWithSource(source, provider).pipe(
Effect.flatMap(syncProvider),
);
}).pipe(Effect.ignoreCause({ log: true })),
{ concurrency: "unbounded", discard: true },
);
yield* upsertProviders(unavailableProviders, {
@@ -654,9 +657,9 @@ export const ProviderRegistryLive = Layer.effect(
// was dropped, which made any settings change that replaced an
// instance never propagate to the aggregator's `providersRef`.)
const instanceChanges = yield* instanceRegistry.subscribeChanges;
// Initial sync: subscribe + kick off refreshes for every instance
// present at boot. Run synchronously so consumers pulling immediately
// after the layer build see the correct aggregator state.
// Initial sync attaches subscriptions and snapshots current state for
// every instance present at boot. Provider probes are already running in
// their managed background fibers and never block this layer.
yield* syncLiveSources;
// React to registry mutations — instance added / removed / rebuilt.
// `Stream.fromSubscription` builds a stream over the pre-acquired
@@ -129,6 +129,7 @@ describe("makeManagedServerProvider", () => {
Effect.forkChild,
);
yield* Effect.yieldNow;
assert.strictEqual(yield* Ref.get(checkCalls), 1);
yield* Deferred.succeed(releaseCheck, undefined);
@@ -152,11 +152,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
return {
maintenanceCapabilities: input.maintenanceCapabilities,
getSnapshot: input.getSettings.pipe(
Effect.flatMap(applySnapshot),
Effect.tapError(Effect.logError),
Effect.orDie,
),
getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
@@ -32,7 +32,7 @@ function makeFakeCodexBinary(
exitCode?: number;
stderr?: string;
requireImage?: boolean;
requireFastServiceTier?: boolean;
requireServiceTier?: string;
requireReasoningEffort?: string;
forbidReasoningEffort?: boolean;
stdinMustContain?: string;
@@ -52,7 +52,7 @@ function makeFakeCodexBinary(
"#!/bin/sh",
'output_path=""',
'seen_image="0"',
'seen_fast_service_tier="0"',
'seen_service_tier=""',
'seen_reasoning_effort=""',
"while [ $# -gt 0 ]; do",
' if [ "$1" = "--image" ]; then',
@@ -65,9 +65,11 @@ function makeFakeCodexBinary(
" fi",
' if [ "$1" = "--config" ]; then',
" shift",
' if [ "$1" = "service_tier=\\"fast\\"" ]; then',
' seen_fast_service_tier="1"',
" fi",
' case "$1" in',
" service_tier=*)",
' seen_service_tier="$1"',
" ;;",
" esac",
' case "$1" in',
" model_reasoning_effort=*)",
' seen_reasoning_effort="$1"',
@@ -93,10 +95,10 @@ function makeFakeCodexBinary(
"fi",
]
: []),
...(input.requireFastServiceTier
...(input.requireServiceTier
? [
'if [ "$seen_fast_service_tier" != "1" ]; then',
' printf "%s\\n" "missing fast service tier config" >&2',
`if [ "$seen_service_tier" != "service_tier=\\"${input.requireServiceTier}\\"" ]; then`,
' printf "%s\\n" "unexpected service tier config: $seen_service_tier" >&2',
` exit 5`,
"fi",
]
@@ -161,7 +163,7 @@ function withFakeCodexEnv<A, E, R>(
exitCode?: number;
stderr?: string;
requireImage?: boolean;
requireFastServiceTier?: boolean;
requireServiceTier?: string;
requireReasoningEffort?: string;
forbidReasoningEffort?: boolean;
stdinMustContain?: string;
@@ -209,7 +211,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
);
it.effect(
"forwards codex fast mode and non-default reasoning effort into codex exec config",
"forwards codex service tier and non-default reasoning effort into codex exec config",
() =>
withFakeCodexEnv(
{
@@ -217,7 +219,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
subject: "Add important change",
body: "",
}),
requireFastServiceTier: true,
requireServiceTier: "priority",
requireReasoningEffort: "xhigh",
stdinMustNotContain: "branch must be a short semantic git branch fragment",
},
@@ -229,7 +231,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
{ id: "reasoningEffort", value: "xhigh" },
{ id: "fastMode", value: true },
{ id: "serviceTier", value: "priority" },
]),
}),
),
@@ -32,10 +32,8 @@ import {
sanitizeThreadTitle,
toJsonSchemaObject,
} from "./TextGenerationUtils.ts";
import {
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
} from "@t3tools/shared/model";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { getCodexServiceTierOptionValue } from "../codexModelOptions.ts";
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
@@ -181,6 +179,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
const reasoningEffort =
getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
const serviceTier = getCodexServiceTierOptionValue(modelSelection);
const command = ChildProcess.make(
codexConfig.binaryPath || "codex",
[
@@ -193,9 +192,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
modelSelection.model,
"--config",
`model_reasoning_effort="${reasoningEffort}"`,
...(getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true
? ["--config", `service_tier="fast"`]
: []),
...(serviceTier ? ["--config", `service_tier="${serviceTier}"`] : []),
"--output-schema",
schemaPath,
"--output-last-message",
+14
View File
@@ -68,6 +68,17 @@ export interface GitStatusDetails {
aheadOfDefaultCount: number;
}
export interface GitRemoteStatusDetails {
isRepo: boolean;
isDefaultBranch: boolean;
branch: string | null;
upstreamRef: string | null;
hasUpstream: boolean;
aheadCount: number;
behindCount: number;
aheadOfDefaultCount: number;
}
export interface GitPreparedCommitContext {
stagedSummary: string;
stagedPatch: string;
@@ -162,6 +173,9 @@ export interface GitVcsDriverShape {
readonly status: (input: VcsStatusInput) => Effect.Effect<VcsStatusResult, GitCommandError>;
readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
readonly statusDetailsRemote: (
cwd: string,
) => Effect.Effect<GitRemoteStatusDetails, GitCommandError>;
readonly prepareCommitContext: (
cwd: string,
filePaths?: readonly string[],
@@ -155,6 +155,67 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
}),
);
it.effect("reports remote divergence without reading working-tree details", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
yield* git(remote, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", remote]);
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
yield* git(cwd, ["checkout", "-b", "feature/remote-status"]);
yield* writeTextFile(cwd, "feature.txt", "feature\n");
yield* git(cwd, ["add", "feature.txt"]);
yield* git(cwd, ["commit", "-m", "feature commit"]);
yield* git(cwd, ["push", "-u", "origin", "feature/remote-status"]);
yield* writeTextFile(cwd, "untracked.txt", "local-only\n");
const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetailsRemote(cwd);
assert.equal(status.isRepo, true);
assert.equal(status.branch, "feature/remote-status");
assert.equal(status.hasUpstream, true);
assert.equal(status.aheadCount, 0);
assert.equal(status.behindCount, 0);
assert.equal(status.aheadOfDefaultCount, 1);
assert.notProperty(status, "workingTree");
assert.notProperty(status, "hasWorkingTreeChanges");
}),
);
it.effect("uses origin HEAD for default-branch detection with a non-origin upstream", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const origin = yield* makeTmpDir("git-vcs-driver-origin-");
const upstream = yield* makeTmpDir("git-vcs-driver-upstream-");
yield* initRepoWithCommit(cwd);
yield* git(origin, ["init", "--bare"]);
yield* git(upstream, ["init", "--bare"]);
yield* git(cwd, ["branch", "-M", "main"]);
yield* git(cwd, ["remote", "add", "origin", origin]);
yield* git(cwd, ["remote", "add", "upstream", upstream]);
yield* git(cwd, ["push", "origin", "main"]);
yield* git(cwd, ["push", "upstream", "main"]);
yield* git(cwd, ["symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main"]);
yield* git(cwd, ["checkout", "-b", "release"]);
yield* writeTextFile(cwd, "release.txt", "release\n");
yield* git(cwd, ["add", "release.txt"]);
yield* git(cwd, ["commit", "-m", "release commit"]);
yield* git(cwd, ["push", "-u", "upstream", "release"]);
yield* git(cwd, [
"symbolic-ref",
"refs/remotes/upstream/HEAD",
"refs/remotes/upstream/release",
]);
const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetailsRemote(cwd);
assert.equal(status.branch, "release");
assert.equal(status.upstreamRef, "upstream/release");
assert.equal(status.isDefaultBranch, false);
}),
);
it.effect("disables SSH askpass for background upstream status fetches", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
+93
View File
@@ -71,6 +71,16 @@ const NON_REPOSITORY_STATUS_DETAILS = Object.freeze<GitVcsDriver.GitStatusDetail
behindCount: 0,
aheadOfDefaultCount: 0,
});
const NON_REPOSITORY_REMOTE_STATUS_DETAILS = Object.freeze<GitVcsDriver.GitRemoteStatusDetails>({
isRepo: false,
isDefaultBranch: false,
branch: null,
upstreamRef: null,
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
});
type TraceTailState = {
processedChars: number;
@@ -1154,6 +1164,78 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
return Number.isFinite(parsed) ? Math.max(0, parsed) : 0;
});
const readStatusDetailsRemote = Effect.fn("readStatusDetailsRemote")(function* (cwd: string) {
const branchResult = yield* executeGit(
"GitVcsDriver.statusDetailsRemote.branch",
cwd,
["rev-parse", "--abbrev-ref", "HEAD"],
{ allowNonZeroExit: true },
).pipe(Effect.catchIf(isMissingGitCwdError, () => Effect.succeed(null)));
if (branchResult === null) {
return NON_REPOSITORY_REMOTE_STATUS_DETAILS;
}
if (branchResult.exitCode !== 0) {
const stderr = branchResult.stderr.trim();
return yield* createGitCommandError(
"GitVcsDriver.statusDetailsRemote.branch",
cwd,
["rev-parse", "--abbrev-ref", "HEAD"],
stderr || "git branch lookup failed",
);
}
const branchValue = branchResult.stdout.trim();
const branch = branchValue.length > 0 && branchValue !== "HEAD" ? branchValue : null;
const upstream = yield* resolveCurrentUpstream(cwd);
const upstreamRef = upstream?.upstreamRef ?? null;
let aheadCount = 0;
let behindCount = 0;
if (upstreamRef) {
const divergence = yield* executeGit(
"GitVcsDriver.statusDetailsRemote.divergence",
cwd,
["rev-list", "--left-right", "--count", `HEAD...${upstreamRef}`],
{ allowNonZeroExit: true },
);
if (divergence.exitCode === 0) {
const [aheadRaw, behindRaw] = divergence.stdout.trim().split(/\s+/);
const parsedAhead = Number.parseInt(aheadRaw ?? "0", 10);
const parsedBehind = Number.parseInt(behindRaw ?? "0", 10);
aheadCount = Number.isFinite(parsedAhead) ? Math.max(0, parsedAhead) : 0;
behindCount = Number.isFinite(parsedBehind) ? Math.max(0, parsedBehind) : 0;
}
} else if (branch) {
aheadCount = yield* computeAheadCountAgainstBase(cwd, branch).pipe(
Effect.orElseSucceed(() => 0),
);
}
const defaultBranch = yield* resolveDefaultBranchName(cwd, "origin");
const isDefaultBranch =
branch !== null &&
(branch === defaultBranch ||
(defaultBranch === null && (branch === "main" || branch === "master")));
const aheadOfDefaultCount =
branch && !isDefaultBranch
? upstreamRef === null
? aheadCount
: yield* computeAheadCountAgainstBase(cwd, branch).pipe(Effect.orElseSucceed(() => 0))
: 0;
return {
isRepo: true,
isDefaultBranch,
branch,
upstreamRef,
hasUpstream: upstreamRef !== null,
aheadCount,
behindCount,
aheadOfDefaultCount,
};
});
const readBranchRecency = Effect.fn("readBranchRecency")(function* (cwd: string) {
const branchRecency = yield* executeGit(
"GitVcsDriver.readBranchRecency",
@@ -1356,6 +1438,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
},
);
const statusDetailsRemote: GitVcsDriver.GitVcsDriverShape["statusDetailsRemote"] = Effect.fn(
"statusDetailsRemote",
)(function* (cwd) {
yield* refreshStatusUpstreamIfStale(cwd).pipe(
Effect.catchIf(isMissingGitCwdError, () => Effect.void),
Effect.ignoreCause({ log: true }),
);
return yield* readStatusDetailsRemote(cwd);
});
const status: GitVcsDriver.GitVcsDriverShape["status"] = (input) =>
statusDetails(input.cwd).pipe(
Effect.map((details) => ({
@@ -2302,6 +2394,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
status,
statusDetails,
statusDetailsLocal,
statusDetailsRemote,
prepareCommitContext,
commit,
pushCurrentBranch,
@@ -10,6 +10,7 @@ import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import type {
VcsStatusLocalResult,
VcsStatusRemoteResult,
@@ -310,6 +311,48 @@ describe("VcsStatusBroadcaster", () => {
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("delays automatic refresh when a cached remote snapshot is available", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
yield* broadcaster.getStatus({ cwd: "/repo" });
const scope = yield* Scope.make();
const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
yield* Stream.runForEach(
broadcaster.streamStatus(
{ cwd: "/repo" },
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.minutes(1)) },
),
(event) =>
event._tag === "snapshot"
? Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore)
: Effect.void,
).pipe(Effect.forkIn(scope));
yield* Deferred.await(snapshotDeferred);
assert.equal(state.remoteStatusCalls, 1);
assert.equal(state.remoteInvalidationCalls, 0);
yield* TestClock.adjust(Duration.seconds(59));
assert.equal(state.remoteStatusCalls, 1);
yield* TestClock.adjust(Duration.seconds(1));
yield* Effect.yieldNow;
assert.equal(state.remoteStatusCalls, 2);
assert.equal(state.remoteInvalidationCalls, 1);
yield* Scope.close(scope, Exit.void);
}).pipe(Effect.provide(Layer.merge(makeTestLayer(state), TestClock.layer())));
});
it("backs off remote refresh failures exponentially and honors larger configured intervals", () => {
assert.equal(
Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(1, Duration.seconds(1))),
+15 -2
View File
@@ -257,6 +257,7 @@ export const layer = Layer.effect(
const makeRemoteRefreshLoop = (
cwd: string,
automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
refreshImmediately: boolean,
) => {
return Effect.gen(function* () {
const consecutiveFailuresRef = yield* Ref.make(0);
@@ -289,6 +290,15 @@ export const layer = Layer.effect(
return nextDelay;
});
if (!refreshImmediately) {
const configuredInterval = yield* automaticRemoteRefreshInterval;
yield* Effect.sleep(
Duration.isZero(configuredInterval)
? DEFAULT_VCS_STATUS_REFRESH_INTERVAL
: configuredInterval,
);
}
return yield* refreshRemoteStatusIfEnabled.pipe(
Effect.repeat(
Schedule.identity<Duration.Duration>().pipe(
@@ -303,6 +313,7 @@ export const layer = Layer.effect(
const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
cwd: string,
automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
refreshImmediately: boolean,
) {
yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
const existing = activePollers.get(cwd);
@@ -315,7 +326,7 @@ export const layer = Layer.effect(
return Effect.succeed([undefined, nextPollers] as const);
}
return makeRemoteRefreshLoop(cwd, automaticRemoteRefreshInterval).pipe(
return makeRemoteRefreshLoop(cwd, automaticRemoteRefreshInterval, refreshImmediately).pipe(
Effect.forkIn(broadcasterScope),
Effect.map((fiber) => {
const nextPollers = new Map(activePollers);
@@ -363,11 +374,13 @@ export const layer = Layer.effect(
const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
const subscription = yield* PubSub.subscribe(changesPubSub);
const initialLocal = yield* getOrLoadLocalStatus(cwd);
const initialRemote = (yield* getCachedStatus(cwd))?.remote?.value ?? null;
const cachedStatus = yield* getCachedStatus(cwd);
const initialRemote = cachedStatus?.remote?.value ?? null;
yield* retainRemotePoller(
cwd,
options?.automaticRemoteRefreshInterval ??
Effect.succeed(DEFAULT_VCS_STATUS_REFRESH_INTERVAL),
cachedStatus?.remote === null || cachedStatus?.remote === undefined,
);
const release = releaseRemotePoller(cwd).pipe(Effect.ignore, Effect.asVoid);
+10 -30
View File
@@ -9,7 +9,7 @@ import {
clerkFrontendApiHostnameFromPublishableKey,
isAllowedClerkFrontendApiHostname,
} from "@t3tools/shared/relayAuth";
import React, { useEffect, useState } from "react";
import React, { useEffect, useMemo } from "react";
import {
makeDesktopClerkExternalAccountAdapter,
@@ -276,36 +276,16 @@ function getDesktopClerkInstance(publishableKey: string): Clerk {
}
export function DesktopClerkProvider({ children, publishableKey }: DesktopClerkProviderProps) {
const [clerkUiCtor, setClerkUiCtor] = useState<DesktopClerkUiCtor | undefined>(
() => window.__internal_ClerkUICtor,
// Clerk accepts a thenable UI constructor, so auth context can mount before the optional UI bundle.
const clerkUiLoad = useMemo(
() => Promise.resolve().then(() => loadDesktopClerkUi(publishableKey)),
[publishableKey],
);
const [clerkUiError, setClerkUiError] = useState<unknown>(null);
useEffect(() => {
let isCurrent = true;
void loadDesktopClerkUi(publishableKey).then(
(ClerkUI) => {
if (isCurrent) {
setClerkUiCtor(() => ClerkUI);
}
},
(error: unknown) => {
if (isCurrent) {
setClerkUiError(error);
}
},
);
return () => {
isCurrent = false;
};
}, [publishableKey]);
if (!clerkUiCtor) {
if (clerkUiError) {
console.error("Failed to load Clerk UI for desktop auth.", clerkUiError);
}
return null;
}
void clerkUiLoad.catch((error: unknown) => {
console.error("Failed to load Clerk UI for desktop auth.", error);
});
}, [clerkUiLoad]);
const clerk = getDesktopClerkInstance(publishableKey);
return (
@@ -313,7 +293,7 @@ export function DesktopClerkProvider({ children, publishableKey }: DesktopClerkP
key={publishableKey}
publishableKey={publishableKey}
Clerk={clerk as ClerkProviderProps["Clerk"]}
ui={{ ClerkUI: clerkUiCtor }}
ui={{ ClerkUI: clerkUiLoad as unknown as DesktopClerkUiCtor }}
standardBrowser={false}
>
{children}
@@ -451,8 +451,8 @@ describe("deriveMessagesTimelineRows", () => {
);
expect(foldRow?.turnId).toBe("turn-1");
expect(foldRow?.expanded).toBe(false);
// First fold entry (00:00:05) → terminal message completedAt (00:00:22).
expect(foldRow?.label).toBe("Worked for 17s");
// User message boundary (00:00:00) → terminal message completedAt (00:00:22).
expect(foldRow?.label).toBe("Worked for 22s");
expect(collapsedRows.map((row) => row.id)).toEqual([
"user-entry",
"turn-fold:turn-1",
@@ -480,6 +480,100 @@ describe("deriveMessagesTimelineRows", () => {
).toBeDefined();
});
it("derives a sane duration for a steer-superseded turn with one instant commentary message", () => {
// A steer ends the previous turn early: its only message completes the
// instant it is created, and trailing work entries land after it. The
// fold duration must span from the user message that started the turn to
// the last entry, not message createdAt → message completedAt (~0ms).
const rows = deriveMessagesTimelineRows({
timelineEntries: [
{
id: "user-entry",
kind: "message",
createdAt: "2026-01-01T00:00:00Z",
message: {
id: "user-1" as never,
role: "user" as const,
text: "do it once more",
turnId: null,
createdAt: "2026-01-01T00:00:00Z",
streaming: false,
},
},
{
id: "assistant-commentary-entry",
kind: "message",
createdAt: "2026-01-01T00:00:09Z",
message: {
id: "assistant-commentary" as never,
role: "assistant" as const,
text: "Kicking off call 1.",
turnId: "turn-1" as never,
createdAt: "2026-01-01T00:00:09Z",
completedAt: "2026-01-01T00:00:09Z",
streaming: false,
},
},
{
id: "work-entry-1",
kind: "work",
createdAt: "2026-01-01T00:00:12Z",
entry: {
id: "work-1",
createdAt: "2026-01-01T00:00:12Z",
turnId: "turn-1" as never,
label: "Ran command",
tone: "tool" as const,
},
},
{
id: "steer-user-entry",
kind: "message",
createdAt: "2026-01-01T00:00:14Z",
message: {
id: "user-2" as never,
role: "user" as const,
text: "actually do 15",
turnId: null,
createdAt: "2026-01-01T00:00:14Z",
streaming: false,
},
},
{
id: "assistant-next-turn-entry",
kind: "message",
createdAt: "2026-01-01T00:00:17Z",
message: {
id: "assistant-next" as never,
role: "assistant" as const,
text: "One down — adjusting.",
turnId: "turn-2" as never,
createdAt: "2026-01-01T00:00:17Z",
streaming: true,
},
},
],
latestTurn: {
turnId: "turn-2" as never,
state: "running",
startedAt: "2026-01-01T00:00:14Z",
completedAt: null,
},
isWorking: true,
activeTurnStartedAt: "2026-01-01T00:00:14Z",
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
const foldRow = rows.find(
(row): row is Extract<(typeof rows)[number], { kind: "turn-fold" }> =>
row.kind === "turn-fold",
);
// User message (00:00:00) → trailing work entry (00:00:12).
expect(foldRow?.turnId).toBe("turn-1");
expect(foldRow?.label).toBe("Worked for 12s");
});
it("uses latest-turn timings and the stopped label for an interrupted latest turn", () => {
const rows = deriveMessagesTimelineRows({
timelineEntries: [
@@ -12,6 +12,16 @@ function computeElapsedMs(startIso: string, endIso: string): number | null {
return Math.max(0, end - start);
}
function maxIsoTimestamp(a: string | null, b: string | null): string | null {
if (a === null) return b;
if (b === null) return a;
const aMs = Date.parse(a);
const bMs = Date.parse(b);
if (!Number.isFinite(aMs)) return b;
if (!Number.isFinite(bMs)) return a;
return bMs > aMs ? b : a;
}
export interface TimelineDurationMessage {
id: string;
role: "user" | "assistant" | "system";
@@ -167,10 +177,22 @@ function deriveTurnFolds(input: {
entries: Array<TimelineEntry>;
terminalEntry: Extract<TimelineEntry, { kind: "message" }> | null;
hasStreamingMessage: boolean;
/**
* The user message that kicked the turn off. Entry timestamps alone
* undercount the duration (the first entry appears only once the
* provider starts producing output), and a turn cut short by a steer may
* hold a single instantaneous commentary message.
*/
startBoundary: string | null;
}
const groupsByTurnId = new Map<TurnId, TurnGroup>();
let pendingUserBoundary: string | null = null;
for (const entry of input.timelineEntries) {
if (entry.kind === "message" && entry.message.role === "user") {
pendingUserBoundary = entry.message.createdAt;
continue;
}
const turnId =
entry.kind === "message" && entry.message.role === "assistant"
? (entry.message.turnId ?? null)
@@ -180,11 +202,20 @@ function deriveTurnFolds(input: {
if (!turnId) {
continue;
}
const group = groupsByTurnId.get(turnId) ?? {
entries: [],
terminalEntry: null,
hasStreamingMessage: false,
};
let group = groupsByTurnId.get(turnId);
if (!group) {
group = {
entries: [],
terminalEntry: null,
hasStreamingMessage: false,
// Each user boundary starts at most one turn; a second turn after the
// same user message (e.g. a steer-superseded continuation) falls back
// to its own first entry.
startBoundary: pendingUserBoundary,
};
pendingUserBoundary = null;
groupsByTurnId.set(turnId, group);
}
group.entries.push(entry);
if (entry.kind === "message") {
if (input.terminalAssistantMessageIds.has(entry.message.id)) {
@@ -194,7 +225,6 @@ function deriveTurnFolds(input: {
group.hasStreamingMessage = true;
}
}
groupsByTurnId.set(turnId, group);
}
const foldsByAnchorEntryId = new Map<string, TurnFold>();
@@ -223,17 +253,21 @@ function deriveTurnFolds(input: {
const isLatestInterruptedTurn =
input.latestTurn?.turnId === turnId && input.latestTurn.state === "interrupted";
// A turn cut short by a steer leaves trailing work entries behind its
// terminal message — take whichever ended last.
const lastEntryEnd =
lastEntry.kind === "message"
? (lastEntry.message.completedAt ?? lastEntry.createdAt)
: lastEntry.createdAt;
const elapsedMs =
input.latestTurn?.turnId === turnId &&
input.latestTurn.startedAt &&
input.latestTurn.completedAt
? computeElapsedMs(input.latestTurn.startedAt, input.latestTurn.completedAt)
: computeElapsedMs(
firstEntry.createdAt,
group.terminalEntry?.message.completedAt ??
(lastEntry.kind === "message"
? (lastEntry.message.completedAt ?? lastEntry.createdAt)
: lastEntry.createdAt),
group.startBoundary ?? firstEntry.createdAt,
maxIsoTimestamp(group.terminalEntry?.message.completedAt ?? null, lastEntryEnd) ??
lastEntryEnd,
);
const duration = elapsedMs !== null ? formatDuration(elapsedMs) : null;
const label = isLatestInterruptedTurn
@@ -368,7 +368,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
maintainScrollAtEndThreshold={0.1}
maintainVisibleContentPosition
onScroll={handleScroll}
className="h-full overflow-x-hidden overscroll-y-contain px-3 sm:px-5"
className="scrollbar-gutter-both h-full overflow-x-hidden overscroll-y-contain px-3 sm:px-5"
ListHeaderComponent={TIMELINE_LIST_HEADER}
ListFooterComponent={TIMELINE_LIST_FOOTER}
/>
+5 -1
View File
@@ -264,7 +264,11 @@ export function workEntryIndicatesToolNeutralStatus(entry: WorkLogEntry): boolea
export function formatDuration(durationMs: number): string {
if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
if (durationMs < 10_000) return `${(durationMs / 1_000).toFixed(1)}s`;
if (durationMs < 10_000) {
const tenths = Math.round(durationMs / 100) / 10;
// 9.95s+ rounds up to the next bucket — render "10s", not "10.0s".
return tenths >= 10 ? "10s" : `${tenths.toFixed(1)}s`;
}
if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
const minutes = Math.floor(durationMs / 60_000);
const seconds = Math.round((durationMs % 60_000) / 1_000);
+32 -1
View File
@@ -776,9 +776,40 @@ describe("incremental orchestration updates", () => {
localEnvironmentId,
);
// A completed assistant message must not settle the turn while the
// session is still running it — providers emit interim assistant
// messages between tool calls.
expect(threadsOf(next)[0]?.session?.status).toBe("running");
expect(threadsOf(next)[0]?.latestTurn?.state).toBe("completed");
expect(threadsOf(next)[0]?.latestTurn?.state).toBe("running");
expect(threadsOf(next)[0]?.latestTurn?.completedAt).toBeNull();
expect(threadsOf(next)[0]?.messages).toHaveLength(1);
const settled = applyOrchestrationEvents(
next,
[
makeEvent(
"thread.session-set",
{
threadId: thread.id,
session: {
threadId: thread.id,
status: "ready",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: "2026-02-27T00:00:04.000Z",
},
},
{ sequence: 4 },
),
],
localEnvironmentId,
);
// Leaving the running session status is the turn-end signal.
expect(threadsOf(settled)[0]?.latestTurn?.state).toBe("completed");
expect(threadsOf(settled)[0]?.latestTurn?.completedAt).toBe("2026-02-27T00:00:04.000Z");
});
it("does not regress latestTurn when an older turn diff completes late", () => {
+77 -17
View File
@@ -885,6 +885,29 @@ function buildLatestTurn(params: {
};
}
/**
* Turn state to settle a still-running latest turn with when its session
* leaves the "running" status, or null while the session is (re)starting or
* running and the turn must stay unsettled.
*/
function settledTurnStateForSessionStatus(
status: OrchestrationSessionStatus,
): "completed" | "interrupted" | "error" | null {
switch (status) {
case "idle":
case "ready":
return "completed";
case "error":
return "error";
case "interrupted":
case "stopped":
return "interrupted";
case "starting":
case "running":
return null;
}
}
function rebindTurnDiffSummariesForAssistantMessage(
turnDiffSummaries: ReadonlyArray<TurnDiffSummary>,
turnId: TurnId,
@@ -1419,6 +1442,15 @@ function applyEnvironmentOrchestrationEvent(
event.payload.messageId,
)
: thread.turnDiffSummaries;
// A completed assistant message only settles the turn once the
// session is no longer running it — providers may emit several
// assistant messages per turn (commentary between tool calls), and
// the turn must stay unsettled until the provider reports turn end.
const turnStillRunning =
event.payload.turnId !== null &&
thread.session?.orchestrationStatus === "running" &&
thread.session.activeTurnId === event.payload.turnId;
const settlesTurn = !event.payload.streaming && !turnStillRunning;
const latestTurn: Thread["latestTurn"] =
event.payload.role === "assistant" &&
event.payload.turnId !== null &&
@@ -1426,13 +1458,13 @@ function applyEnvironmentOrchestrationEvent(
? buildLatestTurn({
previous: thread.latestTurn,
turnId: event.payload.turnId,
state: event.payload.streaming
? "running"
: thread.latestTurn?.state === "interrupted"
state: settlesTurn
? thread.latestTurn?.state === "interrupted"
? "interrupted"
: thread.latestTurn?.state === "error"
? "error"
: "completed",
: "completed"
: "running",
requestedAt:
thread.latestTurn?.turnId === event.payload.turnId
? thread.latestTurn.requestedAt
@@ -1442,11 +1474,11 @@ function applyEnvironmentOrchestrationEvent(
? (thread.latestTurn.startedAt ?? event.payload.createdAt)
: event.payload.createdAt,
sourceProposedPlan: thread.pendingSourceProposedPlan,
completedAt: event.payload.streaming
? thread.latestTurn?.turnId === event.payload.turnId
completedAt: settlesTurn
? event.payload.updatedAt
: thread.latestTurn?.turnId === event.payload.turnId
? (thread.latestTurn.completedAt ?? null)
: null
: event.payload.updatedAt,
: null,
assistantMessageId: event.payload.messageId,
})
: thread.latestTurn;
@@ -1460,11 +1492,12 @@ function applyEnvironmentOrchestrationEvent(
});
case "thread.session-set":
return updateThreadState(state, event.payload.threadId, (thread) => ({
...thread,
session: mapSession(event.payload.session),
error: sanitizeThreadErrorMessage(event.payload.session.lastError),
latestTurn:
return updateThreadState(state, event.payload.threadId, (thread) => {
// Leaving the "running" session status is the turn-end signal:
// settle a still-running latest turn so its duration reflects the
// whole turn, not the last assistant message.
const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);
const latestTurn: Thread["latestTurn"] =
event.payload.session.status === "running" && event.payload.session.activeTurnId !== null
? buildLatestTurn({
previous: thread.latestTurn,
@@ -1485,9 +1518,30 @@ function applyEnvironmentOrchestrationEvent(
: null,
sourceProposedPlan: thread.pendingSourceProposedPlan,
})
: thread.latestTurn,
updatedAt: event.occurredAt,
}));
: thread.latestTurn !== null &&
thread.latestTurn.state === "running" &&
settledTurnState !== null
? buildLatestTurn({
previous: thread.latestTurn,
turnId: thread.latestTurn.turnId,
state: settledTurnState,
requestedAt: thread.latestTurn.requestedAt,
startedAt: thread.latestTurn.startedAt,
// A running turn's completedAt can only hold a mid-turn
// placeholder checkpoint timestamp — the session leaving
// "running" is the authoritative turn end.
completedAt: event.payload.session.updatedAt,
assistantMessageId: thread.latestTurn.assistantMessageId,
})
: thread.latestTurn;
return {
...thread,
session: mapSession(event.payload.session),
error: sanitizeThreadErrorMessage(event.payload.session.lastError),
latestTurn,
updatedAt: event.occurredAt,
};
});
case "thread.session-stop-requested":
return updateThreadState(state, event.payload.threadId, (thread) =>
@@ -1552,8 +1606,14 @@ function applyEnvironmentOrchestrationEvent(
(right.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER),
)
.slice(-MAX_THREAD_CHECKPOINTS);
// Mid-turn diff updates produce placeholder checkpoints; record the
// diff summary, but don't settle a turn its session is still running.
const turnStillRunning =
thread.session?.orchestrationStatus === "running" &&
thread.session.activeTurnId === event.payload.turnId;
const latestTurn =
thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId
!turnStillRunning &&
(thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
? buildLatestTurn({
previous: thread.latestTurn,
turnId: event.payload.turnId,
@@ -288,9 +288,98 @@ describe("applyThreadDetailEvent", () => {
expect(result.thread.latestTurn?.assistantMessageId).toBe("msg-3");
}
});
it("keeps latestTurn running for interim assistant messages while the session runs the turn", () => {
const threadWithRunningSession: OrchestrationThread = {
...baseThread,
session: {
threadId: ThreadId.make("thread-1"),
status: "running",
providerName: "claude",
runtimeMode: "full-access",
activeTurnId: TurnId.make("turn-1"),
lastError: null,
updatedAt: "2026-04-01T06:59:00.000Z",
},
latestTurn: {
turnId: TurnId.make("turn-1"),
state: "running",
requestedAt: "2026-04-01T06:59:00.000Z",
startedAt: "2026-04-01T06:59:00.000Z",
completedAt: null,
assistantMessageId: null,
},
};
const result = applyThreadDetailEvent(threadWithRunningSession, {
...baseEventFields,
sequence: 8,
occurredAt: "2026-04-01T07:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.message-sent",
payload: {
threadId: ThreadId.make("thread-1"),
messageId: MessageId.make("msg-3"),
role: "assistant",
text: "Interim commentary between tool calls.",
turnId: TurnId.make("turn-1"),
streaming: false,
createdAt: "2026-04-01T07:00:00.000Z",
updatedAt: "2026-04-01T07:00:00.000Z",
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.latestTurn?.state).toBe("running");
expect(result.thread.latestTurn?.completedAt).toBeNull();
}
});
});
describe("thread.session-set", () => {
it("settles a running latestTurn when the session leaves the running status", () => {
const threadWithRunningTurn: OrchestrationThread = {
...baseThread,
latestTurn: {
turnId: TurnId.make("turn-1"),
state: "running",
requestedAt: "2026-04-01T07:00:00.000Z",
startedAt: "2026-04-01T07:00:00.000Z",
completedAt: null,
assistantMessageId: MessageId.make("msg-3"),
},
};
const result = applyThreadDetailEvent(threadWithRunningTurn, {
...baseEventFields,
sequence: 9,
occurredAt: "2026-04-01T08:00:00.000Z",
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
type: "thread.session-set",
payload: {
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
status: "ready",
providerName: "claude",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: "2026-04-01T08:00:00.000Z",
},
},
});
expect(result.kind).toBe("updated");
if (result.kind === "updated") {
expect(result.thread.latestTurn?.state).toBe("completed");
expect(result.thread.latestTurn?.completedAt).toBe("2026-04-01T08:00:00.000Z");
}
});
it("updates session and latestTurn for a running session", () => {
const result = applyThreadDetailEvent(baseThread, {
...baseEventFields,
@@ -7,6 +7,7 @@ import type {
OrchestrationEvent,
OrchestrationLatestTurn,
OrchestrationMessage,
OrchestrationSession,
OrchestrationThread,
OrchestrationThreadActivity,
TurnId,
@@ -232,20 +233,29 @@ export function applyThreadDetailEvent(
: Arr.append(thread.messages, message);
const cappedMessages = Arr.takeRight(messages, limits.maxMessages);
// Update latestTurn for assistant messages bound to a turn.
// Update latestTurn for assistant messages bound to a turn. A completed
// assistant message only settles the turn once the session is no longer
// running it — providers may emit several assistant messages per turn
// (commentary between tool calls), and the turn must stay unsettled
// until the provider reports turn end.
const turnStillRunning =
event.payload.turnId !== null &&
thread.session?.status === "running" &&
thread.session.activeTurnId === event.payload.turnId;
const settlesTurn = !event.payload.streaming && !turnStillRunning;
const latestTurn: OrchestrationThread["latestTurn"] =
event.payload.role === "assistant" &&
event.payload.turnId !== null &&
(thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
? {
turnId: event.payload.turnId,
state: event.payload.streaming
? "running"
: thread.latestTurn?.state === "interrupted"
state: settlesTurn
? thread.latestTurn?.state === "interrupted"
? "interrupted"
: thread.latestTurn?.state === "error"
? "error"
: "completed",
: "completed"
: "running",
requestedAt:
thread.latestTurn?.turnId === event.payload.turnId
? thread.latestTurn.requestedAt
@@ -254,11 +264,11 @@ export function applyThreadDetailEvent(
thread.latestTurn?.turnId === event.payload.turnId
? (thread.latestTurn.startedAt ?? event.payload.createdAt)
: event.payload.createdAt,
completedAt: event.payload.streaming
? thread.latestTurn?.turnId === event.payload.turnId
completedAt: settlesTurn
? event.payload.updatedAt
: thread.latestTurn?.turnId === event.payload.turnId
? (thread.latestTurn.completedAt ?? null)
: null
: event.payload.updatedAt,
: null,
assistantMessageId: event.payload.messageId,
}
: thread.latestTurn;
@@ -287,6 +297,9 @@ export function applyThreadDetailEvent(
// ── Session ─────────────────────────────────────────────────────
case "thread.session-set": {
// Leaving the "running" session status is the turn-end signal: settle a
// still-running latest turn so its duration reflects the whole turn.
const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);
const latestTurn: OrchestrationLatestTurn | null =
event.payload.session.status === "running" && event.payload.session.activeTurnId !== null
? {
@@ -306,7 +319,18 @@ export function applyThreadDetailEvent(
? thread.latestTurn.assistantMessageId
: null,
}
: thread.latestTurn;
: thread.latestTurn !== null &&
thread.latestTurn.state === "running" &&
settledTurnState !== null
? {
...thread.latestTurn,
state: settledTurnState,
// A running turn's completedAt can only hold a mid-turn
// placeholder checkpoint timestamp — the session leaving
// "running" is the authoritative turn end.
completedAt: event.payload.session.updatedAt,
}
: thread.latestTurn;
return {
kind: "updated",
@@ -380,8 +404,14 @@ export function applyThreadDetailEvent(
Arr.takeRight(limits.maxCheckpoints),
);
// Mid-turn diff updates produce placeholder checkpoints; record the
// checkpoint, but don't settle a turn its session is still running.
const diffTurnStillRunning =
thread.session?.status === "running" &&
thread.session.activeTurnId === event.payload.turnId;
const latestTurn =
thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId
!diffTurnStillRunning &&
(thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
? {
turnId: event.payload.turnId,
state: checkpointStatusToTurnState(event.payload.status),
@@ -482,6 +512,29 @@ export function applyThreadDetailEvent(
// ── Helpers ──────────────────────────────────────────────────────────
/**
* Turn state to settle a still-running latest turn with when its session
* leaves the "running" status, or null while the session is (re)starting or
* running and the turn must stay unsettled.
*/
function settledTurnStateForSessionStatus(
status: OrchestrationSession["status"],
): "completed" | "interrupted" | "error" | null {
switch (status) {
case "idle":
case "ready":
return "completed";
case "error":
return "error";
case "interrupted":
case "stopped":
return "interrupted";
case "starting":
case "running":
return null;
}
}
function checkpointStatusToTurnState(
status: "ready" | "missing" | "error",
): OrchestrationLatestTurn["state"] {
@@ -17,7 +17,7 @@ import {
} from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
const UPSTREAM_REF = "07b695190f30a450e4921f71f77473e564395c59";
const UPSTREAM_REF = "b39f943a634a6e7ba86c3d6e8cf6d5f35e612566";
const USER_AGENT = "effect-codex-app-server-generator";
const GITHUB_API_BASE =
"https://api.github.com/repos/openai/codex/contents/codex-rs/app-server-protocol";
@@ -348,6 +348,7 @@ function resolveResponseTypeName(
const overrides: Record<string, string> = {
"account/logout": "LogoutAccountResponse",
"account/rateLimits/read": "GetAccountRateLimitsResponse",
"account/usage/read": "GetAccountTokenUsageResponse",
"config/batchWrite": "ConfigWriteResponse",
"config/mcpServer/reload": "McpServerRefreshResponse",
"config/value/write": "ConfigWriteResponse",
@@ -745,14 +746,16 @@ const generateFiles = Effect.fn("generateFiles")(function* () {
yield* Effect.log(`Generated Codex App Server schemas from ${UPSTREAM_REF}`);
yield* Effect.service(ChildProcessSpawner.ChildProcessSpawner).pipe(
Effect.flatMap((spawner) => spawner.spawn(ChildProcess.make("bun", ["oxfmt", generatedDir]))),
Effect.flatMap((spawner) =>
spawner.spawn(ChildProcess.make("vp", ["fmt", generatedDir, "--write"])),
),
Effect.flatMap((child) => child.exitCode),
Effect.tap((code) =>
code === 0
? Effect.void
: Effect.fail(
new GeneratorError({
detail: `oxfmt failed with exit code ${code}`,
detail: `vp fmt failed with exit code ${code}`,
}),
),
),
@@ -1,5 +1,5 @@
// This file is generated by the effect-codex-app-server package. Do not edit manually.
// Upstream protocol ref: 07b695190f30a450e4921f71f77473e564395c59
// Upstream protocol ref: b39f943a634a6e7ba86c3d6e8cf6d5f35e612566
import * as CodexSchema from "./schema.gen.ts";
@@ -9,8 +9,12 @@ export const CLIENT_REQUEST_METHODS = {
"thread/resume": "thread/resume",
"thread/fork": "thread/fork",
"thread/archive": "thread/archive",
"thread/delete": "thread/delete",
"thread/unsubscribe": "thread/unsubscribe",
"thread/name/set": "thread/name/set",
"thread/goal/set": "thread/goal/set",
"thread/goal/get": "thread/goal/get",
"thread/goal/clear": "thread/goal/clear",
"thread/metadata/update": "thread/metadata/update",
"thread/unarchive": "thread/unarchive",
"thread/compact/start": "thread/compact/start",
@@ -22,16 +26,19 @@ export const CLIENT_REQUEST_METHODS = {
"thread/read": "thread/read",
"thread/inject_items": "thread/inject_items",
"skills/list": "skills/list",
"skills/extraRoots/set": "skills/extraRoots/set",
"hooks/list": "hooks/list",
"marketplace/add": "marketplace/add",
"marketplace/remove": "marketplace/remove",
"marketplace/upgrade": "marketplace/upgrade",
"plugin/list": "plugin/list",
"plugin/installed": "plugin/installed",
"plugin/read": "plugin/read",
"plugin/skill/read": "plugin/skill/read",
"plugin/share/save": "plugin/share/save",
"plugin/share/updateTargets": "plugin/share/updateTargets",
"plugin/share/list": "plugin/share/list",
"plugin/share/checkout": "plugin/share/checkout",
"plugin/share/delete": "plugin/share/delete",
"app/list": "app/list",
"fs/readFile": "fs/readFile",
@@ -53,6 +60,7 @@ export const CLIENT_REQUEST_METHODS = {
"model/list": "model/list",
"modelProvider/capabilities/read": "modelProvider/capabilities/read",
"experimentalFeature/list": "experimentalFeature/list",
"permissionProfile/list": "permissionProfile/list",
"experimentalFeature/enablement/set": "experimentalFeature/enablement/set",
"mcpServer/oauth/login": "mcpServer/oauth/login",
"config/mcpServer/reload": "config/mcpServer/reload",
@@ -65,6 +73,7 @@ export const CLIENT_REQUEST_METHODS = {
"account/login/cancel": "account/login/cancel",
"account/logout": "account/logout",
"account/rateLimits/read": "account/rateLimits/read",
"account/usage/read": "account/usage/read",
"account/sendAddCreditsNudgeEmail": "account/sendAddCreditsNudgeEmail",
"feedback/upload": "feedback/upload",
"command/exec": "command/exec",
@@ -96,6 +105,7 @@ export const SERVER_REQUEST_METHODS = {
"item/permissions/requestApproval": "item/permissions/requestApproval",
"item/tool/call": "item/tool/call",
"account/chatgptAuthTokens/refresh": "account/chatgptAuthTokens/refresh",
"attestation/generate": "attestation/generate",
applyPatchApproval: "applyPatchApproval",
execCommandApproval: "execCommandApproval",
} as const;
@@ -105,12 +115,14 @@ export const SERVER_NOTIFICATION_METHODS = {
"thread/started": "thread/started",
"thread/status/changed": "thread/status/changed",
"thread/archived": "thread/archived",
"thread/deleted": "thread/deleted",
"thread/unarchived": "thread/unarchived",
"thread/closed": "thread/closed",
"skills/changed": "skills/changed",
"thread/name/updated": "thread/name/updated",
"thread/goal/updated": "thread/goal/updated",
"thread/goal/cleared": "thread/goal/cleared",
"thread/settings/updated": "thread/settings/updated",
"thread/tokenUsage/updated": "thread/tokenUsage/updated",
"turn/started": "turn/started",
"hook/started": "hook/started",
@@ -148,6 +160,7 @@ export const SERVER_NOTIFICATION_METHODS = {
"thread/compacted": "thread/compacted",
"model/rerouted": "model/rerouted",
"model/verification": "model/verification",
"turn/moderationMetadata": "turn/moderationMetadata",
warning: "warning",
guardianWarning: "guardianWarning",
deprecationNotice: "deprecationNotice",
@@ -178,8 +191,12 @@ export interface ClientRequestParamsByMethod {
readonly "thread/resume": CodexSchema.V2ThreadResumeParams;
readonly "thread/fork": CodexSchema.V2ThreadForkParams;
readonly "thread/archive": CodexSchema.V2ThreadArchiveParams;
readonly "thread/delete": CodexSchema.V2ThreadDeleteParams;
readonly "thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeParams;
readonly "thread/name/set": CodexSchema.V2ThreadSetNameParams;
readonly "thread/goal/set": CodexSchema.V2ThreadGoalSetParams;
readonly "thread/goal/get": CodexSchema.V2ThreadGoalGetParams;
readonly "thread/goal/clear": CodexSchema.V2ThreadGoalClearParams;
readonly "thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateParams;
readonly "thread/unarchive": CodexSchema.V2ThreadUnarchiveParams;
readonly "thread/compact/start": CodexSchema.V2ThreadCompactStartParams;
@@ -191,16 +208,19 @@ export interface ClientRequestParamsByMethod {
readonly "thread/read": CodexSchema.V2ThreadReadParams;
readonly "thread/inject_items": CodexSchema.V2ThreadInjectItemsParams;
readonly "skills/list": CodexSchema.V2SkillsListParams;
readonly "skills/extraRoots/set": CodexSchema.V2SkillsExtraRootsSetParams;
readonly "hooks/list": CodexSchema.V2HooksListParams;
readonly "marketplace/add": CodexSchema.V2MarketplaceAddParams;
readonly "marketplace/remove": CodexSchema.V2MarketplaceRemoveParams;
readonly "marketplace/upgrade": CodexSchema.V2MarketplaceUpgradeParams;
readonly "plugin/list": CodexSchema.V2PluginListParams;
readonly "plugin/installed": CodexSchema.V2PluginInstalledParams;
readonly "plugin/read": CodexSchema.V2PluginReadParams;
readonly "plugin/skill/read": CodexSchema.V2PluginSkillReadParams;
readonly "plugin/share/save": CodexSchema.V2PluginShareSaveParams;
readonly "plugin/share/updateTargets": CodexSchema.V2PluginShareUpdateTargetsParams;
readonly "plugin/share/list": CodexSchema.V2PluginShareListParams;
readonly "plugin/share/checkout": CodexSchema.V2PluginShareCheckoutParams;
readonly "plugin/share/delete": CodexSchema.V2PluginShareDeleteParams;
readonly "app/list": CodexSchema.V2AppsListParams;
readonly "fs/readFile": CodexSchema.V2FsReadFileParams;
@@ -222,6 +242,7 @@ export interface ClientRequestParamsByMethod {
readonly "model/list": CodexSchema.V2ModelListParams;
readonly "modelProvider/capabilities/read": CodexSchema.V2ModelProviderCapabilitiesReadParams;
readonly "experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListParams;
readonly "permissionProfile/list": CodexSchema.V2PermissionProfileListParams;
readonly "experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetParams;
readonly "mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginParams;
readonly "config/mcpServer/reload": undefined;
@@ -234,6 +255,7 @@ export interface ClientRequestParamsByMethod {
readonly "account/login/cancel": CodexSchema.V2CancelLoginAccountParams;
readonly "account/logout": undefined;
readonly "account/rateLimits/read": undefined;
readonly "account/usage/read": undefined;
readonly "account/sendAddCreditsNudgeEmail": CodexSchema.V2SendAddCreditsNudgeEmailParams;
readonly "feedback/upload": CodexSchema.V2FeedbackUploadParams;
readonly "command/exec": CodexSchema.V2CommandExecParams;
@@ -259,8 +281,12 @@ export interface ClientRequestResponsesByMethod {
readonly "thread/resume": CodexSchema.V2ThreadResumeResponse;
readonly "thread/fork": CodexSchema.V2ThreadForkResponse;
readonly "thread/archive": CodexSchema.V2ThreadArchiveResponse;
readonly "thread/delete": CodexSchema.V2ThreadDeleteResponse;
readonly "thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeResponse;
readonly "thread/name/set": CodexSchema.V2ThreadSetNameResponse;
readonly "thread/goal/set": CodexSchema.V2ThreadGoalSetResponse;
readonly "thread/goal/get": CodexSchema.V2ThreadGoalGetResponse;
readonly "thread/goal/clear": CodexSchema.V2ThreadGoalClearResponse;
readonly "thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateResponse;
readonly "thread/unarchive": CodexSchema.V2ThreadUnarchiveResponse;
readonly "thread/compact/start": CodexSchema.V2ThreadCompactStartResponse;
@@ -272,16 +298,19 @@ export interface ClientRequestResponsesByMethod {
readonly "thread/read": CodexSchema.V2ThreadReadResponse;
readonly "thread/inject_items": CodexSchema.V2ThreadInjectItemsResponse;
readonly "skills/list": CodexSchema.V2SkillsListResponse;
readonly "skills/extraRoots/set": CodexSchema.V2SkillsExtraRootsSetResponse;
readonly "hooks/list": CodexSchema.V2HooksListResponse;
readonly "marketplace/add": CodexSchema.V2MarketplaceAddResponse;
readonly "marketplace/remove": CodexSchema.V2MarketplaceRemoveResponse;
readonly "marketplace/upgrade": CodexSchema.V2MarketplaceUpgradeResponse;
readonly "plugin/list": CodexSchema.V2PluginListResponse;
readonly "plugin/installed": CodexSchema.V2PluginInstalledResponse;
readonly "plugin/read": CodexSchema.V2PluginReadResponse;
readonly "plugin/skill/read": CodexSchema.V2PluginSkillReadResponse;
readonly "plugin/share/save": CodexSchema.V2PluginShareSaveResponse;
readonly "plugin/share/updateTargets": CodexSchema.V2PluginShareUpdateTargetsResponse;
readonly "plugin/share/list": CodexSchema.V2PluginShareListResponse;
readonly "plugin/share/checkout": CodexSchema.V2PluginShareCheckoutResponse;
readonly "plugin/share/delete": CodexSchema.V2PluginShareDeleteResponse;
readonly "app/list": CodexSchema.V2AppsListResponse;
readonly "fs/readFile": CodexSchema.V2FsReadFileResponse;
@@ -303,6 +332,7 @@ export interface ClientRequestResponsesByMethod {
readonly "model/list": CodexSchema.V2ModelListResponse;
readonly "modelProvider/capabilities/read": CodexSchema.V2ModelProviderCapabilitiesReadResponse;
readonly "experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListResponse;
readonly "permissionProfile/list": CodexSchema.V2PermissionProfileListResponse;
readonly "experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetResponse;
readonly "mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginResponse;
readonly "config/mcpServer/reload": CodexSchema.V2McpServerRefreshResponse;
@@ -315,6 +345,7 @@ export interface ClientRequestResponsesByMethod {
readonly "account/login/cancel": CodexSchema.V2CancelLoginAccountResponse;
readonly "account/logout": CodexSchema.V2LogoutAccountResponse;
readonly "account/rateLimits/read": CodexSchema.V2GetAccountRateLimitsResponse;
readonly "account/usage/read": CodexSchema.V2GetAccountTokenUsageResponse;
readonly "account/sendAddCreditsNudgeEmail": CodexSchema.V2SendAddCreditsNudgeEmailResponse;
readonly "feedback/upload": CodexSchema.V2FeedbackUploadResponse;
readonly "command/exec": CodexSchema.V2CommandExecResponse;
@@ -346,6 +377,7 @@ export interface ServerRequestParamsByMethod {
readonly "item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalParams;
readonly "item/tool/call": CodexSchema.DynamicToolCallParams;
readonly "account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshParams;
readonly "attestation/generate": CodexSchema.AttestationGenerateParams;
readonly applyPatchApproval: CodexSchema.ApplyPatchApprovalParams;
readonly execCommandApproval: CodexSchema.ExecCommandApprovalParams;
}
@@ -358,6 +390,7 @@ export interface ServerRequestResponsesByMethod {
readonly "item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalResponse;
readonly "item/tool/call": CodexSchema.DynamicToolCallResponse;
readonly "account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshResponse;
readonly "attestation/generate": CodexSchema.AttestationGenerateResponse;
readonly applyPatchApproval: CodexSchema.ApplyPatchApprovalResponse;
readonly execCommandApproval: CodexSchema.ExecCommandApprovalResponse;
}
@@ -367,12 +400,14 @@ export interface ServerNotificationParamsByMethod {
readonly "thread/started": CodexSchema.V2ThreadStartedNotification;
readonly "thread/status/changed": CodexSchema.V2ThreadStatusChangedNotification;
readonly "thread/archived": CodexSchema.V2ThreadArchivedNotification;
readonly "thread/deleted": CodexSchema.V2ThreadDeletedNotification;
readonly "thread/unarchived": CodexSchema.V2ThreadUnarchivedNotification;
readonly "thread/closed": CodexSchema.V2ThreadClosedNotification;
readonly "skills/changed": CodexSchema.V2SkillsChangedNotification;
readonly "thread/name/updated": CodexSchema.V2ThreadNameUpdatedNotification;
readonly "thread/goal/updated": CodexSchema.V2ThreadGoalUpdatedNotification;
readonly "thread/goal/cleared": CodexSchema.V2ThreadGoalClearedNotification;
readonly "thread/settings/updated": CodexSchema.V2ThreadSettingsUpdatedNotification;
readonly "thread/tokenUsage/updated": CodexSchema.V2ThreadTokenUsageUpdatedNotification;
readonly "turn/started": CodexSchema.V2TurnStartedNotification;
readonly "hook/started": CodexSchema.V2HookStartedNotification;
@@ -410,6 +445,7 @@ export interface ServerNotificationParamsByMethod {
readonly "thread/compacted": CodexSchema.V2ContextCompactedNotification;
readonly "model/rerouted": CodexSchema.V2ModelReroutedNotification;
readonly "model/verification": CodexSchema.V2ModelVerificationNotification;
readonly "turn/moderationMetadata": CodexSchema.V2TurnModerationMetadataNotification;
readonly warning: CodexSchema.V2WarningNotification;
readonly guardianWarning: CodexSchema.V2GuardianWarningNotification;
readonly deprecationNotice: CodexSchema.V2DeprecationNoticeNotification;
@@ -435,8 +471,12 @@ export const CLIENT_REQUEST_PARAMS = {
"thread/resume": CodexSchema.V2ThreadResumeParams,
"thread/fork": CodexSchema.V2ThreadForkParams,
"thread/archive": CodexSchema.V2ThreadArchiveParams,
"thread/delete": CodexSchema.V2ThreadDeleteParams,
"thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeParams,
"thread/name/set": CodexSchema.V2ThreadSetNameParams,
"thread/goal/set": CodexSchema.V2ThreadGoalSetParams,
"thread/goal/get": CodexSchema.V2ThreadGoalGetParams,
"thread/goal/clear": CodexSchema.V2ThreadGoalClearParams,
"thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateParams,
"thread/unarchive": CodexSchema.V2ThreadUnarchiveParams,
"thread/compact/start": CodexSchema.V2ThreadCompactStartParams,
@@ -448,16 +488,19 @@ export const CLIENT_REQUEST_PARAMS = {
"thread/read": CodexSchema.V2ThreadReadParams,
"thread/inject_items": CodexSchema.V2ThreadInjectItemsParams,
"skills/list": CodexSchema.V2SkillsListParams,
"skills/extraRoots/set": CodexSchema.V2SkillsExtraRootsSetParams,
"hooks/list": CodexSchema.V2HooksListParams,
"marketplace/add": CodexSchema.V2MarketplaceAddParams,
"marketplace/remove": CodexSchema.V2MarketplaceRemoveParams,
"marketplace/upgrade": CodexSchema.V2MarketplaceUpgradeParams,
"plugin/list": CodexSchema.V2PluginListParams,
"plugin/installed": CodexSchema.V2PluginInstalledParams,
"plugin/read": CodexSchema.V2PluginReadParams,
"plugin/skill/read": CodexSchema.V2PluginSkillReadParams,
"plugin/share/save": CodexSchema.V2PluginShareSaveParams,
"plugin/share/updateTargets": CodexSchema.V2PluginShareUpdateTargetsParams,
"plugin/share/list": CodexSchema.V2PluginShareListParams,
"plugin/share/checkout": CodexSchema.V2PluginShareCheckoutParams,
"plugin/share/delete": CodexSchema.V2PluginShareDeleteParams,
"app/list": CodexSchema.V2AppsListParams,
"fs/readFile": CodexSchema.V2FsReadFileParams,
@@ -479,6 +522,7 @@ export const CLIENT_REQUEST_PARAMS = {
"model/list": CodexSchema.V2ModelListParams,
"modelProvider/capabilities/read": CodexSchema.V2ModelProviderCapabilitiesReadParams,
"experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListParams,
"permissionProfile/list": CodexSchema.V2PermissionProfileListParams,
"experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetParams,
"mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginParams,
"config/mcpServer/reload": undefined,
@@ -491,6 +535,7 @@ export const CLIENT_REQUEST_PARAMS = {
"account/login/cancel": CodexSchema.V2CancelLoginAccountParams,
"account/logout": undefined,
"account/rateLimits/read": undefined,
"account/usage/read": undefined,
"account/sendAddCreditsNudgeEmail": CodexSchema.V2SendAddCreditsNudgeEmailParams,
"feedback/upload": CodexSchema.V2FeedbackUploadParams,
"command/exec": CodexSchema.V2CommandExecParams,
@@ -516,8 +561,12 @@ export const CLIENT_REQUEST_RESPONSES = {
"thread/resume": CodexSchema.V2ThreadResumeResponse,
"thread/fork": CodexSchema.V2ThreadForkResponse,
"thread/archive": CodexSchema.V2ThreadArchiveResponse,
"thread/delete": CodexSchema.V2ThreadDeleteResponse,
"thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeResponse,
"thread/name/set": CodexSchema.V2ThreadSetNameResponse,
"thread/goal/set": CodexSchema.V2ThreadGoalSetResponse,
"thread/goal/get": CodexSchema.V2ThreadGoalGetResponse,
"thread/goal/clear": CodexSchema.V2ThreadGoalClearResponse,
"thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateResponse,
"thread/unarchive": CodexSchema.V2ThreadUnarchiveResponse,
"thread/compact/start": CodexSchema.V2ThreadCompactStartResponse,
@@ -529,16 +578,19 @@ export const CLIENT_REQUEST_RESPONSES = {
"thread/read": CodexSchema.V2ThreadReadResponse,
"thread/inject_items": CodexSchema.V2ThreadInjectItemsResponse,
"skills/list": CodexSchema.V2SkillsListResponse,
"skills/extraRoots/set": CodexSchema.V2SkillsExtraRootsSetResponse,
"hooks/list": CodexSchema.V2HooksListResponse,
"marketplace/add": CodexSchema.V2MarketplaceAddResponse,
"marketplace/remove": CodexSchema.V2MarketplaceRemoveResponse,
"marketplace/upgrade": CodexSchema.V2MarketplaceUpgradeResponse,
"plugin/list": CodexSchema.V2PluginListResponse,
"plugin/installed": CodexSchema.V2PluginInstalledResponse,
"plugin/read": CodexSchema.V2PluginReadResponse,
"plugin/skill/read": CodexSchema.V2PluginSkillReadResponse,
"plugin/share/save": CodexSchema.V2PluginShareSaveResponse,
"plugin/share/updateTargets": CodexSchema.V2PluginShareUpdateTargetsResponse,
"plugin/share/list": CodexSchema.V2PluginShareListResponse,
"plugin/share/checkout": CodexSchema.V2PluginShareCheckoutResponse,
"plugin/share/delete": CodexSchema.V2PluginShareDeleteResponse,
"app/list": CodexSchema.V2AppsListResponse,
"fs/readFile": CodexSchema.V2FsReadFileResponse,
@@ -560,6 +612,7 @@ export const CLIENT_REQUEST_RESPONSES = {
"model/list": CodexSchema.V2ModelListResponse,
"modelProvider/capabilities/read": CodexSchema.V2ModelProviderCapabilitiesReadResponse,
"experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListResponse,
"permissionProfile/list": CodexSchema.V2PermissionProfileListResponse,
"experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetResponse,
"mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginResponse,
"config/mcpServer/reload": CodexSchema.V2McpServerRefreshResponse,
@@ -572,6 +625,7 @@ export const CLIENT_REQUEST_RESPONSES = {
"account/login/cancel": CodexSchema.V2CancelLoginAccountResponse,
"account/logout": CodexSchema.V2LogoutAccountResponse,
"account/rateLimits/read": CodexSchema.V2GetAccountRateLimitsResponse,
"account/usage/read": CodexSchema.V2GetAccountTokenUsageResponse,
"account/sendAddCreditsNudgeEmail": CodexSchema.V2SendAddCreditsNudgeEmailResponse,
"feedback/upload": CodexSchema.V2FeedbackUploadResponse,
"command/exec": CodexSchema.V2CommandExecResponse,
@@ -603,6 +657,7 @@ export const SERVER_REQUEST_PARAMS = {
"item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalParams,
"item/tool/call": CodexSchema.DynamicToolCallParams,
"account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshParams,
"attestation/generate": CodexSchema.AttestationGenerateParams,
applyPatchApproval: CodexSchema.ApplyPatchApprovalParams,
execCommandApproval: CodexSchema.ExecCommandApprovalParams,
} as const;
@@ -615,6 +670,7 @@ export const SERVER_REQUEST_RESPONSES = {
"item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalResponse,
"item/tool/call": CodexSchema.DynamicToolCallResponse,
"account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshResponse,
"attestation/generate": CodexSchema.AttestationGenerateResponse,
applyPatchApproval: CodexSchema.ApplyPatchApprovalResponse,
execCommandApproval: CodexSchema.ExecCommandApprovalResponse,
} as const;
@@ -624,12 +680,14 @@ export const SERVER_NOTIFICATION_PARAMS = {
"thread/started": CodexSchema.V2ThreadStartedNotification,
"thread/status/changed": CodexSchema.V2ThreadStatusChangedNotification,
"thread/archived": CodexSchema.V2ThreadArchivedNotification,
"thread/deleted": CodexSchema.V2ThreadDeletedNotification,
"thread/unarchived": CodexSchema.V2ThreadUnarchivedNotification,
"thread/closed": CodexSchema.V2ThreadClosedNotification,
"skills/changed": CodexSchema.V2SkillsChangedNotification,
"thread/name/updated": CodexSchema.V2ThreadNameUpdatedNotification,
"thread/goal/updated": CodexSchema.V2ThreadGoalUpdatedNotification,
"thread/goal/cleared": CodexSchema.V2ThreadGoalClearedNotification,
"thread/settings/updated": CodexSchema.V2ThreadSettingsUpdatedNotification,
"thread/tokenUsage/updated": CodexSchema.V2ThreadTokenUsageUpdatedNotification,
"turn/started": CodexSchema.V2TurnStartedNotification,
"hook/started": CodexSchema.V2HookStartedNotification,
@@ -669,6 +727,7 @@ export const SERVER_NOTIFICATION_PARAMS = {
"thread/compacted": CodexSchema.V2ContextCompactedNotification,
"model/rerouted": CodexSchema.V2ModelReroutedNotification,
"model/verification": CodexSchema.V2ModelVerificationNotification,
"turn/moderationMetadata": CodexSchema.V2TurnModerationMetadataNotification,
warning: CodexSchema.V2WarningNotification,
guardianWarning: CodexSchema.V2GuardianWarningNotification,
deprecationNotice: CodexSchema.V2DeprecationNoticeNotification,
@@ -1,5 +1,5 @@
// This file is generated by the effect-codex-app-server package. Do not edit manually.
// Upstream protocol ref: 07b695190f30a450e4921f71f77473e564395c59
// Upstream protocol ref: b39f943a634a6e7ba86c3d6e8cf6d5f35e612566
import * as CodexSchema from "./schema.gen.ts";
@@ -74,6 +74,7 @@ export const v2 = {
GetAccountParams: CodexSchema.V2GetAccountParams,
GetAccountRateLimitsResponse: CodexSchema.V2GetAccountRateLimitsResponse,
GetAccountResponse: CodexSchema.V2GetAccountResponse,
GetAccountTokenUsageResponse: CodexSchema.V2GetAccountTokenUsageResponse,
GuardianWarningNotification: CodexSchema.V2GuardianWarningNotification,
HookCompletedNotification: CodexSchema.V2HookCompletedNotification,
HooksListParams: CodexSchema.V2HooksListParams,
@@ -112,13 +113,19 @@ export const v2 = {
ModelProviderCapabilitiesReadResponse: CodexSchema.V2ModelProviderCapabilitiesReadResponse,
ModelReroutedNotification: CodexSchema.V2ModelReroutedNotification,
ModelVerificationNotification: CodexSchema.V2ModelVerificationNotification,
PermissionProfileListParams: CodexSchema.V2PermissionProfileListParams,
PermissionProfileListResponse: CodexSchema.V2PermissionProfileListResponse,
PlanDeltaNotification: CodexSchema.V2PlanDeltaNotification,
PluginInstalledParams: CodexSchema.V2PluginInstalledParams,
PluginInstalledResponse: CodexSchema.V2PluginInstalledResponse,
PluginInstallParams: CodexSchema.V2PluginInstallParams,
PluginInstallResponse: CodexSchema.V2PluginInstallResponse,
PluginListParams: CodexSchema.V2PluginListParams,
PluginListResponse: CodexSchema.V2PluginListResponse,
PluginReadParams: CodexSchema.V2PluginReadParams,
PluginReadResponse: CodexSchema.V2PluginReadResponse,
PluginShareCheckoutParams: CodexSchema.V2PluginShareCheckoutParams,
PluginShareCheckoutResponse: CodexSchema.V2PluginShareCheckoutResponse,
PluginShareDeleteParams: CodexSchema.V2PluginShareDeleteParams,
PluginShareDeleteResponse: CodexSchema.V2PluginShareDeleteResponse,
PluginShareListParams: CodexSchema.V2PluginShareListParams,
@@ -146,6 +153,8 @@ export const v2 = {
SkillsChangedNotification: CodexSchema.V2SkillsChangedNotification,
SkillsConfigWriteParams: CodexSchema.V2SkillsConfigWriteParams,
SkillsConfigWriteResponse: CodexSchema.V2SkillsConfigWriteResponse,
SkillsExtraRootsSetParams: CodexSchema.V2SkillsExtraRootsSetParams,
SkillsExtraRootsSetResponse: CodexSchema.V2SkillsExtraRootsSetResponse,
SkillsListParams: CodexSchema.V2SkillsListParams,
SkillsListResponse: CodexSchema.V2SkillsListResponse,
TerminalInteractionNotification: CodexSchema.V2TerminalInteractionNotification,
@@ -158,9 +167,18 @@ export const v2 = {
ThreadClosedNotification: CodexSchema.V2ThreadClosedNotification,
ThreadCompactStartParams: CodexSchema.V2ThreadCompactStartParams,
ThreadCompactStartResponse: CodexSchema.V2ThreadCompactStartResponse,
ThreadDeletedNotification: CodexSchema.V2ThreadDeletedNotification,
ThreadDeleteParams: CodexSchema.V2ThreadDeleteParams,
ThreadDeleteResponse: CodexSchema.V2ThreadDeleteResponse,
ThreadForkParams: CodexSchema.V2ThreadForkParams,
ThreadForkResponse: CodexSchema.V2ThreadForkResponse,
ThreadGoalClearedNotification: CodexSchema.V2ThreadGoalClearedNotification,
ThreadGoalClearParams: CodexSchema.V2ThreadGoalClearParams,
ThreadGoalClearResponse: CodexSchema.V2ThreadGoalClearResponse,
ThreadGoalGetParams: CodexSchema.V2ThreadGoalGetParams,
ThreadGoalGetResponse: CodexSchema.V2ThreadGoalGetResponse,
ThreadGoalSetParams: CodexSchema.V2ThreadGoalSetParams,
ThreadGoalSetResponse: CodexSchema.V2ThreadGoalSetResponse,
ThreadGoalUpdatedNotification: CodexSchema.V2ThreadGoalUpdatedNotification,
ThreadInjectItemsParams: CodexSchema.V2ThreadInjectItemsParams,
ThreadInjectItemsResponse: CodexSchema.V2ThreadInjectItemsResponse,
@@ -189,6 +207,7 @@ export const v2 = {
ThreadRollbackResponse: CodexSchema.V2ThreadRollbackResponse,
ThreadSetNameParams: CodexSchema.V2ThreadSetNameParams,
ThreadSetNameResponse: CodexSchema.V2ThreadSetNameResponse,
ThreadSettingsUpdatedNotification: CodexSchema.V2ThreadSettingsUpdatedNotification,
ThreadShellCommandParams: CodexSchema.V2ThreadShellCommandParams,
ThreadShellCommandResponse: CodexSchema.V2ThreadShellCommandResponse,
ThreadStartedNotification: CodexSchema.V2ThreadStartedNotification,
@@ -205,6 +224,7 @@ export const v2 = {
TurnDiffUpdatedNotification: CodexSchema.V2TurnDiffUpdatedNotification,
TurnInterruptParams: CodexSchema.V2TurnInterruptParams,
TurnInterruptResponse: CodexSchema.V2TurnInterruptResponse,
TurnModerationMetadataNotification: CodexSchema.V2TurnModerationMetadataNotification,
TurnPlanUpdatedNotification: CodexSchema.V2TurnPlanUpdatedNotification,
TurnStartedNotification: CodexSchema.V2TurnStartedNotification,
TurnStartParams: CodexSchema.V2TurnStartParams,
File diff suppressed because it is too large. Load diff
@@ -152,4 +152,41 @@ it.layer(NodeServices.layer)("effect-codex-app-server client", (it) => {
assert.equal(initialized.userAgent, "mock-codex-app-server");
}),
);
it.effect("drains command stderr so large diagnostics cannot block protocol responses", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const scope = yield* Scope.make();
const clientLayer = CodexClient.layerCommand({
command: "node",
args: mockPeerArgs(yield* mockPeerPath),
cwd: path.join(import.meta.dirname, ".."),
env: {
CODEX_APP_SERVER_TEST_STDERR_BYTES: String(512 * 1024),
},
});
const context = yield* Layer.buildWithScope(clientLayer, scope);
const initialized = yield* Effect.gen(function* () {
const client = yield* CodexClient.CodexAppServerClient;
return yield* client.request("initialize", {
clientInfo: {
name: "effect-codex-app-server-test",
title: "Effect Codex App Server Test",
version: "0.0.0",
},
capabilities: {
experimentalApi: true,
optOutNotificationMethods: null,
},
});
}).pipe(
Effect.timeout("5 seconds"),
Effect.provide(context),
Effect.ensuring(Scope.close(scope, Exit.void)),
);
assert.equal(initialized.userAgent, "mock-codex-app-server");
}),
);
});
+11 -10
View File
@@ -4,6 +4,7 @@ import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stdio from "effect/Stdio";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as CodexRpc from "./_generated/meta.gen.ts";
@@ -253,11 +254,15 @@ export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make
export const layerChildProcess = (
handle: ChildProcessSpawner.ChildProcessHandle,
options: CodexAppServerClientOptions = {},
): Layer.Layer<CodexAppServerClient> => {
const stdio = makeChildStdio(handle);
const terminationError = makeTerminationError(handle);
return Layer.effect(CodexAppServerClient, make(stdio, options, terminationError));
};
): Layer.Layer<CodexAppServerClient> =>
Layer.effect(CodexAppServerClient, makeChildProcessClient(handle, options));
const makeChildProcessClient = Effect.fn(
"effect-codex-app-server/CodexAppServerClient.makeChildProcessClient",
)(function* (handle: ChildProcessSpawner.ChildProcessHandle, options: CodexAppServerClientOptions) {
yield* Stream.runDrain(handle.stderr).pipe(Effect.ignore, Effect.forkScoped);
return yield* make(makeChildStdio(handle), options, makeTerminationError(handle));
});
export interface CodexAppServerCommandLayerOptions extends CodexAppServerClientOptions {
readonly command: string;
@@ -292,9 +297,5 @@ export const layerCommand = (
}),
),
);
}).pipe(
Effect.flatMap((handle) =>
make(makeChildStdio(handle), options, makeTerminationError(handle)),
),
),
}).pipe(Effect.flatMap((handle) => makeChildProcessClient(handle, options))),
);
@@ -10,6 +10,8 @@ import { assert, it } from "@effect/vitest";
import * as CodexError from "./errors.ts";
import * as CodexProtocol from "./protocol.ts";
import * as CodexRpc from "./rpc.ts";
import * as CodexSchema from "./schema.ts";
import { makeInMemoryStdio } from "./_internal/stdio.ts";
const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
@@ -18,8 +20,28 @@ const encoder = new TextEncoder();
const encodeJsonl = (value: unknown) => encoder.encode(`${encodeUnknownJsonString(value)}\n`);
const decodeJson = Schema.decodeEffect(Schema.UnknownFromJsonString);
const decodeAccountTokenUsageResponse = Schema.decodeUnknownEffect(
CodexRpc.CLIENT_REQUEST_RESPONSES["account/usage/read"],
);
it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
it.effect("maps account usage responses to the upstream token usage schema", () =>
Effect.gen(function* () {
assert.strictEqual(
CodexRpc.CLIENT_REQUEST_RESPONSES["account/usage/read"],
CodexSchema.V2GetAccountTokenUsageResponse,
);
const decoded = yield* decodeAccountTokenUsageResponse({
dailyUsageBuckets: [{ startDate: "2026-06-10", tokens: 42 }],
summary: { lifetimeTokens: 42 },
});
assert.deepEqual(decoded, {
dailyUsageBuckets: [{ startDate: "2026-06-10", tokens: 42 }],
summary: { lifetimeTokens: 42 },
});
}),
);
it.effect(
"encodes requests without a jsonrpc field and routes inbound requests and notifications",
() =>
@@ -34,6 +34,18 @@ const handleMethod = (message: Record<string, unknown>) => {
switch (method) {
case "initialize": {
const stderrBytes = Number(process.env.CODEX_APP_SERVER_TEST_STDERR_BYTES ?? 0);
if (Number.isFinite(stderrBytes) && stderrBytes > 0) {
process.stderr.write("x".repeat(stderrBytes), () => {
respond(message.id as number | string, {
userAgent: "mock-codex-app-server",
codexHome: process.cwd(),
platformFamily: process.platform === "win32" ? "windows" : "unix",
platformOs: process.platform === "darwin" ? "macos" : process.platform,
});
});
return;
}
respond(message.id as number | string, {
userAgent: "mock-codex-app-server",
codexHome: process.cwd(),
+2 -1
View File
@@ -50,6 +50,7 @@ overrides:
'@effect/vitest': 4.0.0-beta.78
'@effect/vitest>@vitest/runner': '-'
'@effect/vitest>vitest': '-'
'@expo/metro-config': 56.0.13
'@types/node': 24.12.4
effect: 4.0.0-beta.78
vite: npm:@voidzero-dev/[email protected]
@@ -12620,7 +12621,7 @@ snapshots:
'@babel/plugin-transform-private-methods': 7.29.7(@babel/[email protected])
'@babel/plugin-transform-private-property-in-object': 7.29.7(@babel/[email protected])
'@babel/plugin-transform-react-display-name': 7.29.7(@babel/[email protected])
'@babel/plugin-transform-react-jsx': 7.29.7(@babel/[email protected])
'@babel/plugin-transform-react-jsx': 7.28.6(@babel/[email protected])
'@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/[email protected])
'@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/[email protected])
'@babel/plugin-transform-regenerator': 7.29.7(@babel/[email protected])
+4
View File
@@ -56,6 +56,10 @@ overrides:
"@effect/vitest": "catalog:"
"@effect/vitest>@vitest/runner": "-"
"@effect/vitest>vitest": "-"
# Pinned to the version the patch in patchedDependencies targets — a fresh
# resolve (e.g. release-smoke regenerating the lockfile) must not drift to a
# newer release and orphan the patch (ERR_PNPM_UNUSED_PATCH).
"@expo/metro-config": "56.0.13"
"@types/node": "catalog:"
effect: "catalog:"
vite: "catalog:"