revert more

This commit is contained in:
Julius Marminge authored and maria-rcks committed 2026-08-03 11:44:55 -04:00
1 parent a38b30441f
commit 9dd9a45568
26 files changed
+991 -917

No files matched your search

@@ -46,12 +46,6 @@ const PROJECT_ID = asProjectId("project-1");
const THREAD_ID = ThreadId.make("thread-1");
const FIXTURE_TURN_ID = "fixture-turn";
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
const LONG_LIVE_TEST_TIMEOUT_MS = 60_000;
const live = (
name: string,
test: Parameters<typeof it.live>[1],
timeout = LONG_LIVE_TEST_TIMEOUT_MS,
) => it.live(name, test, timeout);
type IntegrationProvider = ProviderKind;
function nowIso() {
@@ -186,7 +180,7 @@ const startTurn = (input: {
createdAt: input.createdAt ?? nowIso(),
});
live("runs a single turn end-to-end and persists checkpoint state in sqlite + git", () =>
it.live("runs a single turn end-to-end and persists checkpoint state in sqlite + git", () =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
@@ -365,7 +359,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
),
);
live("runs multi-turn file edits and persists checkpoint diffs", () =>
it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
@@ -548,7 +542,7 @@ live("runs multi-turn file edits and persists checkpoint diffs", () =>
),
);
live("tracks approval requests and resolves pending approvals on user response", () =>
it.live("tracks approval requests and resolves pending approvals on user response", () =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
@@ -629,273 +623,264 @@ live("tracks approval requests and resolves pending approvals on user response",
),
);
live(
"records failed turn runtime state and checkpoint status as error",
() =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
it.live("records failed turn runtime state and checkpoint status as error", () =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-failure-1", "2026-02-24T10:04:00.000Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-failure-1", "2026-02-24T10:04:00.000Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "content.delta",
...runtimeBase("evt-failure-2", "2026-02-24T10:04:00.100Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
payload: {
streamKind: "assistant_text",
delta: "Partial output before failure.\n",
},
{
type: "content.delta",
...runtimeBase("evt-failure-2", "2026-02-24T10:04:00.100Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
payload: {
streamKind: "assistant_text",
delta: "Partial output before failure.\n",
},
},
{
type: "runtime.error",
...runtimeBase("evt-failure-3", "2026-02-24T10:04:00.200Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
payload: {
message: "Sandbox command failed.",
},
{
type: "runtime.error",
...runtimeBase("evt-failure-3", "2026-02-24T10:04:00.200Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
payload: {
message: "Sandbox command failed.",
},
},
{
type: "turn.completed",
...runtimeBase("evt-failure-4", "2026-02-24T10:04:00.300Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
payload: {
state: "failed",
errorMessage: "Sandbox command failed.",
},
{
type: "turn.completed",
...runtimeBase("evt-failure-4", "2026-02-24T10:04:00.300Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
payload: {
state: "failed",
errorMessage: "Sandbox command failed.",
},
},
],
});
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-failure",
messageId: "msg-user-failure",
text: "Run risky command",
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-failure",
messageId: "msg-user-failure",
text: "Run risky command",
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.status === "error" &&
entry.session?.lastError === "Sandbox command failed." &&
entry.activities.some((activity) => activity.kind === "runtime.error") &&
entry.checkpoints.length === 1,
30_000,
);
assert.equal(thread.session?.status, "error");
assert.equal(thread.checkpoints[0]?.status, "error");
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.status === "error" &&
entry.session?.lastError === "Sandbox command failed." &&
entry.activities.some((activity) => activity.kind === "runtime.error") &&
entry.checkpoints.length === 1,
);
assert.equal(thread.session?.status, "error");
assert.equal(thread.checkpoints[0]?.status, "error");
const checkpointRow = yield* harness.checkpointRepository.getByThreadAndTurnCount({
threadId: THREAD_ID,
checkpointTurnCount: 1,
});
assert.equal(Option.isSome(checkpointRow), true);
if (Option.isSome(checkpointRow)) {
assert.equal(checkpointRow.value.status, "error");
}
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
true,
);
}),
),
LONG_LIVE_TEST_TIMEOUT_MS,
const checkpointRow = yield* harness.checkpointRepository.getByThreadAndTurnCount({
threadId: THREAD_ID,
checkpointTurnCount: 1,
});
assert.equal(Option.isSome(checkpointRow), true);
if (Option.isSome(checkpointRow)) {
assert.equal(checkpointRow.value.status, "error");
}
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
true,
);
}),
),
);
live(
"reverts to an earlier checkpoint and trims checkpoint projections + git refs",
() =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
it.live("reverts to an earlier checkpoint and trims checkpoint projections + git refs", () =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-revert-1", "2026-02-24T10:05:00.000Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "tool.started",
...runtimeBase("evt-revert-1-tool-started", "2026-02-24T10:05:00.025Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "tool.completed",
...runtimeBase("evt-revert-1-tool-completed", "2026-02-24T10:05:00.035Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "message.delta",
...runtimeBase("evt-revert-1a", "2026-02-24T10:05:00.050Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Updated README to v2.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-revert-2", "2026-02-24T10:05:00.100Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-revert-1",
messageId: "msg-user-revert-1",
text: "First edit",
});
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-revert-1", "2026-02-24T10:05:00.000Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "tool.started",
...runtimeBase("evt-revert-1-tool-started", "2026-02-24T10:05:00.025Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "tool.completed",
...runtimeBase("evt-revert-1-tool-completed", "2026-02-24T10:05:00.035Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "message.delta",
...runtimeBase("evt-revert-1a", "2026-02-24T10:05:00.050Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Updated README to v2.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-revert-2", "2026-02-24T10:05:00.100Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-revert-1",
messageId: "msg-user-revert-1",
text: "First edit",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) => entry.session?.threadId === "thread-1" && entry.checkpoints.length === 1,
30_000,
);
yield* harness.waitForThread(
THREAD_ID,
(entry) => entry.session?.threadId === "thread-1" && entry.checkpoints.length === 1,
);
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
events: [
{
type: "turn.started",
...runtimeBase("evt-revert-3", "2026-02-24T10:05:01.000Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "tool.started",
...runtimeBase("evt-revert-3-tool-started", "2026-02-24T10:05:01.025Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "tool.completed",
...runtimeBase("evt-revert-3-tool-completed", "2026-02-24T10:05:01.035Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "message.delta",
...runtimeBase("evt-revert-3a", "2026-02-24T10:05:01.050Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Updated README to v3.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-revert-4", "2026-02-24T10:05:01.100Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-revert-2",
messageId: "msg-user-revert-2",
text: "Second edit",
});
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
events: [
{
type: "turn.started",
...runtimeBase("evt-revert-3", "2026-02-24T10:05:01.000Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "tool.started",
...runtimeBase("evt-revert-3-tool-started", "2026-02-24T10:05:01.025Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "tool.completed",
...runtimeBase("evt-revert-3-tool-completed", "2026-02-24T10:05:01.035Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "message.delta",
...runtimeBase("evt-revert-3a", "2026-02-24T10:05:01.050Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Updated README to v3.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-revert-4", "2026-02-24T10:05:01.100Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-revert-2",
messageId: "msg-user-revert-2",
text: "Second edit",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.activities.some((activity) => activity.turnId === "turn-2"),
8000,
);
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.activities.some((activity) => activity.turnId === "turn-2"),
8000,
);
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.make("cmd-checkpoint-revert"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
});
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.make("cmd-checkpoint-revert"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
});
yield* harness.waitForDomainEvent((event) => event.type === "thread.reverted");
const revertedThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
30_000,
);
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
assert.deepEqual(
revertedThread.messages.map((message) => ({ role: message.role, text: message.text })),
[
{ role: "user", text: "First edit" },
{ role: "assistant", text: "Updated README to v2.\n" },
],
);
assert.equal(
revertedThread.activities.some((activity) => activity.turnId === "turn-2"),
false,
);
assert.equal(
revertedThread.activities.some(
(activity) => activity.turnId === "turn-1" && activity.kind === "tool.started",
),
true,
);
assert.equal(
revertedThread.activities.some(
(activity) => activity.turnId === "turn-1" && activity.kind === "tool.completed",
),
true,
);
assert.equal(fs.readFileSync(path.join(harness.workspaceDir, "README.md"), "utf8"), "v2\n");
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
false,
);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
yield* harness.waitForDomainEvent((event) => event.type === "thread.reverted");
const revertedThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
);
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
assert.deepEqual(
revertedThread.messages.map((message) => ({ role: message.role, text: message.text })),
[
{ role: "user", text: "First edit" },
{ role: "assistant", text: "Updated README to v2.\n" },
],
);
assert.equal(
revertedThread.activities.some((activity) => activity.turnId === "turn-2"),
false,
);
assert.equal(
revertedThread.activities.some(
(activity) => activity.turnId === "turn-1" && activity.kind === "tool.started",
),
true,
);
assert.equal(
revertedThread.activities.some(
(activity) => activity.turnId === "turn-1" && activity.kind === "tool.completed",
),
true,
);
assert.equal(fs.readFileSync(path.join(harness.workspaceDir, "README.md"), "utf8"), "v2\n");
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
false,
);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
const checkpointRows = yield* harness.checkpointRepository.listByThreadId({
threadId: THREAD_ID,
});
assert.equal(checkpointRows.length, 1);
}),
),
LONG_LIVE_TEST_TIMEOUT_MS,
const checkpointRows = yield* harness.checkpointRepository.listByThreadId({
threadId: THREAD_ID,
});
assert.equal(checkpointRows.length, 1);
}),
),
);
live(
it.live(
"appends checkpoint.revert.failed activity when revert is requested without an active session",
() =>
withHarness((harness) =>
@@ -932,7 +917,7 @@ live(
),
);
live("starts a claudeAgent session on first turn when provider is requested", () =>
it.live("starts a claudeAgent session on first turn when provider is requested", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
@@ -1001,7 +986,7 @@ live("starts a claudeAgent session on first turn when provider is requested", ()
),
);
live("recovers claudeAgent sessions after provider stopAll using persisted resume state", () =>
it.live("recovers claudeAgent sessions after provider stopAll using persisted resume state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
@@ -1059,7 +1044,6 @@ live("recovers claudeAgent sessions after provider stopAll using persisted resum
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
30_000,
);
yield* harness.adapterHarness!.adapter.stopAll();
@@ -1134,7 +1118,7 @@ live("recovers claudeAgent sessions after provider stopAll using persisted resum
),
);
live("forwards claudeAgent approval responses to the provider session", () =>
it.live("forwards claudeAgent approval responses to the provider session", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
@@ -1220,7 +1204,7 @@ live("forwards claudeAgent approval responses to the provider session", () =>
),
);
live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
@@ -1301,130 +1285,126 @@ live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
),
);
live(
"reverts claudeAgent turns and rolls back provider conversation state",
() =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
it.live("reverts claudeAgent turns and rolls back provider conversation state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v2\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-1",
messageId: "msg-user-claude-revert-1",
text: "First Claude edit",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
});
{
type: "message.delta",
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v2\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
}),
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
);
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-1",
messageId: "msg-user-claude-revert-1",
text: "First Claude edit",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v3\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
}),
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
);
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-2",
messageId: "msg-user-claude-revert-2",
text: "Second Claude edit",
});
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v3\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
}),
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.session?.providerName === "claudeAgent",
30_000,
);
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-2",
messageId: "msg-user-claude-revert-2",
text: "Second Claude edit",
});
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.make("cmd-checkpoint-revert-claude"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.session?.providerName === "claudeAgent",
);
const revertedThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
);
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
true,
);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
false,
);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
}),
"claudeAgent",
),
LONG_LIVE_TEST_TIMEOUT_MS,
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.make("cmd-checkpoint-revert-claude"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
});
const revertedThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
);
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
true,
);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
false,
);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
}),
"claudeAgent",
),
);
+23 -1
View File
@@ -12,6 +12,7 @@ import * as AcpError from "effect-acp/errors";
import type * as AcpSchema from "effect-acp/schema";
const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
const exitLogPath = process.env.T3_ACP_EXIT_LOG_PATH;
const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
const emitInterleavedAssistantToolCalls =
process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
@@ -56,6 +57,27 @@ let promptCount = 0;
let overlappingFirstPromptId: string | undefined;
const cancelledSessions = new Set<string>();
function logExit(reason: string): void {
if (!exitLogPath) {
return;
}
appendFileSync(exitLogPath, `${reason}\n`, "utf8");
}
process.once("SIGTERM", () => {
logExit("SIGTERM");
process.exit(0);
});
process.once("SIGINT", () => {
logExit("SIGINT");
process.exit(0);
});
process.once("exit", (code) => {
logExit(`exit:${code}`);
});
function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
if (parameterizedModelPicker) {
const baseOptions: Array<AcpSchema.SessionConfigOption> = [
@@ -398,7 +420,7 @@ const program = Effect.gen(function* () {
yield* agent.handleCancel(({ sessionId }) =>
Effect.sync(() => {
cancelledSessions.add(String(sessionId));
cancelledSessions.add(String(sessionId ?? "mock-session-1"));
}),
);
@@ -323,10 +323,10 @@ async function setSelectOptionIfAdvertised(
sessionId,
configId: option.id,
value,
})) as SetConfigResult;
})) as SetConfigResult | null | undefined;
logSection(`SET_${label}_RESPONSE`, response);
return response.configOptions ?? configOptions;
return response?.configOptions ?? configOptions;
}
async function main() {
@@ -384,10 +384,10 @@ async function main() {
sessionId,
configId: modelConfig.id,
value: targetModel,
})) as SetConfigResult;
})) as SetConfigResult | null | undefined;
logSection("SET_MODEL_RESPONSE", setModelResponse);
configOptions = setModelResponse.configOptions ?? configOptions;
configOptions = setModelResponse?.configOptions ?? configOptions;
configOptions = await setSelectOptionIfAdvertised(
rpc,
@@ -41,7 +41,10 @@ const mockAgentPath = NodePath.join(__dirname, "../../../scripts/acp-mock-agent.
const mockAgentCommand = "node";
const mockAgentArgs = [mockAgentPath] as const;
async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {
async function makeMockAgentWrapper(
extraEnv?: Record<string, string>,
options?: { initialDelaySeconds?: number },
) {
const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-acp-mock-"));
const wrapperPath = path.join(dir, "fake-agent.sh");
const envExports = Object.entries(extraEnv ?? {})
@@ -49,6 +52,7 @@ async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {
.join("\n");
const script = `#!/bin/sh
${envExports}
${options?.initialDelaySeconds ? `sleep ${JSON.stringify(String(options.initialDelaySeconds))}` : ""}
exec ${JSON.stringify(bunExe)} ${JSON.stringify(mockAgentPath)} "$@"
`;
await NodeFSP.writeFile(wrapperPath, script, "utf8");
@@ -96,6 +100,19 @@ async function readJsonLines(filePath: string) {
.map((line) => JSON.parse(line) as Record<string, unknown>);
}
async function waitForFileContent(filePath: string, attempts = 40) {
for (let attempt = 0; attempt < attempts; attempt += 1) {
try {
const raw = await readFile(filePath, "utf8");
if (raw.trim().length > 0) {
return raw;
}
} catch {}
await new Promise((resolve) => setTimeout(resolve, 50));
}
throw new Error(`Timed out waiting for file content at ${filePath}`);
}
const cursorAdapterTestLayer = it.layer(
Layer.effect(
CursorAdapter,
@@ -198,6 +215,90 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
}),
);
it.effect("closes the ACP child process when a session stops", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const settings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-stop-session-close");
const tempDir = yield* Effect.promise(() =>
mkdtemp(path.join(os.tmpdir(), "cursor-adapter-exit-log-")),
);
const exitLogPath = path.join(tempDir, "exit.log");
const wrapperPath = yield* Effect.promise(() =>
makeMockAgentWrapper({
T3_ACP_EXIT_LOG_PATH: exitLogPath,
}),
);
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
yield* adapter.startSession({
threadId,
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "cursor", model: "default" },
});
yield* adapter.stopSession(threadId);
const exitLog = yield* Effect.promise(() => waitForFileContent(exitLogPath));
assert.include(exitLog, "SIGTERM");
}),
);
it.effect(
"serializes concurrent startSession calls for the same thread and closes the replaced ACP session",
() =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const settings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-concurrent-start-session");
const tempDir = yield* Effect.promise(() =>
mkdtemp(path.join(os.tmpdir(), "cursor-adapter-concurrent-exit-log-")),
);
const exitLogPath = path.join(tempDir, "exit.log");
const wrapperPath = yield* Effect.promise(() =>
makeMockAgentWrapper(
{
T3_ACP_EXIT_LOG_PATH: exitLogPath,
},
{ initialDelaySeconds: 0.2 },
),
);
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
const [firstSession, secondSession] = yield* Effect.all(
[
adapter.startSession({
threadId,
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "cursor", model: "default" },
}),
adapter.startSession({
threadId,
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "cursor", model: "default" },
}),
],
{ concurrency: "unbounded" },
);
assert.equal(firstSession.threadId, threadId);
assert.equal(secondSession.threadId, threadId);
yield* adapter.stopSession(threadId);
const exitLog = yield* Effect.promise(() => waitForFileContent(exitLogPath));
assert.equal(exitLog.match(/SIGTERM/g)?.length ?? 0, 2);
}),
);
it.effect("rejects startSession when provider mismatches", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
@@ -247,12 +348,14 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.stopSession(threadId);
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
const modeRequest = requests.find(
(entry) =>
entry.method === "session/set_mode" ||
(entry.method === "session/set_config_option" &&
(entry.params as Record<string, unknown> | undefined)?.configId === "mode"),
);
const modeRequest = requests
.toReversed()
.find(
(entry) =>
entry.method === "session/set_mode" ||
(entry.method === "session/set_config_option" &&
(entry.params as Record<string, unknown> | undefined)?.configId === "mode"),
);
assert.isDefined(modeRequest);
assert.equal(
(modeRequest?.params as Record<string, unknown> | undefined)?.sessionId,
@@ -268,6 +371,80 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
}),
);
it.effect(
"applies initial model and mode configuration during startSession and skips repeating it on first send",
() =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const serverSettings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-initial-config-probe");
const tempDir = yield* Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "cursor-acp-")));
const requestLogPath = path.join(tempDir, "requests.ndjson");
const argvLogPath = path.join(tempDir, "argv.txt");
yield* Effect.promise(() => writeFile(requestLogPath, "", "utf8"));
const wrapperPath = yield* Effect.promise(() =>
makeProbeWrapper(requestLogPath, argvLogPath),
);
yield* serverSettings.updateSettings({
providers: { cursor: { binaryPath: wrapperPath } },
});
const modelSelection = {
provider: "cursor" as const,
model: "gpt-5.4",
options: {
reasoning: "xhigh" as const,
contextWindow: "1m",
fastMode: true,
},
};
yield* adapter.startSession({
threadId,
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection,
});
yield* Effect.promise(() => waitForFileContent(requestLogPath));
const requestsAfterStart = yield* Effect.promise(() => readJsonLines(requestLogPath));
const configIdsAfterStart = requestsAfterStart.flatMap((entry) =>
entry.method === "session/set_config_option" &&
typeof (entry.params as Record<string, unknown> | undefined)?.configId === "string"
? [String((entry.params as Record<string, unknown>).configId)]
: [],
);
assert.deepStrictEqual(configIdsAfterStart, [
"model",
"reasoning",
"context",
"fast",
"mode",
]);
yield* adapter.sendTurn({
threadId,
input: "hello mock",
attachments: [],
modelSelection,
interactionMode: "default",
});
yield* adapter.stopSession(threadId);
const finalRequests = yield* Effect.promise(() => readJsonLines(requestLogPath));
const finalConfigIds = finalRequests.flatMap((entry) =>
entry.method === "session/set_config_option" &&
typeof (entry.params as Record<string, unknown> | undefined)?.configId === "string"
? [String((entry.params as Record<string, unknown>).configId)]
: [],
);
assert.deepStrictEqual(finalConfigIds, ["model", "reasoning", "context", "fast", "mode"]);
assert.equal(finalRequests.filter((entry) => entry.method === "session/prompt").length, 1);
}),
);
it.effect(
"streams ACP tool calls and approvals on the active turn in approval-required mode",
() =>
@@ -847,6 +1024,92 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
}),
);
it.effect("interrupting a session settles pending user-input waits", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const serverSettings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-interrupt-pending-user-input");
const userInputRequested = yield* Deferred.make<void>();
const wrapperPath = yield* Effect.promise(() =>
makeMockAgentWrapper({ T3_ACP_EMIT_ASK_QUESTION: "1" }),
);
yield* serverSettings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
yield* Stream.runForEach(adapter.streamEvents, (event) => {
if (String(event.threadId) !== String(threadId) || event.type !== "user-input.requested") {
return Effect.void;
}
return Deferred.succeed(userInputRequested, undefined).pipe(Effect.ignore);
}).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "cursor", model: "default" },
});
const sendTurnFiber = yield* adapter
.sendTurn({
threadId,
input: "ask me a question and then interrupt",
attachments: [],
})
.pipe(Effect.forkChild);
yield* Deferred.await(userInputRequested);
yield* adapter.interruptTurn(threadId);
yield* Fiber.await(sendTurnFiber);
assert.equal(yield* adapter.hasSession(threadId), true);
yield* adapter.stopSession(threadId);
}),
);
it.effect("broadcasts runtime events to multiple stream consumers", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const settings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-runtime-event-broadcast");
const wrapperPath = yield* Effect.promise(() => makeMockAgentWrapper());
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
const firstConsumer = yield* Stream.take(adapter.streamEvents, 3).pipe(
Stream.runCollect,
Effect.forkChild,
);
const secondConsumer = yield* Stream.take(adapter.streamEvents, 3).pipe(
Stream.runCollect,
Effect.forkChild,
);
yield* adapter.startSession({
threadId,
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "cursor", model: "default" },
});
const firstEvents = Array.from(yield* Fiber.join(firstConsumer));
const secondEvents = Array.from(yield* Fiber.join(secondConsumer));
assert.deepStrictEqual(
firstEvents.map((event) => event.type),
["session.started", "session.state.changed", "thread.started"],
);
assert.deepStrictEqual(
secondEvents.map((event) => event.type),
["session.started", "session.state.changed", "thread.started"],
);
yield* adapter.stopSession(threadId);
}),
);
it.effect("switches model in-session via session/set_config_option", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
@@ -1500,20 +1500,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry;
const initial = yield* registry.getProviders;
assert.deepStrictEqual(Array.isArray(initial), true);
for (let attempt = 0; attempt < 100; attempt += 1) {
const refreshed = yield* registry.getProviders;
if (refreshed.find((status) => status.provider === "codex")?.status === "ready") {
break;
}
yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 5)));
}
const ready = yield* registry.getProviders;
const refreshed = yield* registry.refresh("codex");
assert.strictEqual(
ready.find((status) => status.provider === "codex")?.status,
refreshed.find((status) => status.provider === "codex")?.status,
"ready",
);
assert.notStrictEqual(
@@ -39,8 +39,6 @@ describe("AcpSessionRuntime", () => {
_meta: { parameterizedModelPicker: true },
},
});
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -80,7 +78,7 @@ describe("AcpSessionRuntime", () => {
});
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.events, 4)));
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
expect(notes).toHaveLength(4);
expect(notes.map((note) => note._tag)).toEqual([
"PlanUpdated",
@@ -101,8 +99,6 @@ describe("AcpSessionRuntime", () => {
) {
expect(assistantDelta.itemId).toBe(assistantStart.itemId);
}
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -283,7 +279,7 @@ describe("AcpSessionRuntime", () => {
});
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.events, 7)));
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 7)));
expect(notes.map((note) => note._tag)).toEqual([
"AssistantItemStarted",
"ContentDelta",
@@ -314,8 +310,6 @@ describe("AcpSessionRuntime", () => {
expect(secondStarted.itemId).not.toBe(firstStarted.itemId);
expect(secondDelta.itemId).toBe(secondStarted.itemId);
}
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -346,7 +340,7 @@ describe("AcpSessionRuntime", () => {
});
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.events, 1)));
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 1)));
expect(notes.map((note) => note._tag)).toEqual(["ToolCallUpdated"]);
const toolCall = notes[0];
expect(toolCall?._tag).toBe("ToolCallUpdated");
@@ -354,8 +348,6 @@ describe("AcpSessionRuntime", () => {
expect(toolCall.toolCall.status).toBe("completed");
expect(toolCall.toolCall.title).toBe("Read file");
}
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -407,8 +399,41 @@ describe("AcpSessionRuntime", () => {
(event) => event.method === "session/prompt" && event.status === "succeeded",
),
).toBe(true);
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: bunExe,
args: [mockAgentPath],
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
requestLogger: (event) =>
Effect.sync(() => {
requestEvents.push(event);
}),
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
);
});
yield* runtime.close;
it.effect("skips no-op session config writes when the requested value is already active", () => {
const requestEvents: Array<AcpSessionRequestLogEvent> = [];
return Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime;
yield* runtime.start();
yield* runtime.setConfigOption("model", "default");
yield* runtime.setMode("ask");
expect(
requestEvents.some(
(event) => event.method === "session/set_config_option" && event.status === "started",
),
).toBe(false);
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -452,8 +477,6 @@ describe("AcpSessionRuntime", () => {
expect(
protocolEvents.some((event) => event.direction === "incoming" && event.stage === "decoded"),
).toBe(true);
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -599,8 +622,6 @@ describe("AcpSessionRuntime", () => {
expect(error.message).toContain("composer-2[fast=true]");
}
yield* runtime.close;
const recordedRequests = readFileSync(requestLogPath, "utf8")
.trim()
.split("\n")
@@ -613,8 +634,6 @@ describe("AcpSessionRuntime", () => {
message.params?.value === "composer-2[fast=false]",
),
).toBe(false);
rmSync(tempDir, { recursive: true, force: true });
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -632,6 +651,7 @@ describe("AcpSessionRuntime", () => {
),
Effect.scoped,
Effect.provide(NodeServices.layer),
Effect.ensuring(Effect.sync(() => rmSync(tempDir, { recursive: true, force: true }))),
);
});
});
@@ -255,6 +255,24 @@ describe("AcpRuntimeModel", () => {
}
});
it("trims padded current mode updates before emitting a mode change", () => {
const result = parseSessionUpdateEvent({
sessionId: "session-1",
update: {
sessionUpdate: "current_mode_update",
currentModeId: " code ",
},
} satisfies EffectAcpSchema.SessionNotification);
expect(result.modeId).toBe("code");
expect(result.events).toEqual([
{
_tag: "ModeChanged",
modeId: "code",
},
]);
});
it("projects typed ACP plan and content updates", () => {
const planResult = parseSessionUpdateEvent({
sessionId: "session-1",
@@ -515,11 +515,13 @@ export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotificat
switch (upd.sessionUpdate) {
case "current_mode_update": {
modeId = upd.currentModeId;
events.push({
_tag: "ModeChanged",
modeId,
});
modeId = upd.currentModeId.trim();
if (modeId) {
events.push({
_tag: "ModeChanged",
modeId,
});
}
break;
}
case "plan": {
@@ -113,7 +113,7 @@ export interface AcpSessionRuntimeShape {
readonly handleExtRequest: EffectAcpClient.AcpClientShape["handleExtRequest"];
readonly handleExtNotification: EffectAcpClient.AcpClientShape["handleExtNotification"];
readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
readonly events: Stream.Stream<AcpParsedSessionEvent, never>;
readonly getEvents: () => Stream.Stream<AcpParsedSessionEvent, never>;
readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
readonly getConfigOptions: Effect.Effect<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;
readonly prompt: (
@@ -136,7 +136,6 @@ export interface AcpSessionRuntimeShape {
method: string,
payload: unknown,
) => Effect.Effect<void, EffectAcpErrors.AcpError>;
readonly close: Effect.Effect<void>;
}
interface AcpStartedState extends AcpSessionRuntimeStartResult {}
@@ -164,12 +163,12 @@ export const make = (
): Effect.Effect<
AcpSessionRuntime["Service"],
EffectAcpErrors.AcpError,
ChildProcessSpawner.ChildProcessSpawner
ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
> =>
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const runtimeScope = yield* Scope.make("sequential");
const runtimeScope = yield* Scope.Scope;
const eventQueue = yield* Queue.unbounded<AcpParsedSessionEvent>();
const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallState>());
@@ -296,7 +295,6 @@ export const make = (
});
}),
);
const close = Scope.close(runtimeScope, Exit.void).pipe(Effect.asVoid);
const initializeClientCapabilities = {
fs: {
@@ -380,32 +378,47 @@ export const make = (
| EffectAcpSchema.ResumeSessionResponse,
): Effect.Effect<void> => Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(response));
const updateCurrentModeId = (modeId: string): Effect.Effect<void> =>
Ref.update(modeStateRef, (current) =>
current ? { ...current, currentModeId: modeId } : current,
);
const setConfigOption = (
configId: string,
value: string | boolean,
): Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError> =>
validateConfigOptionValue(configId, value).pipe(
Effect.flatMap(() => getStartedState),
Effect.flatMap((started) => {
const requestPayload =
typeof value === "boolean"
? ({
sessionId: started.sessionId,
configId,
type: "boolean",
value,
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest)
: ({
sessionId: started.sessionId,
configId,
value: String(value),
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest);
return runLoggedRequest(
"session/set_config_option",
requestPayload,
acp.agent.setSessionConfigOption(requestPayload),
).pipe(Effect.tap((response) => updateConfigOptions(response)));
}),
Effect.flatMap((started) =>
Ref.get(configOptionsRef).pipe(
Effect.flatMap((configOptions) => {
const existing = findSessionConfigOption(configOptions, configId);
if (existing && configOptionCurrentValueMatches(existing, value)) {
return Effect.succeed({
configOptions,
} satisfies EffectAcpSchema.SetSessionConfigOptionResponse);
}
const requestPayload =
typeof value === "boolean"
? ({
sessionId: started.sessionId,
configId,
type: "boolean",
value,
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest)
: ({
sessionId: started.sessionId,
configId,
value: String(value),
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest);
return runLoggedRequest(
"session/set_config_option",
requestPayload,
acp.agent.setSessionConfigOption(requestPayload),
).pipe(Effect.tap((response) => updateConfigOptions(response)));
}),
),
),
);
const startOnce = Effect.gen(function* () {
@@ -585,7 +598,7 @@ export const make = (
handleExtRequest: acp.handleExtRequest,
handleExtNotification: acp.handleExtNotification,
start: () => start,
events: Stream.fromQueue(eventQueue),
getEvents: () => Stream.fromQueue(eventQueue),
getModeState: Ref.get(modeStateRef),
getConfigOptions: Ref.get(configOptionsRef),
prompt: (payload) =>
@@ -644,7 +657,17 @@ export const make = (
),
),
setMode: (modeId) =>
getStartedState.pipe(Effect.flatMap(() => setConfigOption("mode", modeId))),
Ref.get(modeStateRef).pipe(
Effect.flatMap((modeState) => {
if (modeState?.currentModeId === modeId) {
return Effect.succeed({} satisfies EffectAcpSchema.SetSessionModeResponse);
}
return setConfigOption("mode", modeId).pipe(
Effect.tap(() => updateCurrentModeId(modeId)),
Effect.as({} satisfies EffectAcpSchema.SetSessionModeResponse),
);
}),
),
setConfigOption,
setModel: (model) =>
getStartedState.pipe(
@@ -668,7 +691,6 @@ export const make = (
request: (method, payload) =>
runLoggedRequest(method, payload, acp.raw.request(method, payload)),
notify: acp.raw.notify,
close,
} satisfies AcpSessionRuntimeShape;
});
@@ -690,6 +712,20 @@ function sessionConfigOptionsFromSetup(
return response?.configOptions ?? [];
}
function configOptionCurrentValueMatches(
configOption: EffectAcpSchema.SessionConfigOption,
value: string | boolean,
): boolean {
const currentValue = configOption.currentValue;
if (configOption.type === "boolean") {
return currentValue === value;
}
if (typeof currentValue !== "string") {
return false;
}
return currentValue.trim() === String(value).trim();
}
const handleSessionUpdate = ({
queue,
modeStateRef,
@@ -17,7 +17,6 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
const started = yield* runtime.start();
expect(started.initializeResult).toBeDefined();
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -58,7 +57,10 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
if (Array.isArray(configOptions)) {
const modelConfig = configOptions.find((opt) => opt.category === "model");
const parameterizedOptions = configOptions.filter(
(opt) => opt.category === "thought_level" || opt.category === "model_config",
(opt) =>
opt.category === "thought_level" ||
opt.category === "model_option" ||
opt.category === "model_config",
);
// @effect-diagnostics-next-line preferSchemaOverJson:off
yield* Console.log("Model config option:", JSON.stringify(modelConfig, null, 2));
@@ -70,7 +72,6 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
expect(modelConfig).toBeDefined();
expect(typeof modelConfig?.id).toBe("string");
}
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -117,14 +118,16 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
if (Array.isArray(setResult.configOptions)) {
const modelConfig = setResult.configOptions.find((opt) => opt.category === "model");
const parameterizedOptions = setResult.configOptions.filter(
(opt) => opt.category === "thought_level" || opt.category === "model_config",
(opt) =>
opt.category === "thought_level" ||
opt.category === "model_option" ||
opt.category === "model_config",
);
if (modelConfig?.type === "select") {
expect(modelConfig.currentValue).toBe("gpt-5.4");
}
expect(parameterizedOptions.length).toBeGreaterThan(0);
}
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -1,91 +0,0 @@
import { describe, expect, it } from "vitest";
import type * as EffectCodexSchema from "effect-codex-app-server/schema";
import { readCodexAccountSnapshotResponse } from "./codexAccount.ts";
import { buildCodexInitializeParams, parseCodexSkillsListResponse } from "./codexAppServer.ts";
describe("buildCodexInitializeParams", () => {
it("returns the typed Codex initialize payload", () => {
expect(buildCodexInitializeParams()).toEqual({
clientInfo: {
name: "t3code_desktop",
title: "T3 Code Desktop",
version: "0.1.0",
},
capabilities: {
experimentalApi: true,
},
});
});
});
describe("readCodexAccountSnapshotResponse", () => {
it("maps chatgpt responses without lossy unknown parsing", () => {
const response = {
account: {
type: "chatgpt",
email: "[email protected]",
planType: "pro",
},
requiresOpenaiAuth: false,
} satisfies EffectCodexSchema.V2GetAccountResponse;
expect(readCodexAccountSnapshotResponse(response)).toEqual({
type: "chatgpt",
planType: "pro",
sparkEnabled: true,
});
});
});
describe("parseCodexSkillsListResponse", () => {
it("prefers the matching cwd bucket and keeps typed skill metadata", () => {
const response = {
data: [
{
cwd: "/tmp/other",
errors: [],
skills: [
{
name: "other",
path: "/tmp/other/SKILL.md",
description: "Other skill",
enabled: true,
scope: "repo",
},
],
},
{
cwd: "/work/project",
errors: [],
skills: [
{
name: "planner",
path: "/work/project/.skills/planner/SKILL.md",
description: "Plans work",
enabled: true,
scope: "repo",
shortDescription: "Plan steps",
interface: {
displayName: "Planner",
shortDescription: "Plan work",
},
},
],
},
],
} satisfies EffectCodexSchema.V2SkillsListResponse;
expect(parseCodexSkillsListResponse(response, "/work/project")).toEqual([
{
name: "planner",
path: "/work/project/.skills/planner/SKILL.md",
enabled: true,
description: "Plans work",
scope: "repo",
displayName: "Planner",
shortDescription: "Plan steps",
},
]);
});
});
@@ -31,8 +31,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
readonly getSettings: Effect.Effect<Settings, ServerSettingsError>;
readonly streamSettings: Stream.Stream<Settings>;
readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
readonly buildInitialSnapshot?: ((settings: Settings) => ServerProvider) | undefined;
readonly initialSnapshot?: ((settings: Settings) => ServerProvider) | undefined;
readonly initialSnapshot: (settings: Settings) => ServerProvider;
readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;
readonly enrichSnapshot?: (input: {
readonly settings: Settings;
@@ -42,26 +41,18 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
}) => Effect.Effect<void>;
readonly refreshInterval?: Duration.Input;
}): Effect.fn.Return<ServerProviderShape, ServerSettingsError, Scope.Scope> {
type InitialRefreshState = "idle" | "running" | "done";
const refreshSemaphore = yield* Semaphore.make(1);
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<ServerProvider>(),
PubSub.shutdown,
);
const initialSettings = yield* input.getSettings;
const initialSnapshotFactory = input.buildInitialSnapshot ?? input.initialSnapshot;
if (!initialSnapshotFactory) {
return yield* Effect.die(
new Error("makeManagedServerProvider requires an initial snapshot factory."),
);
}
const initialSnapshot = initialSnapshotFactory(initialSettings);
const initialSnapshot = input.initialSnapshot(initialSettings);
const snapshotStateRef = yield* Ref.make<ProviderSnapshotState>({
snapshot: initialSnapshot,
enrichmentGeneration: 0,
});
const settingsRef = yield* Ref.make(initialSettings);
const initialRefreshStateRef = yield* Ref.make<InitialRefreshState>("idle");
const enrichmentFiberRef = yield* Ref.make<Fiber.Fiber<void, unknown> | null>(null);
const scope = yield* Effect.scope;
@@ -73,7 +64,6 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
if (state.enrichmentGeneration !== generation || Equal.equals(state.snapshot, nextSnapshot)) {
return [null, state] as const;
}
return [
nextSnapshot,
{
@@ -139,7 +129,6 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
] as const;
});
yield* Ref.set(settingsRef, nextSettings);
yield* Ref.set(initialRefreshStateRef, "done");
yield* PubSub.publish(changesPubSub, nextSnapshot);
yield* restartSnapshotEnrichment(nextSettings, nextSnapshot, nextGeneration);
return nextSnapshot;
@@ -152,28 +141,6 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
return yield* applySnapshot(nextSettings, { forceRefresh: true });
});
const startInitialRefreshIfNeeded = Effect.fn("startInitialRefreshIfNeeded")(function* () {
const shouldStart = yield* Ref.modify(
initialRefreshStateRef,
(state): readonly [boolean, InitialRefreshState] =>
state === "idle" ? [true, "running"] : [false, state],
);
if (!shouldStart) {
return;
}
yield* refreshSnapshot().pipe(
Effect.onExit((exit) =>
exit._tag === "Failure"
? Ref.update(initialRefreshStateRef, (state) => (state === "running" ? "idle" : state))
: Effect.void,
),
Effect.ignoreCause({ log: true }),
Effect.forkIn(scope),
);
});
yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
Effect.asVoid(applySnapshot(nextSettings)),
).pipe(Effect.forkScoped);
@@ -203,17 +170,17 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
Effect.ignoreCause({ log: true }),
),
).pipe(Effect.forkScoped);
yield* startInitialRefreshIfNeeded();
yield* applySnapshot(initialSettings, { forceRefresh: true }).pipe(
Effect.ignoreCause({ log: true }),
Effect.forkScoped,
);
return {
getSnapshot: startInitialRefreshIfNeeded().pipe(
Effect.flatMap(() =>
input.getSettings.pipe(
Effect.flatMap(applySnapshot),
Effect.tapError(Effect.logError),
Effect.orDie,
),
),
getSnapshot: input.getSettings.pipe(
Effect.flatMap(applySnapshot),
Effect.tapError(Effect.logError),
Effect.orDie,
),
refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),
get streamChanges() {
+1 -1
View File
@@ -182,7 +182,7 @@ export const layerTest = (overrides: DeepPartial<ServerSettings> = {}) =>
const ServerSettingsJson = fromLenientJson(ServerSettings);
const decodeServerSettingsJsonExit = Schema.decodeUnknownExit(ServerSettingsJson);
const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent", "cursor"];
const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent", "opencode", "cursor"];
/**
* Ensure the `textGenerationModelSelection` points to an enabled provider.
@@ -102,25 +102,23 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
},
},
]
: provider === "codex"
? [
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "xhigh", label: "Extra High" },
{ value: "high", label: "High", isDefault: true },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
: [
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "xhigh", label: "Extra High" },
{ value: "high", label: "High", isDefault: true },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
]
: [];
},
];
const screen = await render(
<CompactComposerControlsMenu
activePlan={false}
@@ -1,5 +1,5 @@
import { type ProviderKind, type ServerProvider } from "@t3tools/contracts";
import { resolveModelSlugForProvider, resolveSelectableModel } from "@t3tools/shared/model";
import { resolveSelectableModel } from "@t3tools/shared/model";
import { memo, useState } from "react";
import type { VariantProps } from "class-variance-authority";
import { type ProviderPickerKind, PROVIDER_OPTIONS } from "../../session-logic";
@@ -46,24 +46,22 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
open?: boolean;
triggerVariant?: VariantProps<typeof buttonVariants>["variant"];
triggerClassName?: string;
disabledReason?: string;
onProviderModelChange: (provider: ProviderKind, model: string) => void;
}) {
const [isMenuOpen, setIsMenuOpen] = useState(false);
const activeProvider = props.lockedProvider ?? props.provider;
const selectedProviderOptions = props.modelOptionsByProvider[activeProvider];
const selectedModelValue =
resolveSelectableModel(activeProvider, props.model, selectedProviderOptions) ?? props.model;
const selectedModelLabel =
selectedProviderOptions.find((option) => option.slug === selectedModelValue)?.name ??
props.model;
selectedProviderOptions.find((option) => option.slug === props.model)?.name ?? props.model;
const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[activeProvider];
const handleModelChange = (provider: ProviderKind, value: string) => {
if (props.disabled) return;
if (!value) return;
const resolvedModel =
resolveSelectableModel(provider, value, props.modelOptionsByProvider[provider]) ??
resolveModelSlugForProvider(provider, value);
const resolvedModel = resolveSelectableModel(
provider,
value,
props.modelOptionsByProvider[provider],
);
if (!resolvedModel) return;
props.onProviderModelChange(provider, resolvedModel);
setIsMenuOpen(false);
@@ -92,7 +90,6 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
props.triggerClassName,
)}
disabled={props.disabled}
title={props.disabled ? props.disabledReason : undefined}
/>
}
>
@@ -124,7 +121,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
{props.lockedProvider !== null ? (
<MenuGroup>
<MenuRadioGroup
value={selectedModelValue}
value={props.model}
onValueChange={(value) => handleModelChange(props.lockedProvider!, value)}
>
{props.modelOptionsByProvider[props.lockedProvider].map((modelOption) => (
@@ -182,15 +179,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
<MenuSubPopup className="[--available-height:min(24rem,70vh)]" sideOffset={4}>
<MenuGroup>
<MenuRadioGroup
value={
props.provider === option.value
? (resolveSelectableModel(
option.value,
props.model,
props.modelOptionsByProvider[option.value],
) ?? props.model)
: ""
}
value={props.provider === option.value ? props.model : ""}
onValueChange={(value) => handleModelChange(option.value, value)}
>
{props.modelOptionsByProvider[option.value].map((modelOption) => (
@@ -628,6 +628,92 @@ describe("TraitsPicker (Codex)", () => {
});
});
// ── OpenCode TraitsPicker tests ───────────────────────────────────────
async function mountOpenCodePicker(props: { model?: string; options?: OpenCodeModelOptions }) {
const threadId = ThreadId.make("thread-opencode-traits");
const threadRef = scopeThreadRef(LOCAL_ENVIRONMENT_ID, threadId);
const threadKey = scopedThreadKey(threadRef);
const model = props.model ?? DEFAULT_MODEL_BY_PROVIDER.opencode;
const draftsByThreadKey: Record<string, ComposerThreadDraftState> = {
[threadKey]: {
prompt: "",
images: [],
nonPersistedImageIds: [],
persistedAttachments: [],
terminalContexts: [],
modelSelectionByProvider: {
opencode: {
provider: "opencode",
model,
...(props.options ? { options: props.options } : {}),
},
},
activeProvider: "opencode",
runtimeMode: null,
interactionMode: null,
},
};
useComposerDraftStore.setState({
draftsByThreadKey,
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
});
const host = document.createElement("div");
document.body.append(host);
const screen = await render(
<TraitsPicker
provider="opencode"
models={findTestProvider("opencode").models}
threadRef={threadRef}
model={model}
prompt=""
modelOptions={props.options}
onPromptChange={() => {}}
/>,
{ container: host },
);
const cleanup = async () => {
await screen.unmount();
host.remove();
};
return {
[Symbol.asyncDispose]: cleanup,
cleanup,
};
}
describe("TraitsPicker (OpenCode)", () => {
afterEach(() => {
document.body.innerHTML = "";
localStorage.removeItem(COMPOSER_DRAFT_STORAGE_KEY);
useComposerDraftStore.setState({
draftsByThreadKey: {},
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
stickyModelSelectionByProvider: {},
});
});
it("shows the selected agent label with capitalization in the trigger", async () => {
await using _ = await mountOpenCodePicker({
options: {
variant: "medium",
agent: "plan",
},
});
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Medium · Plan");
expect(text).not.toContain("Medium · plan");
});
});
});
describe("TraitsPicker (Cursor)", () => {
afterEach(() => {
document.body.innerHTML = "";
@@ -27,86 +27,6 @@ const CODEX_MODELS: ReadonlyArray<ServerProviderModel> = [
},
];
const CURSOR_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "auto",
name: "Auto",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "composer-2",
name: "Composer 2",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "gpt-5.3-codex",
name: "Codex 5.3",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium", isDefault: true },
{ value: "high", label: "High" },
{ value: "xhigh", label: "Extra high" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium", isDefault: true },
{ value: "high", label: "High" },
{ value: "xhigh", label: "Extra high" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "272k", label: "272k", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: [],
},
},
{
slug: "claude-opus-4-6",
name: "Opus 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
],
supportsFastMode: false,
supportsThinkingToggle: true,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
];
const CLAUDE_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "claude-opus-4-6",
@@ -393,141 +313,6 @@ describe("getComposerProviderState", () => {
});
});
it("returns minimal state for Cursor without trait controls", () => {
const state = getComposerProviderState({
provider: "cursor",
model: "auto",
models: CURSOR_MODELS,
prompt: "",
modelOptions: undefined,
});
expect(state).toEqual({
provider: "cursor",
promptEffort: null,
modelOptionsForDispatch: undefined,
});
});
it("dispatches Cursor fast traits separately from the family model key", () => {
const state = getComposerProviderState({
provider: "cursor",
model: "composer-2",
models: CURSOR_MODELS,
prompt: "",
modelOptions: {
cursor: { fastMode: true },
},
});
expect(state).toEqual({
provider: "cursor",
promptEffort: null,
modelOptionsForDispatch: { fastMode: true },
});
});
it("resolves Cursor reasoning effort from server-driven capabilities", () => {
const state = getComposerProviderState({
provider: "cursor",
model: "gpt-5.3-codex",
models: CURSOR_MODELS,
prompt: "",
modelOptions: {
cursor: { reasoning: "high" },
},
});
expect(state).toEqual({
provider: "cursor",
promptEffort: "high",
modelOptionsForDispatch: { reasoning: "high" },
});
});
it("preserves default Cursor reasoning in dispatch options so prior overrides can be cleared", () => {
const state = getComposerProviderState({
provider: "cursor",
model: "gpt-5.3-codex",
models: CURSOR_MODELS,
prompt: "",
modelOptions: {
cursor: { reasoning: "medium" },
},
});
expect(state).toEqual({
provider: "cursor",
promptEffort: "medium",
modelOptionsForDispatch: { reasoning: "medium" },
});
});
it("preserves Cursor context window in dispatch options", () => {
const state = getComposerProviderState({
provider: "cursor",
model: "gpt-5.4",
models: CURSOR_MODELS,
prompt: "",
modelOptions: {
cursor: {
contextWindow: "1m",
},
},
});
expect(state).toEqual({
provider: "cursor",
promptEffort: "medium",
modelOptionsForDispatch: {
contextWindow: "1m",
reasoning: "medium",
},
});
});
it("preserves explicit default Cursor reasoning so deepMerge can clear a prior non-default", () => {
const state = getComposerProviderState({
provider: "cursor",
model: "gpt-5.4",
models: CURSOR_MODELS,
prompt: "",
modelOptions: {
cursor: { reasoning: "medium" },
},
});
expect(state.modelOptionsForDispatch).toHaveProperty("reasoning", "medium");
});
it("preserves explicit Cursor fastMode: false so deepMerge can overwrite a prior true", () => {
const state = getComposerProviderState({
provider: "cursor",
model: "composer-2",
models: CURSOR_MODELS,
prompt: "",
modelOptions: {
cursor: { fastMode: false },
},
});
expect(state.modelOptionsForDispatch).toHaveProperty("fastMode", false);
});
it("preserves explicit Cursor thinking: true so deepMerge can overwrite a prior false", () => {
const state = getComposerProviderState({
provider: "cursor",
model: "claude-opus-4-6",
models: CURSOR_MODELS,
prompt: "",
modelOptions: {
cursor: { thinking: true },
},
});
expect(state.modelOptionsForDispatch).toHaveProperty("thinking", true);
});
it("preserves Claude default effort explicitly in dispatch options", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
+4 -6
View File
@@ -5,12 +5,10 @@ import type * as React from "react";
import { cn } from "~/lib/utils";
type InputProps = Omit<InputPrimitive.Props, "className" | "size" | "style"> & {
className?: string | undefined;
size?: "sm" | "default" | "lg" | number | undefined;
style?: React.CSSProperties | undefined;
unstyled?: boolean | undefined;
nativeInput?: boolean | undefined;
type InputProps = Omit<InputPrimitive.Props & React.RefAttributes<HTMLInputElement>, "size"> & {
size?: "sm" | "default" | "lg" | number;
unstyled?: boolean;
nativeInput?: boolean;
};
function Input({
+27
View File
@@ -1303,6 +1303,33 @@ describe("composerDraftStore modelSelection", () => {
);
});
it("preserves the selected Cursor model when only traits change", () => {
const store = useComposerDraftStore.getState();
store.setProviderModelOptions(
threadRef,
"cursor",
{
reasoning: "high",
},
{
model: "gpt-5.4",
persistSticky: true,
},
);
expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider.cursor).toEqual(
modelSelection("cursor", "gpt-5.4", {
reasoning: "high",
}),
);
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.cursor).toEqual(
modelSelection("cursor", "gpt-5.4", {
reasoning: "high",
}),
);
});
it("updates only the draft when sticky persistence is omitted", () => {
const store = useComposerDraftStore.getState();
+35 -29
View File
@@ -1263,6 +1263,41 @@ describe("deriveWorkLogEntries", () => {
});
});
it("does not use command stdout as the detail when Cursor omits the command input", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
id: "cursor-command-complete",
createdAt: "2026-04-16T22:40:42.221Z",
kind: "tool.completed",
summary: "Ran command",
payload: {
itemType: "command_execution",
title: "Ran command",
data: {
toolCallId: "toolu_vrtx_01WypXgRM8PPygBtrVAZwzy5",
kind: "execute",
rawInput: {},
rawOutput: {
exitCode: 0,
stdout: "total 960\napps\npackages\n",
stderr: "",
},
},
},
}),
];
const [entry] = deriveWorkLogEntries(activities, undefined);
expect(entry).toMatchObject({
id: "cursor-command-complete",
label: "Ran command",
itemType: "command_execution",
toolTitle: "Ran command",
});
expect(entry?.detail).toBeUndefined();
expect(entry?.command).toBeUndefined();
});
it("collapses legacy completed tool rows that are missing tool metadata", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
@@ -1651,32 +1686,3 @@ describe("deriveActiveWorkStartedAt", () => {
).toBe("2026-02-27T21:11:00.000Z");
});
});
describe("PROVIDER_OPTIONS", () => {
it("advertises Codex, Claude, OpenCode, and Cursor as available providers", () => {
const claude = PROVIDER_OPTIONS.find((option) => option.value === "claudeAgent");
const opencode = PROVIDER_OPTIONS.find((option) => option.value === "opencode");
const cursor = PROVIDER_OPTIONS.find((option) => option.value === "cursor");
expect(PROVIDER_OPTIONS).toEqual([
{ value: "codex", label: "Codex", available: true },
{ value: "claudeAgent", label: "Claude", available: true },
{ value: "opencode", label: "OpenCode", available: true },
{ value: "cursor", label: "Cursor", available: true },
]);
expect(claude).toEqual({
value: "claudeAgent",
label: "Claude",
available: true,
});
expect(opencode).toEqual({
value: "opencode",
label: "OpenCode",
available: true,
});
expect(cursor).toEqual({
value: "cursor",
label: "Cursor",
available: true,
});
});
});
+3 -2
View File
@@ -1,7 +1,6 @@
import type {
EnvironmentId,
MessageId,
ModelSelection,
OrchestrationCheckpointSummary,
OrchestrationEvent,
OrchestrationLatestTurn,
@@ -130,7 +129,9 @@ function arraysEqual<T>(left: readonly T[], right: readonly T[]): boolean {
return left.length === right.length && left.every((value, index) => value === right[index]);
}
function normalizeModelSelection<T extends ModelSelection>(selection: T): T {
function normalizeModelSelection<T extends { provider: ProviderKind; model: string }>(
selection: T,
): T {
return {
...selection,
model: resolveModelSlugForProvider(selection.provider, selection.model),
+2 -1
View File
@@ -33,7 +33,6 @@ export const CursorModelOptions = Schema.Struct({
contextWindow: Schema.optional(Schema.String),
});
export type CursorModelOptions = typeof CursorModelOptions.Type;
export const OpenCodeModelOptions = Schema.Struct({
variant: Schema.optional(TrimmedNonEmptyString),
agent: Schema.optional(TrimmedNonEmptyString),
@@ -254,6 +253,8 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Partial<
[OPENCODE_DRIVER_KIND]: {},
};
// ── Provider display names ────────────────────────────────────────────
export const PROVIDER_DISPLAY_NAMES: Record<ProviderKind, string> = {
codex: "Codex",
claudeAgent: "Claude",
-4
View File
@@ -33,10 +33,6 @@ export const ORCHESTRATION_WS_METHODS = {
subscribeThread: "orchestration.subscribeThread",
} as const;
export const ORCHESTRATION_WS_CHANNELS = {
domainEvent: "orchestration.domainEvent",
} as const;
export const ProviderKind = Schema.Literals(["codex", "claudeAgent", "cursor", "opencode"]);
export type ProviderKind = typeof ProviderKind.Type;
export const ProviderApprovalPolicy = Schema.Literals([
@@ -25,6 +25,7 @@ const RuntimeEventRawSource = Schema.Union([
Schema.Literal("claude.sdk.message"),
Schema.Literal("claude.sdk.permission"),
Schema.Literal("codex.sdk.thread-event"),
Schema.Literal("opencode.sdk.event"),
Schema.Literal("acp.jsonrpc"),
Schema.TemplateLiteral(["acp.", Schema.String, ".extension"]),
]);
+1 -1
View File
@@ -293,7 +293,7 @@ export const ClaudeSettings = makeProviderSettingsSchema(
export type ClaudeSettings = typeof ClaudeSettings.Type;
export const CursorSettings = Schema.Struct({
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
binaryPath: makeBinaryPathSetting("agent"),
apiEndpoint: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
-23
View File
@@ -312,29 +312,6 @@ export function trimOrNull<T extends string>(value: T | null | undefined): T | n
return trimmed || null;
}
/**
* Resolve the actual API model identifier from a model selection.
*
* Provider-aware: each provider can map `contextWindow` (or other options)
* to whatever the API requires. The canonical slug stored in the selection
* stays unchanged so the capabilities system keeps working.
*/
export function resolveApiModelId(modelSelection: ModelSelection): string {
switch (modelSelection.provider) {
case "claudeAgent": {
switch (modelSelection.options?.contextWindow) {
case "1m":
return `${modelSelection.model}[1m]`;
default:
return modelSelection.model;
}
}
default: {
return modelSelection.model;
}
}
}
export function createModelSelection(
instanceId: ProviderInstanceId,
model: string,