nit
This commit is contained in:
1 parent
21622d5bb7
commit
a38b30441f
14 files changed
+1298
-1061
No files matched your search
@@ -676,14 +676,7 @@ const GitManagerTestLayer = GitVcsDriver.layer.pipe(
|
||||
);
|
||||
|
||||
it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
const LONG_EFFECT_TEST_TIMEOUT_MS = 30_000;
|
||||
const effect = (
|
||||
name: string,
|
||||
test: Parameters<typeof it.effect>[1],
|
||||
timeout = LONG_EFFECT_TEST_TIMEOUT_MS,
|
||||
) => it.effect(name, test, timeout);
|
||||
|
||||
effect("status includes PR metadata when branch already has an open PR", () =>
|
||||
it.effect("status includes PR metadata when branch already has an open PR", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -725,7 +718,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("status trims PR metadata returned by gh before publishing it", () =>
|
||||
it.effect("status trims PR metadata returned by gh before publishing it", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -764,7 +757,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("status ignores invalid gh pr list entries and keeps valid ones", () =>
|
||||
it.effect("status ignores invalid gh pr list entries and keeps valid ones", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -816,7 +809,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("status preserves lowercase merged and closed PR states from gh json", () =>
|
||||
it.effect("status preserves lowercase merged and closed PR states from gh json", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -866,7 +859,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("status returns an explicit non-repo result for non-git directories", () =>
|
||||
it.effect("status returns an explicit non-repo result for non-git directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir("t3code-git-manager-non-repo-");
|
||||
const { manager } = yield* makeManager();
|
||||
@@ -893,7 +886,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("status returns an explicit non-repo result for deleted directories", () =>
|
||||
it.effect("status returns an explicit non-repo result for deleted directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const rootDir = yield* makeTempDir("t3code-git-manager-missing-dir-");
|
||||
const cwd = NodePath.join(rootDir, "deleted-repo");
|
||||
@@ -923,7 +916,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("status briefly caches repeated lookups for the same cwd", () =>
|
||||
it.effect("status briefly caches repeated lookups for the same cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -955,7 +948,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect(
|
||||
it.effect(
|
||||
"status ignores unrelated fork PRs when the current branch tracks the same repository",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
@@ -997,7 +990,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect(
|
||||
it.effect(
|
||||
"status detects cross-repo PRs from the upstream remote URL owner",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
@@ -1063,10 +1056,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
"pr list --head jasonLaster:statemachine --state all --limit 20 --json number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
||||
);
|
||||
}),
|
||||
LONG_EFFECT_TEST_TIMEOUT_MS,
|
||||
20_000,
|
||||
);
|
||||
|
||||
effect(
|
||||
it.effect(
|
||||
"status ignores synthetic local branch aliases when the upstream remote name contains slashes",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
@@ -1179,10 +1172,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
),
|
||||
).toBe(false);
|
||||
}),
|
||||
LONG_EFFECT_TEST_TIMEOUT_MS,
|
||||
20_000,
|
||||
);
|
||||
|
||||
effect("status returns merged PR state when latest PR was merged", () =>
|
||||
it.effect("status returns merged PR state when latest PR was merged", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -1221,7 +1214,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("status prefers open PR when merged PR has newer updatedAt", () =>
|
||||
it.effect("status prefers open PR when merged PR has newer updatedAt", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -1269,7 +1262,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("status is resilient to gh lookup failures and returns pr null", () =>
|
||||
it.effect("status is resilient to gh lookup failures and returns pr null", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -1294,7 +1287,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("creates a commit when working tree is dirty", () =>
|
||||
it.effect("creates a commit when working tree is dirty", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -1344,7 +1337,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("uses custom commit message when provided", () =>
|
||||
it.effect("uses custom commit message when provided", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -1387,7 +1380,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("commits only selected files when filePaths is provided", () =>
|
||||
it.effect("commits only selected files when filePaths is provided", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -1412,7 +1405,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("creates feature branch, commits, and pushes with featureBranch option", () =>
|
||||
it.effect("creates feature branch, commits, and pushes with featureBranch option", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -1475,7 +1468,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("featureBranch uses custom commit message and derives branch name", () =>
|
||||
it.effect("featureBranch uses custom commit message and derives branch name", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -1518,7 +1511,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("skips commit when there are no uncommitted changes", () =>
|
||||
it.effect("skips commit when there are no uncommitted changes", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -1536,7 +1529,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("featureBranch returns error when worktree is clean", () =>
|
||||
it.effect("featureBranch returns error when worktree is clean", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -1557,7 +1550,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("commits and pushes with upstream auto-setup when needed", () =>
|
||||
it.effect("commits and pushes with upstream auto-setup when needed", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -1584,7 +1577,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect(
|
||||
it.effect(
|
||||
"pushes and creates PR from a no-upstream branch when local commits are ahead of base",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
@@ -1636,7 +1629,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("skips push when branch is already up to date", () =>
|
||||
it.effect("skips push when branch is already up to date", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -1657,7 +1650,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("pushes existing clean commits without rerunning commit logic", () =>
|
||||
it.effect("pushes existing clean commits without rerunning commit logic", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -1685,7 +1678,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("create_pr pushes a clean branch before creating the PR when needed", () =>
|
||||
it.effect("create_pr pushes a clean branch before creating the PR when needed", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -1732,7 +1725,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("returns existing PR metadata for commit/push/pr action", () =>
|
||||
it.effect("returns existing PR metadata for commit/push/pr action", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -1778,7 +1771,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect(
|
||||
it.effect(
|
||||
"returns existing cross-repo PR metadata using the fork owner selector",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
@@ -1836,10 +1829,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
).toBe(true);
|
||||
expect(ghCalls.some((call) => call.startsWith("pr create "))).toBe(false);
|
||||
}),
|
||||
LONG_EFFECT_TEST_TIMEOUT_MS,
|
||||
12_000,
|
||||
);
|
||||
|
||||
effect(
|
||||
it.effect(
|
||||
"returns the correct existing PR when a slash remote checks out to a synthetic local alias",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
@@ -1936,10 +1929,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
false,
|
||||
);
|
||||
}),
|
||||
LONG_EFFECT_TEST_TIMEOUT_MS,
|
||||
20_000,
|
||||
);
|
||||
|
||||
effect(
|
||||
it.effect(
|
||||
"prefers owner-qualified selectors before bare branch names for cross-repo PRs",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
@@ -2011,10 +2004,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
expect(ownerSelectorCallIndex).toBeGreaterThanOrEqual(0);
|
||||
expect(ghCalls.some((call) => call.startsWith("pr create "))).toBe(false);
|
||||
}),
|
||||
LONG_EFFECT_TEST_TIMEOUT_MS,
|
||||
12_000,
|
||||
);
|
||||
|
||||
effect(
|
||||
it.effect(
|
||||
"stops probing head selectors after finding an existing PR",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
@@ -2078,10 +2071,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
"pr list --head octocat:statemachine --state open --limit 1",
|
||||
);
|
||||
}),
|
||||
LONG_EFFECT_TEST_TIMEOUT_MS,
|
||||
12_000,
|
||||
);
|
||||
|
||||
effect("creates PR when one does not already exist", () =>
|
||||
it.effect("creates PR when one does not already exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -2156,75 +2149,79 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("creates a new PR instead of reusing an unrelated fork PR with the same head branch", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/no-fork-match"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
|
||||
yield* runGit(repoDir, ["add", "changes.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/no-fork-match"]);
|
||||
it.effect(
|
||||
"creates a new PR instead of reusing an unrelated fork PR with the same head branch",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/no-fork-match"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
|
||||
yield* runGit(repoDir, ["add", "changes.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/no-fork-match"]);
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 1661,
|
||||
title: "Fork PR with same branch name",
|
||||
url: "https://github.com/pingdotgg/t3code/pull/1661",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/no-fork-match",
|
||||
state: "OPEN",
|
||||
isCrossRepository: true,
|
||||
headRepository: {
|
||||
nameWithOwner: "lnieuwenhuis/t3code",
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 1661,
|
||||
title: "Fork PR with same branch name",
|
||||
url: "https://github.com/pingdotgg/t3code/pull/1661",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/no-fork-match",
|
||||
state: "OPEN",
|
||||
isCrossRepository: true,
|
||||
headRepository: {
|
||||
nameWithOwner: "lnieuwenhuis/t3code",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: "lnieuwenhuis",
|
||||
},
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: "lnieuwenhuis",
|
||||
]),
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 188,
|
||||
title: "Add stacked git actions",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/188",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/no-fork-match",
|
||||
state: "OPEN",
|
||||
isCrossRepository: false,
|
||||
},
|
||||
},
|
||||
]),
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 188,
|
||||
title: "Add stacked git actions",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/188",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/no-fork-match",
|
||||
state: "OPEN",
|
||||
isCrossRepository: false,
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
|
||||
expect(result.pr.status).toBe("created");
|
||||
expect(result.pr.number).toBe(188);
|
||||
expect(result.toast).toEqual({
|
||||
title: "Created PR #188",
|
||||
description: "Add stacked git actions",
|
||||
cta: {
|
||||
kind: "open_pr",
|
||||
label: "View PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/188",
|
||||
},
|
||||
});
|
||||
expect(
|
||||
ghCalls.some((call) => call.includes("pr create --base main --head feature/no-fork-match")),
|
||||
).toBe(true);
|
||||
}),
|
||||
expect(result.pr.status).toBe("created");
|
||||
expect(result.pr.number).toBe(188);
|
||||
expect(result.toast).toEqual({
|
||||
title: "Created PR #188",
|
||||
description: "Add stacked git actions",
|
||||
cta: {
|
||||
kind: "open_pr",
|
||||
label: "View PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/188",
|
||||
},
|
||||
});
|
||||
expect(
|
||||
ghCalls.some((call) =>
|
||||
call.includes("pr create --base main --head feature/no-fork-match"),
|
||||
),
|
||||
).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
effect("creates cross-repo PRs with the fork owner selector and default base branch", () =>
|
||||
it.effect("creates cross-repo PRs with the fork owner selector and default base branch", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -2295,7 +2292,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("rejects push/pr actions from detached HEAD", () =>
|
||||
it.effect("rejects push/pr actions from detached HEAD", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -2313,7 +2310,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("surfaces missing gh binary errors", () =>
|
||||
it.effect("surfaces missing gh binary errors", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -2343,7 +2340,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("surfaces gh auth errors with guidance", () =>
|
||||
it.effect("surfaces gh auth errors with guidance", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -2373,7 +2370,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("resolves pull requests from #number references", () =>
|
||||
it.effect("resolves pull requests from #number references", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -2408,7 +2405,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("prepares pull request threads in local mode by checking out the PR branch", () =>
|
||||
it.effect("prepares pull request threads in local mode by checking out the PR branch", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -2444,7 +2441,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("prepares pull request threads in worktree mode on the PR head branch", () =>
|
||||
it.effect("prepares pull request threads in worktree mode on the PR head branch", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -2663,7 +2660,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("preserves fork upstream tracking when preparing a local PR thread", () =>
|
||||
it.effect("preserves fork upstream tracking when preparing a local PR thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -2716,7 +2713,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("derives fork repository identity from PR URL when GitHub omits nameWithOwner", () =>
|
||||
it.effect("derives fork repository identity from PR URL when GitHub omits nameWithOwner", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -2773,7 +2770,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("reuses an existing dedicated worktree for the PR head branch", () =>
|
||||
it.effect("reuses an existing dedicated worktree for the PR head branch", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -2825,7 +2822,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect(
|
||||
it.effect(
|
||||
"does not block fork PR worktree prep when the fork head branch collides with root main",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
@@ -2885,65 +2882,67 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("does not overwrite an existing local main branch when preparing a fork PR worktree", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const originDir = yield* createBareRemote();
|
||||
const forkDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "fork-main-source"]);
|
||||
fs.writeFileSync(path.join(repoDir, "fork-main-second.txt"), "fork main second\n");
|
||||
yield* runGit(repoDir, ["add", "fork-main-second.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Fork main second branch"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "fork-seed", "fork-main-source:main"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
const localMainBefore = (yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim();
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/root-branch"]);
|
||||
it.effect(
|
||||
"does not overwrite an existing local main branch when preparing a fork PR worktree",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const originDir = yield* createBareRemote();
|
||||
const forkDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "fork-main-source"]);
|
||||
fs.writeFileSync(path.join(repoDir, "fork-main-second.txt"), "fork main second\n");
|
||||
yield* runGit(repoDir, ["add", "fork-main-second.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Fork main second branch"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "fork-seed", "fork-main-source:main"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
const localMainBefore = (yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim();
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/root-branch"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
number: 92,
|
||||
title: "Fork main overwrite PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/92",
|
||||
baseRefName: "main",
|
||||
headRefName: "main",
|
||||
state: "open",
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "octocat/codething-mvp",
|
||||
headRepositoryOwnerLogin: "octocat",
|
||||
},
|
||||
repositoryCloneUrls: {
|
||||
"octocat/codething-mvp": {
|
||||
url: forkDir,
|
||||
sshUrl: forkDir,
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
number: 92,
|
||||
title: "Fork main overwrite PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/92",
|
||||
baseRefName: "main",
|
||||
headRefName: "main",
|
||||
state: "open",
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "octocat/codething-mvp",
|
||||
headRepositoryOwnerLogin: "octocat",
|
||||
},
|
||||
repositoryCloneUrls: {
|
||||
"octocat/codething-mvp": {
|
||||
url: forkDir,
|
||||
sshUrl: forkDir,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const result = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "92",
|
||||
mode: "worktree",
|
||||
});
|
||||
const result = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "92",
|
||||
mode: "worktree",
|
||||
});
|
||||
|
||||
expect(result.branch).toBe("t3code/pr-92/main");
|
||||
expect((yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim()).toBe(localMainBefore);
|
||||
expect(
|
||||
(yield* runGit(result.worktreePath as string, [
|
||||
"rev-parse",
|
||||
"--abbrev-ref",
|
||||
"@{upstream}",
|
||||
])).stdout.trim(),
|
||||
).toBe("fork-seed/main");
|
||||
}),
|
||||
expect(result.branch).toBe("t3code/pr-92/main");
|
||||
expect((yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim()).toBe(localMainBefore);
|
||||
expect(
|
||||
(yield* runGit(result.worktreePath as string, [
|
||||
"rev-parse",
|
||||
"--abbrev-ref",
|
||||
"@{upstream}",
|
||||
])).stdout.trim(),
|
||||
).toBe("fork-seed/main");
|
||||
}),
|
||||
);
|
||||
|
||||
effect("reuses an existing PR worktree and restores fork upstream tracking", () =>
|
||||
it.effect("reuses an existing PR worktree and restores fork upstream tracking", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -3087,7 +3086,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("emits ordered progress events for commit hooks", () =>
|
||||
it.effect("emits ordered progress events for commit hooks", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -3150,7 +3149,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("emits action_failed when a commit hook rejects", () =>
|
||||
it.effect("emits action_failed when a commit hook rejects", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
|
||||
@@ -96,6 +96,22 @@ function withFakeAcpAgent<A, E, R>(
|
||||
});
|
||||
}
|
||||
|
||||
function waitForFileContent(path: string): Effect.Effect<string> {
|
||||
return Effect.promise(async () => {
|
||||
const deadline = Date.now() + 5_000;
|
||||
for (;;) {
|
||||
try {
|
||||
return readFileSync(path, "utf8");
|
||||
} catch (error) {
|
||||
if (Date.now() >= deadline) {
|
||||
throw error instanceof Error ? error : new Error(String(error));
|
||||
}
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
|
||||
it.effect("uses ACP model config options instead of raw CLI model ids", () => {
|
||||
const requestLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-log-"));
|
||||
@@ -145,14 +161,6 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
|
||||
parameterizedModelPicker: true,
|
||||
},
|
||||
});
|
||||
expect(
|
||||
requests.some(
|
||||
(request) =>
|
||||
request.method === "session/set_config_option" &&
|
||||
request.params?.configId === "mode" &&
|
||||
request.params?.value === "ask",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
requests.some(
|
||||
(request) =>
|
||||
@@ -250,4 +258,41 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("closes the ACP child process after text generation completes", () => {
|
||||
const exitLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-exit-log-"));
|
||||
const exitLogPath = path.join(exitLogDir, "exit.log");
|
||||
|
||||
return withFakeAcpAgent(
|
||||
{
|
||||
T3_ACP_EXIT_LOG_PATH: exitLogPath,
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
|
||||
subject: "Close runtime after generation",
|
||||
body: "",
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/cursor-runtime-close",
|
||||
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
|
||||
stagedPatch:
|
||||
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
|
||||
modelSelection: {
|
||||
provider: "cursor",
|
||||
model: "composer-2",
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Close runtime after generation");
|
||||
|
||||
const exitLog = yield* waitForFileContent(exitLogPath);
|
||||
expect(exitLog).toContain("exit:0");
|
||||
|
||||
rmSync(exitLogDir, { recursive: true, force: true });
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -183,16 +183,8 @@ function splitNullSeparatedPaths(input: string): string[] {
|
||||
// ── Tests ──
|
||||
|
||||
it.layer(TestLayer)("git integration", (it) => {
|
||||
const LONG_EFFECT_TEST_TIMEOUT_MS = 30_000;
|
||||
const ASYNC_GIT_WAIT_TIMEOUT_MS = 30_000;
|
||||
const effect = (
|
||||
name: string,
|
||||
test: Parameters<typeof it.effect>[1],
|
||||
timeout = LONG_EFFECT_TEST_TIMEOUT_MS,
|
||||
) => it.effect(name, test, timeout);
|
||||
|
||||
describe("shell process execution", () => {
|
||||
effect("caps captured output when maxOutputBytes is exceeded", () =>
|
||||
it.effect("caps captured output when maxOutputBytes is exceeded", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* runShellCommand({
|
||||
command: `node -e "process.stdout.write('x'.repeat(2000))"`,
|
||||
@@ -211,7 +203,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
// ── initGitRepo ──
|
||||
|
||||
describe("initGitRepo", () => {
|
||||
effect("creates a valid git repo", () =>
|
||||
it.effect("creates a valid git repo", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* (yield* GitCore).initRepo({ cwd: tmp });
|
||||
@@ -219,7 +211,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("listGitBranches reports isRepo: true after init + commit", () =>
|
||||
it.effect("listGitBranches reports isRepo: true after init + commit", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -315,7 +307,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
// ── listGitBranches ──
|
||||
|
||||
describe("listGitBranches", () => {
|
||||
effect("returns isRepo: false for non-git directory", () =>
|
||||
it.effect("returns isRepo: false for non-git directory", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const result = yield* (yield* GitCore).listBranches({ cwd: tmp });
|
||||
@@ -325,7 +317,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("returns isRepo: false for deleted directories", () =>
|
||||
it.effect("returns isRepo: false for deleted directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const deletedDir = path.join(tmp, "deleted-repo");
|
||||
@@ -340,7 +332,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("returns the current branch with current: true", () =>
|
||||
it.effect("returns the current branch with current: true", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -351,7 +343,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("does not include detached HEAD pseudo-refs as branches", () =>
|
||||
it.effect("does not include detached HEAD pseudo-refs as branches", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -363,7 +355,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("keeps current branch first and sorts the remaining branches by recency", () =>
|
||||
it.effect("keeps current branch first and sorts the remaining branches by recency", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -401,7 +393,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("keeps default branch right after current branch", () =>
|
||||
it.effect("keeps default branch right after current branch", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir();
|
||||
@@ -445,7 +437,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("lists multiple branches after creating them", () =>
|
||||
it.effect("lists multiple branches after creating them", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -556,7 +548,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("lists local branches first and remote branches last", () =>
|
||||
it.effect("lists local branches first and remote branches last", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const tmp = yield* makeTmpDir();
|
||||
@@ -603,7 +595,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("includes remoteName metadata for remotes with slash in the name", () =>
|
||||
it.effect("includes remoteName metadata for remotes with slash in the name", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const tmp = yield* makeTmpDir();
|
||||
@@ -674,7 +666,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
// ── checkoutGitBranch ──
|
||||
|
||||
describe("checkoutGitBranch", () => {
|
||||
effect("checks out an existing branch", () =>
|
||||
it.effect("checks out an existing branch", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -688,7 +680,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("refreshes upstream behind count after checkout when remote branch advanced", () =>
|
||||
it.effect("refreshes upstream behind count after checkout when remote branch advanced", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* Effect.context<never>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
@@ -734,7 +726,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
expect(details.behindCount).toBe(1);
|
||||
},
|
||||
{
|
||||
timeout: ASYNC_GIT_WAIT_TIMEOUT_MS,
|
||||
timeout: 10_000,
|
||||
interval: 100,
|
||||
},
|
||||
),
|
||||
@@ -742,7 +734,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("statusDetails remains successful when upstream refresh fails after checkout", () =>
|
||||
it.effect("statusDetails remains successful when upstream refresh fails after checkout", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
@@ -789,7 +781,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("defers upstream refresh until statusDetails is requested", () =>
|
||||
it.effect("defers upstream refresh until statusDetails is requested", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
@@ -834,7 +826,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("shares upstream refreshes across worktrees that use the same git common dir", () =>
|
||||
it.effect("coalesces upstream refreshes across sibling worktrees on the same remote", () =>
|
||||
Effect.gen(function* () {
|
||||
const ok = (stdout = "") =>
|
||||
Effect.succeed({
|
||||
@@ -908,78 +900,83 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("briefly backs off failed upstream refreshes across sibling worktrees", () =>
|
||||
Effect.gen(function* () {
|
||||
const ok = (stdout = "") =>
|
||||
Effect.succeed({
|
||||
code: 0,
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
it.effect(
|
||||
"briefly backs off failed upstream refreshes across sibling worktrees on one remote",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const ok = (stdout = "") =>
|
||||
Effect.succeed({
|
||||
code: 0,
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
|
||||
let fetchCount = 0;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (
|
||||
input.args[0] === "rev-parse" &&
|
||||
input.args[1] === "--abbrev-ref" &&
|
||||
input.args[2] === "--symbolic-full-name" &&
|
||||
input.args[3] === "@{upstream}"
|
||||
) {
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123" ? "origin/feature/pr-123\n" : "origin/main\n",
|
||||
);
|
||||
}
|
||||
if (input.args[0] === "remote") {
|
||||
return ok("origin\n");
|
||||
}
|
||||
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
|
||||
return ok("/repo/.git\n");
|
||||
}
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
fetchCount += 1;
|
||||
let fetchCount = 0;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (
|
||||
input.args[0] === "rev-parse" &&
|
||||
input.args[1] === "--abbrev-ref" &&
|
||||
input.args[2] === "--symbolic-full-name" &&
|
||||
input.args[3] === "@{upstream}"
|
||||
) {
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123"
|
||||
? "origin/feature/pr-123\n"
|
||||
: "origin/main\n",
|
||||
);
|
||||
}
|
||||
if (input.args[0] === "remote") {
|
||||
return ok("origin\n");
|
||||
}
|
||||
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
|
||||
return ok("/repo/.git\n");
|
||||
}
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
fetchCount += 1;
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "simulated fetch timeout",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.status") {
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123"
|
||||
? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n"
|
||||
: "# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n",
|
||||
);
|
||||
}
|
||||
if (
|
||||
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
|
||||
input.operation === "GitCore.statusDetails.stagedNumstat"
|
||||
) {
|
||||
return ok();
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.defaultRef") {
|
||||
return ok("refs/remotes/origin/main\n");
|
||||
}
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "simulated fetch timeout",
|
||||
detail: "Unexpected git command in refresh failure cooldown test.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.status") {
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123"
|
||||
? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n"
|
||||
: "# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n",
|
||||
);
|
||||
}
|
||||
if (
|
||||
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
|
||||
input.operation === "GitCore.statusDetails.stagedNumstat"
|
||||
) {
|
||||
return ok();
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.defaultRef") {
|
||||
return ok("refs/remotes/origin/main\n");
|
||||
}
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "Unexpected git command in refresh failure cooldown test.",
|
||||
}),
|
||||
);
|
||||
});
|
||||
yield* core.statusDetails("/repo/worktrees/main");
|
||||
yield* core.statusDetails("/repo/worktrees/pr-123");
|
||||
expect(fetchCount).toBe(1);
|
||||
}),
|
||||
});
|
||||
|
||||
yield* core.statusDetails("/repo/worktrees/main");
|
||||
yield* core.statusDetails("/repo/worktrees/pr-123");
|
||||
expect(fetchCount).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
effect("throws when branch does not exist", () =>
|
||||
it.effect("throws when branch does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -990,7 +987,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("does not silently checkout a local branch when a remote ref no longer exists", () =>
|
||||
it.effect("does not silently checkout a local branch when a remote ref no longer exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
@@ -1013,7 +1010,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("checks out a remote tracking branch when remote name contains slashes", () =>
|
||||
it.effect("checks out a remote tracking branch when remote name contains slashes", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const prefixRemote = yield* makeTmpDir();
|
||||
@@ -1078,7 +1075,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect(
|
||||
it.effect(
|
||||
"falls back to detached checkout when --track would conflict with an existing local branch",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
@@ -1108,7 +1105,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("throws when checkout would overwrite uncommitted changes", () =>
|
||||
it.effect("throws when checkout would overwrite uncommitted changes", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1146,7 +1143,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
// ── createGitBranch ──
|
||||
|
||||
describe("createGitBranch", () => {
|
||||
effect("creates a new branch visible in listGitBranches", () =>
|
||||
it.effect("creates a new branch visible in listGitBranches", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1157,7 +1154,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("throws when branch already exists", () =>
|
||||
it.effect("throws when branch already exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1173,7 +1170,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
// ── renameGitBranch ──
|
||||
|
||||
describe("renameGitBranch", () => {
|
||||
effect("renames the current branch", () =>
|
||||
it.effect("renames the current branch", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1195,7 +1192,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("returns success without git invocation when old/new names match", () =>
|
||||
it.effect("returns success without git invocation when old/new names match", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1213,7 +1210,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("appends numeric suffix when target branch already exists", () =>
|
||||
it.effect("appends numeric suffix when target branch already exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1240,7 +1237,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("increments suffix until it finds an available branch name", () =>
|
||||
it.effect("increments suffix until it finds an available branch name", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1259,7 +1256,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("uses '--' separator for branch rename arguments", () =>
|
||||
it.effect("uses '--' separator for branch rename arguments", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1290,7 +1287,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
// ── createGitWorktree + removeGitWorktree ──
|
||||
|
||||
describe("createGitWorktree", () => {
|
||||
effect("creates a worktree with a new branch from the base branch", () =>
|
||||
it.effect("creates a worktree with a new branch from the base branch", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1317,7 +1314,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("worktree has the new branch checked out", () =>
|
||||
it.effect("worktree has the new branch checked out", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1342,7 +1339,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("creates a worktree for an existing branch when newBranch is omitted", () =>
|
||||
it.effect("creates a worktree for an existing branch when newBranch is omitted", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1364,7 +1361,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("throws when new branch name already exists", () =>
|
||||
it.effect("throws when new branch name already exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1387,7 +1384,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("listGitBranches from worktree cwd reports worktree branch as current", () =>
|
||||
it.effect("listGitBranches from worktree cwd reports worktree branch as current", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1419,7 +1416,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("removeGitWorktree cleans up the worktree", () =>
|
||||
it.effect("removeGitWorktree cleans up the worktree", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1442,7 +1439,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("removeGitWorktree force removes a dirty worktree", () =>
|
||||
it.effect("removeGitWorktree force removes a dirty worktree", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1477,7 +1474,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
// ── Full flow: local branch checkout ──
|
||||
|
||||
describe("full flow: local branch checkout", () => {
|
||||
effect("init → commit → create branch → checkout → verify current", () =>
|
||||
it.effect("init → commit → create branch → checkout → verify current", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1494,7 +1491,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
// ── Full flow: worktree creation from base branch ──
|
||||
|
||||
describe("full flow: worktree creation", () => {
|
||||
effect("creates worktree with new branch from current branch", () =>
|
||||
it.effect("creates worktree with new branch from current branch", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1529,7 +1526,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
});
|
||||
|
||||
describe("fetchPullRequestBranch", () => {
|
||||
effect("fetches a GitHub pull request ref into a local branch without checkout", () =>
|
||||
it.effect("fetches a GitHub pull request ref into a local branch without checkout", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const { initialBranch } = yield* initRepoWithCommit(tmp);
|
||||
@@ -1562,7 +1559,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
// ── Full flow: thread switching simulation ──
|
||||
|
||||
describe("full flow: thread switching (checkout toggling)", () => {
|
||||
effect("checkout a → checkout b → checkout a → current matches", () =>
|
||||
it.effect("checkout a → checkout b → checkout a → current matches", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1590,7 +1587,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
// ── Full flow: checkout conflict ──
|
||||
|
||||
describe("full flow: checkout conflict", () => {
|
||||
effect("uncommitted changes prevent checkout to a diverged branch", () =>
|
||||
it.effect("uncommitted changes prevent checkout to a diverged branch", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1624,7 +1621,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
});
|
||||
|
||||
describe("GitCore", () => {
|
||||
effect("supports branch lifecycle operations through the service API", () =>
|
||||
it.effect("supports branch lifecycle operations through the service API", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const core = yield* GitCore;
|
||||
@@ -1648,7 +1645,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect(
|
||||
it.effect(
|
||||
"reuses an existing remote when the target URL only differs by a trailing slash after .git",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
@@ -1669,7 +1666,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("reports status details and dirty state", () =>
|
||||
it.effect("reports status details and dirty state", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1685,7 +1682,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("returns a non-repo status for deleted directories", () =>
|
||||
it.effect("returns a non-repo status for deleted directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const deletedDir = path.join(tmp, "deleted-repo");
|
||||
@@ -1716,7 +1713,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("computes ahead count against base branch when no upstream is configured", () =>
|
||||
it.effect("computes ahead count against base branch when no upstream is configured", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1736,37 +1733,39 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("computes ahead count against origin/default when local default branch is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
it.effect(
|
||||
"computes ahead count against origin/default when local default branch is missing",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
|
||||
yield* initRepoWithCommit(source);
|
||||
const initialBranch = (yield* (yield* GitCore).listBranches({
|
||||
cwd: source,
|
||||
})).branches.find((branch) => branch.current)!.name;
|
||||
yield* git(source, ["remote", "add", "origin", remote]);
|
||||
yield* git(source, ["push", "-u", "origin", initialBranch]);
|
||||
yield* git(source, ["checkout", "-b", "feature/remote-base-only"]);
|
||||
yield* writeTextFile(
|
||||
path.join(source, "feature.txt"),
|
||||
`ahead of origin/${initialBranch}\n`,
|
||||
);
|
||||
yield* git(source, ["add", "feature.txt"]);
|
||||
yield* git(source, ["commit", "-m", "feature commit"]);
|
||||
yield* git(source, ["branch", "-D", initialBranch]);
|
||||
yield* initRepoWithCommit(source);
|
||||
const initialBranch = (yield* (yield* GitCore).listBranches({
|
||||
cwd: source,
|
||||
})).branches.find((branch) => branch.current)!.name;
|
||||
yield* git(source, ["remote", "add", "origin", remote]);
|
||||
yield* git(source, ["push", "-u", "origin", initialBranch]);
|
||||
yield* git(source, ["checkout", "-b", "feature/remote-base-only"]);
|
||||
yield* writeTextFile(
|
||||
path.join(source, "feature.txt"),
|
||||
`ahead of origin/${initialBranch}\n`,
|
||||
);
|
||||
yield* git(source, ["add", "feature.txt"]);
|
||||
yield* git(source, ["commit", "-m", "feature commit"]);
|
||||
yield* git(source, ["branch", "-D", initialBranch]);
|
||||
|
||||
const core = yield* GitCore;
|
||||
const details = yield* core.statusDetails(source);
|
||||
expect(details.branch).toBe("feature/remote-base-only");
|
||||
expect(details.hasUpstream).toBe(false);
|
||||
expect(details.aheadCount).toBe(1);
|
||||
expect(details.behindCount).toBe(0);
|
||||
}),
|
||||
const core = yield* GitCore;
|
||||
const details = yield* core.statusDetails(source);
|
||||
expect(details.branch).toBe("feature/remote-base-only");
|
||||
expect(details.hasUpstream).toBe(false);
|
||||
expect(details.aheadCount).toBe(1);
|
||||
expect(details.behindCount).toBe(0);
|
||||
}),
|
||||
);
|
||||
|
||||
effect(
|
||||
it.effect(
|
||||
"computes ahead count against a non-origin remote-prefixed gh-merge-base candidate",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
@@ -1804,7 +1803,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("skips push when no upstream is configured and branch is not ahead of base", () =>
|
||||
it.effect("skips push when no upstream is configured and branch is not ahead of base", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -1820,7 +1819,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("pushes with upstream setup when no comparable base branch exists", () =>
|
||||
it.effect("pushes with upstream setup when no comparable base branch exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir();
|
||||
@@ -1845,7 +1844,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("pushes with upstream setup to the only configured non-origin remote", () =>
|
||||
it.effect("pushes with upstream setup to the only configured non-origin remote", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir();
|
||||
@@ -1870,7 +1869,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect(
|
||||
it.effect(
|
||||
"pushes with upstream setup when comparable base exists but remote branch is missing",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
@@ -1906,7 +1905,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("prefers branch pushRemote over origin when setting upstream", () =>
|
||||
it.effect("prefers branch pushRemote over origin when setting upstream", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const origin = yield* makeTmpDir();
|
||||
@@ -1943,7 +1942,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect(
|
||||
it.effect(
|
||||
"pushes renamed PR worktree branches to their tracked upstream branch even when push.default is current",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
@@ -1990,7 +1989,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("pushes to the tracked upstream when the remote name contains slashes", () =>
|
||||
it.effect("pushes to the tracked upstream when the remote name contains slashes", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir();
|
||||
@@ -2031,7 +2030,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("includes command context when worktree removal fails", () =>
|
||||
it.effect("includes command context when worktree removal fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -2052,38 +2051,46 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("refreshes upstream before statusDetails so behind count reflects remote updates", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
const clone = yield* makeTmpDir();
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
it.effect(
|
||||
"refreshes upstream before statusDetails so behind count reflects remote updates",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
const clone = yield* makeTmpDir();
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
|
||||
yield* initRepoWithCommit(source);
|
||||
const initialBranch = (yield* (yield* GitCore).listBranches({
|
||||
cwd: source,
|
||||
})).branches.find((branch) => branch.current)!.name;
|
||||
yield* git(source, ["remote", "add", "origin", remote]);
|
||||
yield* git(source, ["push", "-u", "origin", initialBranch]);
|
||||
yield* initRepoWithCommit(source);
|
||||
const initialBranch = (yield* (yield* GitCore).listBranches({
|
||||
cwd: source,
|
||||
})).branches.find((branch) => branch.current)!.name;
|
||||
yield* git(source, ["remote", "add", "origin", remote]);
|
||||
yield* git(source, ["push", "-u", "origin", initialBranch]);
|
||||
|
||||
yield* git(clone, ["clone", remote, "."]);
|
||||
yield* git(clone, ["config", "user.email", "[email protected]"]);
|
||||
yield* git(clone, ["config", "user.name", "Test"]);
|
||||
yield* git(clone, ["checkout", "-B", initialBranch, "--track", `origin/${initialBranch}`]);
|
||||
yield* writeTextFile(path.join(clone, "CHANGELOG.md"), "remote change\n");
|
||||
yield* git(clone, ["add", "CHANGELOG.md"]);
|
||||
yield* git(clone, ["commit", "-m", "remote update"]);
|
||||
yield* git(clone, ["push", "origin", initialBranch]);
|
||||
yield* git(clone, ["clone", remote, "."]);
|
||||
yield* git(clone, ["config", "user.email", "[email protected]"]);
|
||||
yield* git(clone, ["config", "user.name", "Test"]);
|
||||
yield* git(clone, [
|
||||
"checkout",
|
||||
"-B",
|
||||
initialBranch,
|
||||
"--track",
|
||||
`origin/${initialBranch}`,
|
||||
]);
|
||||
yield* writeTextFile(path.join(clone, "CHANGELOG.md"), "remote change\n");
|
||||
yield* git(clone, ["add", "CHANGELOG.md"]);
|
||||
yield* git(clone, ["commit", "-m", "remote update"]);
|
||||
yield* git(clone, ["push", "origin", initialBranch]);
|
||||
|
||||
const core = yield* GitCore;
|
||||
const details = yield* core.statusDetails(source);
|
||||
expect(details.branch).toBe(initialBranch);
|
||||
expect(details.aheadCount).toBe(0);
|
||||
expect(details.behindCount).toBe(1);
|
||||
}),
|
||||
const core = yield* GitCore;
|
||||
const details = yield* core.statusDetails(source);
|
||||
expect(details.branch).toBe(initialBranch);
|
||||
expect(details.aheadCount).toBe(0);
|
||||
expect(details.behindCount).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
effect("prepares commit context by auto-staging and creates commit", () =>
|
||||
it.effect("prepares commit context by auto-staging and creates commit", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -2101,7 +2108,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("prepareCommitContext stages only selected files when filePaths provided", () =>
|
||||
it.effect("prepareCommitContext stages only selected files when filePaths provided", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -2124,7 +2131,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("prepareCommitContext stages everything when filePaths is undefined", () =>
|
||||
it.effect("prepareCommitContext stages everything when filePaths is undefined", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -2140,7 +2147,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("prepareCommitContext truncates oversized staged patches instead of failing", () =>
|
||||
it.effect("prepareCommitContext truncates oversized staged patches instead of failing", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -2155,7 +2162,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("readRangeContext truncates oversized diff patches instead of failing", () =>
|
||||
it.effect("readRangeContext truncates oversized diff patches instead of failing", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const { initialBranch } = yield* initRepoWithCommit(tmp);
|
||||
@@ -2174,7 +2181,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("pushes with upstream setup and then skips when up to date", () =>
|
||||
it.effect("pushes with upstream setup and then skips when up to date", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir();
|
||||
@@ -2202,7 +2209,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("pulls behind branch and then reports up-to-date", () =>
|
||||
it.effect("pulls behind branch and then reports up-to-date", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
@@ -2234,7 +2241,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("top-level pullGitBranch rejects when no upstream exists", () =>
|
||||
it.effect("top-level pullGitBranch rejects when no upstream exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -2246,7 +2253,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("lists branches when recency lookup fails", () =>
|
||||
it.effect("lists branches when recency lookup fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
@@ -2276,7 +2283,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
effect("falls back to empty remote branch data when remote lookups fail", () =>
|
||||
it.effect("falls back to empty remote branch data when remote lookups fail", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir();
|
||||
|
||||
@@ -49,16 +49,16 @@ const makeRoutingTextGeneration = Effect.gen(function* () {
|
||||
const codex = yield* CodexTextGen;
|
||||
const claude = yield* ClaudeTextGen;
|
||||
const cursor = yield* CursorTextGen;
|
||||
const opencode = yield* OpenCodeTextGen;
|
||||
const openCode = yield* OpenCodeTextGen;
|
||||
|
||||
const providerToService = {
|
||||
codex,
|
||||
claudeAgent: claude,
|
||||
cursor,
|
||||
opencode,
|
||||
};
|
||||
|
||||
const route = (provider: TextGenerationProvider | "opencode") => providerToService[provider];
|
||||
const route = (provider?: TextGenerationProvider): TextGenerationShape =>
|
||||
provider === "claudeAgent"
|
||||
? claude
|
||||
: provider === "opencode"
|
||||
? openCode
|
||||
: provider === "cursor"
|
||||
? cursor
|
||||
: codex;
|
||||
|
||||
return {
|
||||
generateCommitMessage: (input) =>
|
||||
|
||||
@@ -13,7 +13,7 @@ import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
|
||||
import type { TextGenerationError } from "@t3tools/contracts";
|
||||
|
||||
/** Providers that support git text generation (commit messages, PR content, branch names). */
|
||||
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor";
|
||||
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "opencode";
|
||||
|
||||
export interface CommitMessageGenerationInput {
|
||||
cwd: string;
|
||||
|
||||
@@ -153,7 +153,7 @@ async function waitForThread(
|
||||
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
||||
activities: ReadonlyArray<{ kind: string }>;
|
||||
}) => boolean,
|
||||
timeoutMs = 30_000,
|
||||
timeoutMs = 15_000,
|
||||
) {
|
||||
const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
|
||||
const poll = async (): Promise<{
|
||||
@@ -178,7 +178,7 @@ async function waitForThread(
|
||||
async function waitForEvent(
|
||||
engine: OrchestrationEngineShape,
|
||||
predicate: (event: { type: string }) => boolean,
|
||||
timeoutMs = 30_000,
|
||||
timeoutMs = 15_000,
|
||||
) {
|
||||
const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
|
||||
const poll = async () => {
|
||||
@@ -229,7 +229,7 @@ function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string {
|
||||
return runGit(cwd, ["show", `${ref}:${filePath}`]);
|
||||
}
|
||||
|
||||
async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 30_000) {
|
||||
async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 15_000) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const poll = async (): Promise<void> => {
|
||||
if (gitRefExists(cwd, ref)) {
|
||||
@@ -245,9 +245,6 @@ async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 30_000)
|
||||
}
|
||||
|
||||
describe("CheckpointReactor", () => {
|
||||
const LONG_TEST_TIMEOUT_MS = 30_000;
|
||||
const test = (name: string, run: () => Promise<void>, timeout = LONG_TEST_TIMEOUT_MS) =>
|
||||
it(name, run, timeout);
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
| OrchestrationEngineService
|
||||
| CheckpointReactor
|
||||
@@ -450,7 +447,7 @@ describe("CheckpointReactor", () => {
|
||||
};
|
||||
}
|
||||
|
||||
test("captures pre-turn baseline on turn.started and post-turn checkpoint on turn.completed", async () => {
|
||||
it("captures pre-turn baseline on turn.started and post-turn checkpoint on turn.completed", async () => {
|
||||
const harness = await createHarness({ seedFilesystemCheckpoints: false });
|
||||
const createdAt = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
@@ -700,7 +697,7 @@ describe("CheckpointReactor", () => {
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
});
|
||||
|
||||
test("captures pre-turn and completion checkpoints for claude runtime events", async () => {
|
||||
it("captures pre-turn and completion checkpoints for claude runtime events", async () => {
|
||||
const harness = await createHarness({
|
||||
seedFilesystemCheckpoints: false,
|
||||
providerName: ProviderDriverKind.make("claudeAgent"),
|
||||
@@ -761,7 +758,7 @@ describe("CheckpointReactor", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("appends capture failure activity when turn diff summary cannot be derived", async () => {
|
||||
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
|
||||
const harness = await createHarness({ seedFilesystemCheckpoints: false });
|
||||
const createdAt = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
@@ -808,7 +805,7 @@ describe("CheckpointReactor", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("captures pre-turn baseline from project workspace root when thread worktree is unset", async () => {
|
||||
it("captures pre-turn baseline from project workspace root when thread worktree is unset", async () => {
|
||||
const harness = await createHarness({
|
||||
hasSession: false,
|
||||
seedFilesystemCheckpoints: false,
|
||||
@@ -845,7 +842,7 @@ describe("CheckpointReactor", () => {
|
||||
).toBe("v1\n");
|
||||
});
|
||||
|
||||
test("captures turn completion checkpoint from project workspace root when provider session cwd is unavailable", async () => {
|
||||
it("captures turn completion checkpoint from project workspace root when provider session cwd is unavailable", async () => {
|
||||
const harness = await createHarness({
|
||||
hasSession: false,
|
||||
seedFilesystemCheckpoints: false,
|
||||
@@ -896,7 +893,7 @@ describe("CheckpointReactor", () => {
|
||||
).toBe("v2\n");
|
||||
});
|
||||
|
||||
test("ignores non-v2 checkpoint.captured runtime events", async () => {
|
||||
it("ignores non-v2 checkpoint.captured runtime events", async () => {
|
||||
const harness = await createHarness();
|
||||
const createdAt = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
@@ -938,7 +935,7 @@ describe("CheckpointReactor", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("continues processing runtime events after a single checkpoint runtime failure", async () => {
|
||||
it("continues processing runtime events after a single checkpoint runtime failure", async () => {
|
||||
const nonRepositorySessionCwd = fs.mkdtempSync(
|
||||
path.join(os.tmpdir(), "t3-checkpoint-runtime-non-repo-"),
|
||||
);
|
||||
@@ -998,7 +995,7 @@ describe("CheckpointReactor", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("executes provider revert and emits thread.reverted for checkpoint revert requests", async () => {
|
||||
it("executes provider revert and emits thread.reverted for checkpoint revert requests", async () => {
|
||||
const harness = await createHarness();
|
||||
const createdAt = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
@@ -1079,7 +1076,7 @@ describe("CheckpointReactor", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("executes provider revert and emits thread.reverted for claude sessions", async () => {
|
||||
it("executes provider revert and emits thread.reverted for claude sessions", async () => {
|
||||
const harness = await createHarness({ providerName: "claudeAgent" });
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
@@ -1148,7 +1145,7 @@ describe("CheckpointReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("processes consecutive revert requests with deterministic rollback sequencing", async () => {
|
||||
it("processes consecutive revert requests with deterministic rollback sequencing", async () => {
|
||||
const harness = await createHarness();
|
||||
const createdAt = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
@@ -1231,7 +1228,7 @@ describe("CheckpointReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("appends an error activity when revert is requested without an active session", async () => {
|
||||
it("appends an error activity when revert is requested without an active session", async () => {
|
||||
const harness = await createHarness({ hasSession: false });
|
||||
const createdAt = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Deferred, Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
|
||||
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { deriveServerPaths, ServerConfig } from "../../config.ts";
|
||||
@@ -538,59 +538,6 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
|
||||
it("records session lastError and clears active turn when provider turn start fails", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.sendTurn.mockImplementation(
|
||||
() =>
|
||||
Effect.fail(
|
||||
new ProviderAdapterRequestError({
|
||||
provider: "cursor",
|
||||
method: "session/set_config_option",
|
||||
detail: 'Invalid value for session config option "model"',
|
||||
}),
|
||||
) as never,
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-session-error"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-session-error"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return (
|
||||
thread?.session?.lastError ===
|
||||
'Provider adapter request failed (cursor) for session/set_config_option: Invalid value for session config option "model"' &&
|
||||
thread?.session?.status === "ready" &&
|
||||
thread?.session?.activeTurnId === null
|
||||
);
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session).toMatchObject({
|
||||
status: "ready",
|
||||
activeTurnId: null,
|
||||
lastError:
|
||||
'Provider adapter request failed (cursor) for session/set_config_option: Invalid value for session config option "model"',
|
||||
});
|
||||
});
|
||||
|
||||
it("generates a thread title on the first turn", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
@@ -1915,63 +1862,6 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("switches cursor model in-session without restarting", async () => {
|
||||
const harness = await createHarness({
|
||||
threadModelSelection: { provider: "cursor", model: "composer-2" },
|
||||
});
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-cursor-model-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-cursor-model-1"),
|
||||
role: "user",
|
||||
text: "first cursor turn",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: { provider: "cursor", model: "composer-2" },
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-cursor-model-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-cursor-model-2"),
|
||||
role: "user",
|
||||
text: "second cursor turn",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: {
|
||||
provider: "cursor",
|
||||
model: "composer-2",
|
||||
options: { fastMode: true },
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||
|
||||
expect(harness.startSession.mock.calls.length).toBe(1);
|
||||
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
||||
modelSelection: { provider: "cursor", model: "composer-2", options: { fastMode: true } },
|
||||
});
|
||||
});
|
||||
|
||||
it("restarts the provider session when runtime mode is updated on the thread", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
@@ -2346,30 +2236,37 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves provider method context when turn start fails", async () => {
|
||||
it("starts a fresh session when only projected session state exists", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
harness.sendTurn.mockImplementation(
|
||||
() =>
|
||||
Effect.fail(
|
||||
new ProviderAdapterRequestError({
|
||||
provider: "cursor",
|
||||
method: "session/set_config_option",
|
||||
detail: "Invalid cursor/set_config_option payload: Expected string, got null",
|
||||
}),
|
||||
) as never,
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-set-stale"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-provider-error"),
|
||||
commandId: CommandId.make("cmd-turn-start-stale"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-provider-error"),
|
||||
messageId: asMessageId("user-message-stale"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
text: "resume codex",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
@@ -2378,73 +2275,19 @@ describe("ProviderCommandReactor", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
false
|
||||
);
|
||||
});
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(
|
||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
).toMatchObject({
|
||||
payload: {
|
||||
detail: expect.stringContaining(
|
||||
"Provider adapter request failed (cursor) for session/set_config_option",
|
||||
),
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the full rendered cause for non-adapter turn start failures", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.sendTurn.mockImplementation(
|
||||
() =>
|
||||
Effect.fail(
|
||||
new Error("Invalid params", { cause: new Error("session/prompt failed") }),
|
||||
) as never,
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-raw-error"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-raw-error"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(
|
||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
).toMatchObject({
|
||||
payload: {
|
||||
detail: expect.stringContaining("session/prompt failed"),
|
||||
},
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2560,60 +2403,6 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("processes approval responses while a provider turn is still in flight", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
const unblockSendTurn = Effect.runSync(Deferred.make<void>());
|
||||
|
||||
harness.sendTurn.mockImplementation(() =>
|
||||
Deferred.await(unblockSendTurn).pipe(
|
||||
Effect.as({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-blocked-approval"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-blocked-approval"),
|
||||
role: "user",
|
||||
text: "need approval while turn is running",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.make("cmd-approval-respond-during-send-turn"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
requestId: asApprovalRequestId("approval-request-while-send-turn-blocked"),
|
||||
decision: "acceptForSession",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.respondToRequest.mock.calls.length === 1);
|
||||
expect(harness.respondToRequest.mock.calls[0]?.[0]).toEqual({
|
||||
threadId: "thread-1",
|
||||
requestId: "approval-request-while-send-turn-blocked",
|
||||
decision: "acceptForSession",
|
||||
});
|
||||
|
||||
await Effect.runPromise(Deferred.succeed(unblockSendTurn, undefined));
|
||||
});
|
||||
|
||||
it("reacts to thread.user-input.respond by forwarding structured user input answers", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
@@ -183,7 +183,7 @@ function findProviderAdapterRequestError(
|
||||
|
||||
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
|
||||
const error = findProviderAdapterRequestError(cause);
|
||||
if (Schema.is(ProviderAdapterRequestError)(error)) {
|
||||
if (error) {
|
||||
const detail = error.detail.toLowerCase();
|
||||
return (
|
||||
detail.includes("unknown pending approval request") ||
|
||||
@@ -199,7 +199,7 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
|
||||
|
||||
function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
|
||||
const error = findProviderAdapterRequestError(cause);
|
||||
if (Schema.is(ProviderAdapterRequestError)(error)) {
|
||||
if (error) {
|
||||
return error.detail.toLowerCase().includes("unknown pending user-input request");
|
||||
}
|
||||
const message = Cause.pretty(cause).toLowerCase();
|
||||
@@ -314,7 +314,7 @@ const make = Effect.gen(function* () {
|
||||
? failReason.error
|
||||
: undefined;
|
||||
if (providerError) {
|
||||
return providerError.message;
|
||||
return providerError.detail;
|
||||
}
|
||||
return Cause.pretty(cause);
|
||||
};
|
||||
@@ -594,9 +594,6 @@ const make = Effect.gen(function* () {
|
||||
thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null;
|
||||
if (existingSessionThreadId) {
|
||||
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
|
||||
const providerChanged =
|
||||
requestedModelSelection !== undefined &&
|
||||
requestedModelSelection.provider !== currentProvider;
|
||||
const sessionModelSwitch =
|
||||
currentProvider === undefined
|
||||
? "in-session"
|
||||
@@ -616,14 +613,15 @@ const make = Effect.gen(function* () {
|
||||
|
||||
if (
|
||||
!runtimeModeChanged &&
|
||||
!providerChanged &&
|
||||
!shouldRestartForModelChange &&
|
||||
!shouldRestartForModelSelectionChange
|
||||
) {
|
||||
return existingSessionThreadId;
|
||||
}
|
||||
|
||||
const resumeCursor = providerChanged ? undefined : (activeSession?.resumeCursor ?? undefined);
|
||||
const resumeCursor = shouldRestartForModelChange
|
||||
? undefined
|
||||
: (activeSession?.resumeCursor ?? undefined);
|
||||
yield* Effect.logInfo("provider command reactor restarting provider session", {
|
||||
threadId,
|
||||
existingSessionThreadId,
|
||||
@@ -634,7 +632,6 @@ const make = Effect.gen(function* () {
|
||||
currentRuntimeMode: thread.session?.runtimeMode,
|
||||
desiredRuntimeMode: thread.runtimeMode,
|
||||
runtimeModeChanged,
|
||||
providerChanged,
|
||||
modelChanged,
|
||||
instanceChanged,
|
||||
shouldRestartForModelChange,
|
||||
@@ -1055,6 +1052,9 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
const handleTurnStartFailure = (cause: Cause.Cause<unknown>) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.void;
|
||||
}
|
||||
const detail = formatFailureDetail(cause);
|
||||
return setThreadSessionErrorOnTurnStartFailure({
|
||||
threadId: event.payload.threadId,
|
||||
@@ -1071,9 +1071,22 @@ const make = Effect.gen(function* () {
|
||||
createdAt: event.payload.createdAt,
|
||||
}),
|
||||
),
|
||||
Effect.asVoid,
|
||||
);
|
||||
};
|
||||
|
||||
const recoverTurnStartFailure = (cause: Cause.Cause<unknown>) =>
|
||||
handleTurnStartFailure(cause).pipe(
|
||||
Effect.catchCause((recoveryCause) =>
|
||||
Effect.logWarning("provider command reactor failed to recover turn start failure", {
|
||||
eventType: event.type,
|
||||
threadId: event.payload.threadId,
|
||||
cause: Cause.pretty(recoveryCause),
|
||||
originalCause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const sendTurnRequest = yield* buildSendTurnRequestForThread({
|
||||
threadId: event.payload.threadId,
|
||||
messageText: message.text,
|
||||
@@ -1094,7 +1107,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
yield* providerService
|
||||
.sendTurn(sendTurnRequest.value)
|
||||
.pipe(Effect.catchCause(handleTurnStartFailure), Effect.forkScoped);
|
||||
.pipe(Effect.catchCause(recoverTurnStartFailure), Effect.forkScoped);
|
||||
});
|
||||
|
||||
const processTurnInterruptRequested = Effect.fn("processTurnInterruptRequested")(function* (
|
||||
|
||||
@@ -12,7 +12,6 @@ import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Result from "effect/Result";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { resolveApiModelId } from "@t3tools/shared/model";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
import {
|
||||
query as claudeQuery,
|
||||
@@ -377,50 +376,13 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo
|
||||
);
|
||||
}
|
||||
|
||||
function buildInitialClaudeProviderSnapshot(claudeSettings: ClaudeSettings): ServerProvider {
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(
|
||||
BUILT_IN_MODELS,
|
||||
PROVIDER,
|
||||
claudeSettings.customModels,
|
||||
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
|
||||
);
|
||||
|
||||
if (!claudeSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
slashCommands: [],
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Claude is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: true,
|
||||
checkedAt,
|
||||
models,
|
||||
slashCommands: [],
|
||||
probe: {
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Checking Claude availability...",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveClaudeApiModelId(modelSelection: ClaudeModelSelection): string {
|
||||
return resolveApiModelId(modelSelection);
|
||||
switch (modelSelection.options?.contextWindow) {
|
||||
case "1m":
|
||||
return `${modelSelection.model}[1m]`;
|
||||
default:
|
||||
return modelSelection.model;
|
||||
}
|
||||
}
|
||||
|
||||
function toTitleCaseWords(value: string): string {
|
||||
@@ -1002,7 +964,7 @@ export const ClaudeProviderLive = Layer.effect(
|
||||
Stream.map((settings) => settings.providers.claudeAgent),
|
||||
),
|
||||
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
|
||||
buildInitialSnapshot: buildInitialClaudeProviderSnapshot,
|
||||
initialSnapshot: makePendingClaudeProvider,
|
||||
checkProvider,
|
||||
});
|
||||
}),
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
type CursorModelOptions,
|
||||
EventId,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderInteractionMode,
|
||||
@@ -23,12 +24,17 @@ import {
|
||||
DateTime,
|
||||
Deferred,
|
||||
Effect,
|
||||
Exit,
|
||||
Fiber,
|
||||
FileSystem,
|
||||
Layer,
|
||||
Queue,
|
||||
Option,
|
||||
PubSub,
|
||||
Random,
|
||||
Scope,
|
||||
Semaphore,
|
||||
Stream,
|
||||
SynchronizedRef,
|
||||
} from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
@@ -118,6 +124,7 @@ interface PendingUserInput {
|
||||
interface CursorSessionContext {
|
||||
readonly threadId: ThreadId;
|
||||
session: ProviderSession;
|
||||
readonly scope: Scope.Closeable;
|
||||
readonly acp: AcpSessionRuntimeShape;
|
||||
notificationFiber: Fiber.Fiber<void, never> | undefined;
|
||||
readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;
|
||||
@@ -237,6 +244,55 @@ function resolveRequestedModeId(input: {
|
||||
);
|
||||
}
|
||||
|
||||
function applyRequestedSessionConfiguration<E>(input: {
|
||||
readonly runtime: AcpSessionRuntimeShape;
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
readonly interactionMode: ProviderInteractionMode | undefined;
|
||||
readonly modelSelection:
|
||||
| {
|
||||
readonly model: string;
|
||||
readonly options?: CursorModelOptions | null | undefined;
|
||||
}
|
||||
| undefined;
|
||||
readonly mapError: (context: {
|
||||
readonly cause: import("effect-acp/errors").AcpError;
|
||||
readonly method: "session/set_config_option" | "session/set_mode";
|
||||
}) => E;
|
||||
}): Effect.Effect<void, E> {
|
||||
return Effect.gen(function* () {
|
||||
if (input.modelSelection) {
|
||||
yield* applyCursorAcpModelSelection({
|
||||
runtime: input.runtime,
|
||||
model: input.modelSelection.model,
|
||||
modelOptions: input.modelSelection.options,
|
||||
mapError: ({ cause }) =>
|
||||
input.mapError({
|
||||
cause,
|
||||
method: "session/set_config_option",
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
const requestedModeId = resolveRequestedModeId({
|
||||
interactionMode: input.interactionMode,
|
||||
runtimeMode: input.runtimeMode,
|
||||
modeState: yield* input.runtime.getModeState,
|
||||
});
|
||||
if (!requestedModeId) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* input.runtime.setMode(requestedModeId).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
input.mapError({
|
||||
cause,
|
||||
method: "session/set_mode",
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function selectAutoApprovedPermissionOption(
|
||||
request: EffectAcpSchema.RequestPermissionRequest,
|
||||
): string | undefined {
|
||||
@@ -271,9 +327,12 @@ export function makeCursorAdapter(
|
||||
stream: "native",
|
||||
})
|
||||
: undefined);
|
||||
const managedNativeEventLogger =
|
||||
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
|
||||
|
||||
const sessions = new Map<ThreadId, CursorSessionContext>();
|
||||
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
const threadLocksRef = yield* SynchronizedRef.make(new Map<string, Semaphore.Semaphore>());
|
||||
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
|
||||
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
const randomUUIDv4 = crypto.randomUUIDv4.pipe(
|
||||
@@ -301,7 +360,28 @@ export function makeCursorAdapter(
|
||||
);
|
||||
|
||||
const offerRuntimeEvent = (event: ProviderRuntimeEvent) =>
|
||||
Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid);
|
||||
PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid);
|
||||
|
||||
const getThreadSemaphore = (threadId: string) =>
|
||||
SynchronizedRef.modifyEffect(threadLocksRef, (current) => {
|
||||
const existing: Option.Option<Semaphore.Semaphore> = Option.fromNullishOr(
|
||||
current.get(threadId),
|
||||
);
|
||||
return Option.match(existing, {
|
||||
onNone: () =>
|
||||
Semaphore.make(1).pipe(
|
||||
Effect.map((semaphore) => {
|
||||
const next = new Map(current);
|
||||
next.set(threadId, semaphore);
|
||||
return [semaphore, next] as const;
|
||||
}),
|
||||
),
|
||||
onSome: (semaphore) => Effect.succeed([semaphore, current] as const),
|
||||
});
|
||||
});
|
||||
|
||||
const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>
|
||||
Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));
|
||||
|
||||
const logNative = (
|
||||
threadId: ThreadId,
|
||||
@@ -383,7 +463,7 @@ export function makeCursorAdapter(
|
||||
if (ctx.notificationFiber) {
|
||||
yield* Fiber.interrupt(ctx.notificationFiber);
|
||||
}
|
||||
yield* Effect.ignore(ctx.acp.close);
|
||||
yield* Effect.ignore(Scope.close(ctx.scope, Exit.void));
|
||||
sessions.delete(ctx.threadId);
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.exited",
|
||||
@@ -395,355 +475,395 @@ export function makeCursorAdapter(
|
||||
});
|
||||
|
||||
const startSession: CursorAdapterShape["startSession"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
if (input.provider !== undefined && input.provider !== PROVIDER) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "startSession",
|
||||
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
|
||||
});
|
||||
}
|
||||
if (!input.cwd?.trim()) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "startSession",
|
||||
issue: "cwd is required and must be non-empty.",
|
||||
});
|
||||
}
|
||||
withThreadLock(
|
||||
input.threadId,
|
||||
Effect.gen(function* () {
|
||||
if (input.provider !== undefined && input.provider !== PROVIDER) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "startSession",
|
||||
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
|
||||
});
|
||||
}
|
||||
if (!input.cwd?.trim()) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "startSession",
|
||||
issue: "cwd is required and must be non-empty.",
|
||||
});
|
||||
}
|
||||
|
||||
const cwd = nodePath.resolve(input.cwd.trim());
|
||||
const cursorModelSelection =
|
||||
input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined;
|
||||
const existing = sessions.get(input.threadId);
|
||||
if (existing && !existing.stopped) {
|
||||
yield* stopSessionInternal(existing);
|
||||
}
|
||||
const cwd = nodePath.resolve(input.cwd.trim());
|
||||
const cursorModelSelection =
|
||||
input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined;
|
||||
const existing = sessions.get(input.threadId);
|
||||
if (existing && !existing.stopped) {
|
||||
yield* stopSessionInternal(existing);
|
||||
}
|
||||
|
||||
const cursorSettings = yield* serverSettingsService.getSettings.pipe(
|
||||
Effect.map((settings) => settings.providers.cursor),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
detail: error.message,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
|
||||
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
|
||||
let ctx!: CursorSessionContext;
|
||||
|
||||
const resumeSessionId = parseCursorResume(input.resumeCursor)?.sessionId;
|
||||
const acpNativeLoggers = makeAcpNativeLoggers({
|
||||
nativeEventLogger,
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
});
|
||||
|
||||
const acp = yield* makeCursorAcpRuntime({
|
||||
cursorSettings,
|
||||
childProcessSpawner,
|
||||
cwd,
|
||||
...(resumeSessionId ? { resumeSessionId } : {}),
|
||||
clientInfo: { name: "t3-code", version: "0.0.0" },
|
||||
...acpNativeLoggers,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const started = yield* Effect.gen(function* () {
|
||||
yield* acp.handleExtRequest("cursor/ask_question", CursorAskQuestionRequest, (params) =>
|
||||
Effect.gen(function* () {
|
||||
yield* logNative(
|
||||
input.threadId,
|
||||
"cursor/ask_question",
|
||||
params,
|
||||
"acp.cursor.extension",
|
||||
);
|
||||
const requestId = ApprovalRequestId.make(crypto.randomUUID());
|
||||
const runtimeRequestId = RuntimeRequestId.make(requestId);
|
||||
const answers = yield* Deferred.make<ProviderUserInputAnswers>();
|
||||
pendingUserInputs.set(requestId, { answers });
|
||||
yield* offerRuntimeEvent({
|
||||
type: "user-input.requested",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { questions: extractAskQuestions(params) },
|
||||
raw: {
|
||||
source: "acp.cursor.extension",
|
||||
method: "cursor/ask_question",
|
||||
payload: params,
|
||||
},
|
||||
});
|
||||
const resolved = yield* Deferred.await(answers);
|
||||
pendingUserInputs.delete(requestId);
|
||||
yield* offerRuntimeEvent({
|
||||
type: "user-input.resolved",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { answers: resolved },
|
||||
});
|
||||
return { answers: resolved };
|
||||
}),
|
||||
const cursorSettings = yield* serverSettingsService.getSettings.pipe(
|
||||
Effect.map((settings) => settings.providers.cursor),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
detail: error.message,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* acp.handleExtRequest("cursor/create_plan", CursorCreatePlanRequest, (params) =>
|
||||
Effect.gen(function* () {
|
||||
yield* logNative(
|
||||
input.threadId,
|
||||
"cursor/create_plan",
|
||||
params,
|
||||
"acp.cursor.extension",
|
||||
);
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.proposed.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
payload: { planMarkdown: extractPlanMarkdown(params) },
|
||||
raw: {
|
||||
source: "acp.cursor.extension",
|
||||
method: "cursor/create_plan",
|
||||
payload: params,
|
||||
},
|
||||
});
|
||||
return { accepted: true } as const;
|
||||
}),
|
||||
|
||||
const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
|
||||
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
|
||||
const sessionScope = yield* Scope.make("sequential");
|
||||
let sessionScopeTransferred = false;
|
||||
yield* Effect.addFinalizer(() =>
|
||||
sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void),
|
||||
);
|
||||
yield* acp.handleExtNotification(
|
||||
"cursor/update_todos",
|
||||
CursorUpdateTodosRequest,
|
||||
(params) =>
|
||||
let ctx!: CursorSessionContext;
|
||||
|
||||
const resumeSessionId = parseCursorResume(input.resumeCursor)?.sessionId;
|
||||
const acpNativeLoggers = makeAcpNativeLoggers({
|
||||
nativeEventLogger,
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
});
|
||||
|
||||
const acp = yield* makeCursorAcpRuntime({
|
||||
cursorSettings,
|
||||
childProcessSpawner,
|
||||
cwd,
|
||||
...(resumeSessionId ? { resumeSessionId } : {}),
|
||||
clientInfo: { name: "t3-code", version: "0.0.0" },
|
||||
...acpNativeLoggers,
|
||||
}).pipe(
|
||||
Effect.provideService(Scope.Scope, sessionScope),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const started = yield* Effect.gen(function* () {
|
||||
yield* acp.handleExtRequest("cursor/ask_question", CursorAskQuestionRequest, (params) =>
|
||||
Effect.gen(function* () {
|
||||
yield* logNative(
|
||||
input.threadId,
|
||||
"cursor/update_todos",
|
||||
"cursor/ask_question",
|
||||
params,
|
||||
"acp.cursor.extension",
|
||||
);
|
||||
if (ctx) {
|
||||
yield* emitPlanUpdate(
|
||||
ctx,
|
||||
extractTodosAsPlan(params),
|
||||
const requestId = ApprovalRequestId.make(crypto.randomUUID());
|
||||
const runtimeRequestId = RuntimeRequestId.make(requestId);
|
||||
const answers = yield* Deferred.make<ProviderUserInputAnswers>();
|
||||
pendingUserInputs.set(requestId, { answers });
|
||||
yield* offerRuntimeEvent({
|
||||
type: "user-input.requested",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { questions: extractAskQuestions(params) },
|
||||
raw: {
|
||||
source: "acp.cursor.extension",
|
||||
method: "cursor/ask_question",
|
||||
payload: params,
|
||||
},
|
||||
});
|
||||
const resolved = yield* Deferred.await(answers);
|
||||
pendingUserInputs.delete(requestId);
|
||||
yield* offerRuntimeEvent({
|
||||
type: "user-input.resolved",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { answers: resolved },
|
||||
});
|
||||
return { answers: resolved };
|
||||
}),
|
||||
);
|
||||
yield* acp.handleExtRequest("cursor/create_plan", CursorCreatePlanRequest, (params) =>
|
||||
Effect.gen(function* () {
|
||||
yield* logNative(
|
||||
input.threadId,
|
||||
"cursor/create_plan",
|
||||
params,
|
||||
"acp.cursor.extension",
|
||||
);
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.proposed.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
payload: { planMarkdown: extractPlanMarkdown(params) },
|
||||
raw: {
|
||||
source: "acp.cursor.extension",
|
||||
method: "cursor/create_plan",
|
||||
payload: params,
|
||||
},
|
||||
});
|
||||
return { accepted: true } as const;
|
||||
}),
|
||||
);
|
||||
yield* acp.handleExtNotification(
|
||||
"cursor/update_todos",
|
||||
CursorUpdateTodosRequest,
|
||||
(params) =>
|
||||
Effect.gen(function* () {
|
||||
yield* logNative(
|
||||
input.threadId,
|
||||
"cursor/update_todos",
|
||||
params,
|
||||
"acp.cursor.extension",
|
||||
"cursor/update_todos",
|
||||
);
|
||||
if (ctx) {
|
||||
yield* emitPlanUpdate(
|
||||
ctx,
|
||||
extractTodosAsPlan(params),
|
||||
params,
|
||||
"acp.cursor.extension",
|
||||
"cursor/update_todos",
|
||||
);
|
||||
}
|
||||
}),
|
||||
);
|
||||
yield* acp.handleRequestPermission((params) =>
|
||||
Effect.gen(function* () {
|
||||
yield* logNative(
|
||||
input.threadId,
|
||||
"session/request_permission",
|
||||
params,
|
||||
"acp.jsonrpc",
|
||||
);
|
||||
if (input.runtimeMode === "full-access") {
|
||||
const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);
|
||||
if (autoApprovedOptionId !== undefined) {
|
||||
return {
|
||||
outcome: {
|
||||
outcome: "selected" as const,
|
||||
optionId: autoApprovedOptionId,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
const permissionRequest = parsePermissionRequest(params);
|
||||
const requestId = ApprovalRequestId.make(crypto.randomUUID());
|
||||
const runtimeRequestId = RuntimeRequestId.make(requestId);
|
||||
const decision = yield* Deferred.make<ProviderApprovalDecision>();
|
||||
pendingApprovals.set(requestId, {
|
||||
decision,
|
||||
kind: permissionRequest.kind,
|
||||
});
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestOpenedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
detail: permissionRequest.detail ?? JSON.stringify(params).slice(0, 2000),
|
||||
args: params,
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/request_permission",
|
||||
rawPayload: params,
|
||||
}),
|
||||
);
|
||||
const resolved = yield* Deferred.await(decision);
|
||||
pendingApprovals.delete(requestId);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestResolvedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
decision: resolved,
|
||||
}),
|
||||
);
|
||||
return {
|
||||
outcome:
|
||||
resolved === "cancel"
|
||||
? ({ outcome: "cancelled" } as const)
|
||||
: {
|
||||
outcome: "selected" as const,
|
||||
optionId: acpPermissionOutcome(resolved),
|
||||
},
|
||||
};
|
||||
}),
|
||||
);
|
||||
return yield* acp.start();
|
||||
}).pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/start", error),
|
||||
),
|
||||
);
|
||||
|
||||
yield* applyRequestedSessionConfiguration({
|
||||
runtime: acp,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: undefined,
|
||||
modelSelection: cursorModelSelection,
|
||||
mapError: ({ cause, method }) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
|
||||
});
|
||||
|
||||
const now = yield* nowIso;
|
||||
const session: ProviderSession = {
|
||||
provider: PROVIDER,
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
cwd,
|
||||
model: cursorModelSelection?.model,
|
||||
threadId: input.threadId,
|
||||
resumeCursor: {
|
||||
schemaVersion: CURSOR_RESUME_VERSION,
|
||||
sessionId: started.sessionId,
|
||||
},
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
ctx = {
|
||||
threadId: input.threadId,
|
||||
session,
|
||||
scope: sessionScope,
|
||||
acp,
|
||||
notificationFiber: undefined,
|
||||
pendingApprovals,
|
||||
pendingUserInputs,
|
||||
turns: [],
|
||||
lastPlanFingerprint: undefined,
|
||||
activeTurnId: undefined,
|
||||
stopped: false,
|
||||
};
|
||||
|
||||
const nf = yield* Stream.runDrain(
|
||||
Stream.mapEffect(acp.getEvents(), (event) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event._tag) {
|
||||
case "ModeChanged":
|
||||
return;
|
||||
case "AssistantItemStarted":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
itemId: event.itemId,
|
||||
lifecycle: "item.started",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "AssistantItemCompleted":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
itemId: event.itemId,
|
||||
lifecycle: "item.completed",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "PlanUpdated":
|
||||
yield* logNative(
|
||||
ctx.threadId,
|
||||
"session/update",
|
||||
event.rawPayload,
|
||||
"acp.jsonrpc",
|
||||
);
|
||||
yield* emitPlanUpdate(
|
||||
ctx,
|
||||
event.payload,
|
||||
event.rawPayload,
|
||||
"acp.jsonrpc",
|
||||
"session/update",
|
||||
);
|
||||
return;
|
||||
case "ToolCallUpdated":
|
||||
yield* logNative(
|
||||
ctx.threadId,
|
||||
"session/update",
|
||||
event.rawPayload,
|
||||
"acp.jsonrpc",
|
||||
);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpToolCallEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
toolCall: event.toolCall,
|
||||
rawPayload: event.rawPayload,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "ContentDelta":
|
||||
yield* logNative(
|
||||
ctx.threadId,
|
||||
"session/update",
|
||||
event.rawPayload,
|
||||
"acp.jsonrpc",
|
||||
);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpContentDeltaEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
...(event.itemId ? { itemId: event.itemId } : {}),
|
||||
text: event.text,
|
||||
rawPayload: event.rawPayload,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
}),
|
||||
);
|
||||
yield* acp.handleRequestPermission((params) =>
|
||||
Effect.gen(function* () {
|
||||
yield* logNative(input.threadId, "session/request_permission", params, "acp.jsonrpc");
|
||||
if (ctx?.session.runtimeMode === "full-access") {
|
||||
const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);
|
||||
if (autoApprovedOptionId !== undefined) {
|
||||
return {
|
||||
outcome: {
|
||||
outcome: "selected" as const,
|
||||
optionId: autoApprovedOptionId,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
const permissionRequest = parsePermissionRequest(params);
|
||||
const requestId = ApprovalRequestId.make(crypto.randomUUID());
|
||||
const runtimeRequestId = RuntimeRequestId.make(requestId);
|
||||
const decision = yield* Deferred.make<ProviderApprovalDecision>();
|
||||
pendingApprovals.set(requestId, {
|
||||
decision,
|
||||
kind: permissionRequest.kind,
|
||||
});
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestOpenedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
detail: permissionRequest.detail ?? JSON.stringify(params).slice(0, 2000),
|
||||
args: params,
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/request_permission",
|
||||
rawPayload: params,
|
||||
}),
|
||||
);
|
||||
const resolved = yield* Deferred.await(decision);
|
||||
pendingApprovals.delete(requestId);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestResolvedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
decision: resolved,
|
||||
}),
|
||||
);
|
||||
return {
|
||||
outcome:
|
||||
resolved === "cancel"
|
||||
? ({ outcome: "cancelled" } as const)
|
||||
: {
|
||||
outcome: "selected" as const,
|
||||
optionId: acpPermissionOutcome(resolved),
|
||||
},
|
||||
};
|
||||
}),
|
||||
);
|
||||
return yield* acp.start();
|
||||
}).pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/start", error),
|
||||
),
|
||||
);
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
const now = yield* nowIso;
|
||||
const session: ProviderSession = {
|
||||
provider: PROVIDER,
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
cwd,
|
||||
model: cursorModelSelection?.model,
|
||||
threadId: input.threadId,
|
||||
resumeCursor: {
|
||||
schemaVersion: CURSOR_RESUME_VERSION,
|
||||
sessionId: started.sessionId,
|
||||
},
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
ctx.notificationFiber = nf;
|
||||
sessions.set(input.threadId, ctx);
|
||||
sessionScopeTransferred = true;
|
||||
|
||||
ctx = {
|
||||
threadId: input.threadId,
|
||||
session,
|
||||
acp,
|
||||
notificationFiber: undefined,
|
||||
pendingApprovals,
|
||||
pendingUserInputs,
|
||||
turns: [],
|
||||
lastPlanFingerprint: undefined,
|
||||
activeTurnId: undefined,
|
||||
stopped: false,
|
||||
};
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
payload: { resume: started.initializeResult },
|
||||
});
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.state.changed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
payload: { state: "ready", reason: "Cursor ACP session ready" },
|
||||
});
|
||||
yield* offerRuntimeEvent({
|
||||
type: "thread.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
payload: { providerThreadId: started.sessionId },
|
||||
});
|
||||
|
||||
const nf = yield* Stream.runDrain(
|
||||
Stream.mapEffect(acp.events, (event) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event._tag) {
|
||||
case "ModeChanged":
|
||||
return;
|
||||
case "AssistantItemStarted":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
itemId: event.itemId,
|
||||
lifecycle: "item.started",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "AssistantItemCompleted":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
itemId: event.itemId,
|
||||
lifecycle: "item.completed",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "PlanUpdated":
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload, "acp.jsonrpc");
|
||||
yield* emitPlanUpdate(
|
||||
ctx,
|
||||
event.payload,
|
||||
event.rawPayload,
|
||||
"acp.jsonrpc",
|
||||
"session/update",
|
||||
);
|
||||
return;
|
||||
case "ToolCallUpdated":
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload, "acp.jsonrpc");
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpToolCallEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
toolCall: event.toolCall,
|
||||
rawPayload: event.rawPayload,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "ContentDelta":
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload, "acp.jsonrpc");
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpContentDeltaEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
...(event.itemId ? { itemId: event.itemId } : {}),
|
||||
text: event.text,
|
||||
rawPayload: event.rawPayload,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
ctx.notificationFiber = nf;
|
||||
sessions.set(input.threadId, ctx);
|
||||
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
payload: { resume: started.initializeResult },
|
||||
});
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.state.changed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
payload: { state: "ready", reason: "Cursor ACP session ready" },
|
||||
});
|
||||
yield* offerRuntimeEvent({
|
||||
type: "thread.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
payload: { providerThreadId: started.sessionId },
|
||||
});
|
||||
|
||||
return session;
|
||||
});
|
||||
return session;
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
const sendTurn: CursorAdapterShape["sendTurn"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -753,12 +873,19 @@ export function makeCursorAdapter(
|
||||
input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined;
|
||||
const model = turnModelSelection?.model ?? ctx.session.model;
|
||||
const resolvedModel = resolveCursorAcpBaseModelId(model);
|
||||
yield* applyCursorAcpModelSelection({
|
||||
yield* applyRequestedSessionConfiguration({
|
||||
runtime: ctx.acp,
|
||||
model,
|
||||
modelOptions: turnModelSelection?.options,
|
||||
mapError: ({ cause }) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_config_option", cause),
|
||||
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;
|
||||
@@ -768,23 +895,6 @@ export function makeCursorAdapter(
|
||||
updatedAt: yield* nowIso,
|
||||
};
|
||||
|
||||
const requestedModeId = resolveRequestedModeId({
|
||||
interactionMode: input.interactionMode,
|
||||
runtimeMode: ctx.session.runtimeMode,
|
||||
modeState: yield* ctx.acp.getModeState,
|
||||
});
|
||||
if (requestedModeId) {
|
||||
yield* Effect.ignore(
|
||||
ctx.acp
|
||||
.setMode(requestedModeId)
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_mode", error),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.started",
|
||||
...(yield* makeEventStamp()),
|
||||
@@ -907,6 +1017,7 @@ export function makeCursorAdapter(
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
|
||||
yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs);
|
||||
yield* Effect.ignore(
|
||||
ctx.acp.cancel.pipe(
|
||||
Effect.mapError((error) =>
|
||||
@@ -974,10 +1085,13 @@ export function makeCursorAdapter(
|
||||
});
|
||||
|
||||
const stopSession: CursorAdapterShape["stopSession"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
yield* stopSessionInternal(ctx);
|
||||
});
|
||||
withThreadLock(
|
||||
threadId,
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
yield* stopSessionInternal(ctx);
|
||||
}),
|
||||
);
|
||||
|
||||
const listSessions: CursorAdapterShape["listSessions"] = () =>
|
||||
Effect.sync(() => Array.from(sessions.values(), (c) => ({ ...c.session })));
|
||||
@@ -993,10 +1107,13 @@ export function makeCursorAdapter(
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.forEach(sessions.values(), stopSessionInternal, { discard: true }).pipe(
|
||||
Effect.tap(() => Queue.shutdown(runtimeEventQueue)),
|
||||
Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)),
|
||||
Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),
|
||||
),
|
||||
);
|
||||
|
||||
const streamEvents = Stream.fromPubSub(runtimeEventPubSub);
|
||||
|
||||
return {
|
||||
provider: PROVIDER,
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
@@ -1011,9 +1128,7 @@ export function makeCursorAdapter(
|
||||
listSessions,
|
||||
hasSession,
|
||||
stopAll,
|
||||
get streamEvents() {
|
||||
return Stream.fromQueue(runtimeEventQueue);
|
||||
},
|
||||
streamEvents,
|
||||
} satisfies CursorAdapterShape;
|
||||
});
|
||||
}
|
||||
@@ -1,9 +1,20 @@
|
||||
import * as path from "node:path";
|
||||
import * as os from "node:os";
|
||||
import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import type { CursorSettings, ServerProviderModel } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
buildCursorProviderSnapshot,
|
||||
buildCursorCapabilitiesFromConfigOptions,
|
||||
buildCursorDiscoveredModelsFromConfigOptions,
|
||||
discoverCursorModelCapabilitiesViaAcp,
|
||||
discoverCursorModelsViaAcp,
|
||||
getCursorFallbackModels,
|
||||
getCursorParameterizedModelPickerUnsupportedMessage,
|
||||
parseCursorAboutOutput,
|
||||
@@ -13,6 +24,37 @@ import {
|
||||
resolveCursorAcpConfigUpdates,
|
||||
} from "./CursorProvider.ts";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
|
||||
|
||||
async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {
|
||||
const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-mock-"));
|
||||
const wrapperPath = path.join(dir, "fake-agent.sh");
|
||||
const envExports = Object.entries(extraEnv ?? {})
|
||||
.map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)
|
||||
.join("\n");
|
||||
const script = `#!/bin/sh
|
||||
${envExports}
|
||||
exec ${JSON.stringify("bun")} ${JSON.stringify(mockAgentPath)} "$@"
|
||||
`;
|
||||
await writeFile(wrapperPath, script, "utf8");
|
||||
await chmod(wrapperPath, 0o755);
|
||||
return wrapperPath;
|
||||
}
|
||||
|
||||
async function waitForFileContent(filePath: string, attempts = 40): Promise<string> {
|
||||
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
||||
try {
|
||||
const content = await readFile(filePath, "utf8");
|
||||
if (content.trim().length > 0) {
|
||||
return content;
|
||||
}
|
||||
} catch {}
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
}
|
||||
throw new Error(`Timed out waiting for file content at ${filePath}`);
|
||||
}
|
||||
|
||||
const parameterizedGpt54ConfigOptions = [
|
||||
{
|
||||
type: "select",
|
||||
@@ -90,6 +132,64 @@ const parameterizedClaudeConfigOptions = [
|
||||
},
|
||||
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
|
||||
|
||||
const parameterizedClaudeModelOptionConfigOptions = [
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "claude-opus-4-6",
|
||||
options: [{ name: "Opus 4.6", value: "claude-opus-4-6" }],
|
||||
category: "model",
|
||||
id: "model",
|
||||
name: "Model",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "high",
|
||||
options: [
|
||||
{ name: "Low", value: "low" },
|
||||
{ name: "Medium", value: "medium" },
|
||||
{ name: "High", value: "high" },
|
||||
],
|
||||
category: "thought_level",
|
||||
id: "reasoning",
|
||||
name: "Reasoning",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "max",
|
||||
options: [
|
||||
{ name: "Low", value: "low" },
|
||||
{ name: "Medium", value: "medium" },
|
||||
{ name: "High", value: "high" },
|
||||
{ name: "Max", value: "max" },
|
||||
],
|
||||
category: "model_option",
|
||||
id: "effort",
|
||||
name: "Effort",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "true",
|
||||
options: [
|
||||
{ name: "Off", value: "false" },
|
||||
{ name: "Fast", value: "true" },
|
||||
],
|
||||
category: "model_config",
|
||||
id: "fast",
|
||||
name: "Fast",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "true",
|
||||
options: [
|
||||
{ name: "Off", value: "false" },
|
||||
{ name: ":icon-brain:", value: "true" },
|
||||
],
|
||||
category: "model_config",
|
||||
id: "thinking",
|
||||
name: "Thinking",
|
||||
},
|
||||
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
|
||||
|
||||
const sessionNewCursorConfigOptions = [
|
||||
{
|
||||
type: "select",
|
||||
@@ -132,6 +232,21 @@ const sessionNewCursorConfigOptions = [
|
||||
},
|
||||
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
|
||||
|
||||
const baseCursorSettings: CursorSettings = {
|
||||
enabled: true,
|
||||
binaryPath: "agent",
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
};
|
||||
|
||||
const emptyCapabilities = {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
} as const;
|
||||
|
||||
describe("getCursorFallbackModels", () => {
|
||||
it("does not publish any built-in cursor models before ACP discovery", () => {
|
||||
expect(
|
||||
@@ -142,6 +257,56 @@ describe("getCursorFallbackModels", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildCursorProviderSnapshot", () => {
|
||||
it("downgrades ready status to warning when ACP model discovery times out", () => {
|
||||
expect(
|
||||
buildCursorProviderSnapshot({
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
cursorSettings: baseCursorSettings,
|
||||
parsed: {
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated", type: "Team", label: "Cursor Team Subscription" },
|
||||
},
|
||||
discoveryWarning: "Cursor ACP model discovery timed out after 15000ms.",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "warning",
|
||||
message: "Cursor ACP model discovery timed out after 15000ms.",
|
||||
models: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves provider error state while appending discovery warnings", () => {
|
||||
expect(
|
||||
buildCursorProviderSnapshot({
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
cursorSettings: {
|
||||
...baseCursorSettings,
|
||||
customModels: ["claude-sonnet-4-6"],
|
||||
},
|
||||
parsed: {
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
status: "error",
|
||||
auth: { status: "unauthenticated" },
|
||||
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
|
||||
},
|
||||
discoveryWarning: "Cursor ACP model discovery failed. Check server logs for details.",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "error",
|
||||
message:
|
||||
"Cursor Agent is not authenticated. Run `agent login` and try again. Cursor ACP model discovery failed. Check server logs for details.",
|
||||
models: [
|
||||
{
|
||||
slug: "claude-sonnet-4-6",
|
||||
isCustom: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildCursorCapabilitiesFromConfigOptions", () => {
|
||||
it("derives model capabilities from parameterized Cursor ACP config options", () => {
|
||||
expect(buildCursorCapabilitiesFromConfigOptions(parameterizedGpt54ConfigOptions)).toEqual(
|
||||
@@ -177,6 +342,23 @@ describe("buildCursorCapabilitiesFromConfigOptions", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("prefers the newer model_option effort control over legacy thought_level", () => {
|
||||
expect(
|
||||
buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeModelOptionConfigOptions),
|
||||
).toEqual({
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High" },
|
||||
{ value: "max", label: "Max", isDefault: true },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkCursorProviderStatus", () => {
|
||||
@@ -226,6 +408,91 @@ describe("checkCursorProviderStatus", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("discoverCursorModelsViaAcp", () => {
|
||||
it("keeps the ACP probe runtime alive long enough to discover models", async () => {
|
||||
const wrapperPath = await makeMockAgentWrapper();
|
||||
|
||||
const models = await Effect.runPromise(
|
||||
discoverCursorModelsViaAcp({
|
||||
enabled: true,
|
||||
binaryPath: wrapperPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
expect(models.map((model) => model.slug)).toEqual([
|
||||
"default",
|
||||
"composer-2",
|
||||
"gpt-5.4",
|
||||
"claude-opus-4-6",
|
||||
]);
|
||||
});
|
||||
|
||||
it("closes the ACP probe runtime after discovery completes", async () => {
|
||||
const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-exit-log-"));
|
||||
const exitLogPath = path.join(tempDir, "exit.log");
|
||||
const wrapperPath = await makeMockAgentWrapper({
|
||||
T3_ACP_EXIT_LOG_PATH: exitLogPath,
|
||||
});
|
||||
|
||||
await Effect.runPromise(
|
||||
discoverCursorModelsViaAcp({
|
||||
enabled: true,
|
||||
binaryPath: wrapperPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
const exitLog = await waitForFileContent(exitLogPath);
|
||||
expect(exitLog).toContain("SIGTERM");
|
||||
});
|
||||
});
|
||||
|
||||
describe("discoverCursorModelCapabilitiesViaAcp", () => {
|
||||
it("closes all ACP probe runtimes after capability enrichment completes", async () => {
|
||||
const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-capabilities-exit-log-"));
|
||||
const exitLogPath = path.join(tempDir, "exit.log");
|
||||
const wrapperPath = await makeMockAgentWrapper({
|
||||
T3_ACP_EXIT_LOG_PATH: exitLogPath,
|
||||
});
|
||||
const existingModels: ReadonlyArray<ServerProviderModel> = [
|
||||
{ slug: "default", name: "Auto", isCustom: false, capabilities: emptyCapabilities },
|
||||
{ slug: "composer-2", name: "Composer 2", isCustom: false, capabilities: emptyCapabilities },
|
||||
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, capabilities: emptyCapabilities },
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Opus 4.6",
|
||||
isCustom: false,
|
||||
capabilities: emptyCapabilities,
|
||||
},
|
||||
];
|
||||
|
||||
const models = await Effect.runPromise(
|
||||
discoverCursorModelCapabilitiesViaAcp(
|
||||
{
|
||||
enabled: true,
|
||||
binaryPath: wrapperPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
},
|
||||
existingModels,
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
expect(models.map((model) => model.slug)).toEqual([
|
||||
"default",
|
||||
"composer-2",
|
||||
"gpt-5.4",
|
||||
"claude-opus-4-6",
|
||||
]);
|
||||
|
||||
const exitLog = await waitForFileContent(exitLogPath);
|
||||
expect(exitLog.match(/SIGTERM/g)?.length ?? 0).toBe(4);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseCursorAboutOutput", () => {
|
||||
it("parses json about output and forwards subscription metadata", () => {
|
||||
expect(
|
||||
@@ -377,4 +644,16 @@ describe("resolveCursorAcpConfigUpdates", () => {
|
||||
]),
|
||||
).toEqual([{ configId: "fast", value: "false" }]);
|
||||
});
|
||||
|
||||
it("writes Cursor effort changes through the newer model_option config when available", () => {
|
||||
expect(
|
||||
resolveCursorAcpConfigUpdates(parameterizedClaudeModelOptionConfigOptions, {
|
||||
reasoning: "max",
|
||||
thinking: false,
|
||||
}),
|
||||
).toEqual([
|
||||
{ configId: "effort", value: "max" },
|
||||
{ configId: "thinking", value: "false" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -298,7 +298,7 @@ type EventBaseInput = {
|
||||
raw: {
|
||||
source: "opencode.sdk.event",
|
||||
payload: input.raw,
|
||||
} as unknown as ProviderRuntimeEvent["raw"],
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
|
||||
@@ -10,9 +10,14 @@ import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { ClaudeAdapter, type ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
|
||||
import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts";
|
||||
import { CursorAdapter, type CursorAdapterShape } from "../Services/CursorAdapter.ts";
|
||||
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
|
||||
import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
|
||||
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||
import type { CodexAdapterShape } from "../Services/CodexAdapter.ts";
|
||||
import { CursorAdapter } from "../Services/CursorAdapter.ts";
|
||||
import type { CursorAdapterShape } from "../Services/CursorAdapter.ts";
|
||||
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
|
||||
import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
|
||||
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
|
||||
import { ProviderUnsupportedError } from "../Errors.ts";
|
||||
@@ -57,6 +62,23 @@ const fakeClaudeAdapter: ClaudeAdapter.ClaudeAdapterShape = {
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const fakeOpenCodeAdapter: OpenCodeAdapterShape = {
|
||||
provider: "opencode",
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
sendTurn: vi.fn(),
|
||||
interruptTurn: vi.fn(),
|
||||
respondToRequest: vi.fn(),
|
||||
respondToUserInput: vi.fn(),
|
||||
stopSession: vi.fn(),
|
||||
listSessions: vi.fn(),
|
||||
hasSession: vi.fn(),
|
||||
readThread: vi.fn(),
|
||||
rollbackThread: vi.fn(),
|
||||
stopAll: vi.fn(),
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const fakeCursorAdapter: CursorAdapterShape = {
|
||||
provider: "cursor",
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
@@ -81,6 +103,7 @@ const layer = it.layer(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(CodexAdapter, fakeCodexAdapter),
|
||||
Layer.succeed(ClaudeAdapter, fakeClaudeAdapter),
|
||||
Layer.succeed(OpenCodeAdapter, fakeOpenCodeAdapter),
|
||||
Layer.succeed(CursorAdapter, fakeCursorAdapter),
|
||||
),
|
||||
),
|
||||
@@ -95,13 +118,15 @@ it.layer(layer)("ProviderAdapterRegistryLive", (it) => {
|
||||
const registry = yield* ProviderAdapterRegistry;
|
||||
const codex = yield* registry.getByProvider("codex");
|
||||
const claude = yield* registry.getByProvider("claudeAgent");
|
||||
const openCode = yield* registry.getByProvider("opencode");
|
||||
const cursor = yield* registry.getByProvider("cursor");
|
||||
assert.equal(codex, fakeCodexAdapter);
|
||||
assert.equal(claude, fakeClaudeAdapter);
|
||||
assert.equal(openCode, fakeOpenCodeAdapter);
|
||||
assert.equal(cursor, fakeCursorAdapter);
|
||||
|
||||
const providers = yield* registry.listProviders();
|
||||
assert.deepEqual(providers, ["codex", "claudeAgent", "cursor"]);
|
||||
assert.deepEqual(providers, ["codex", "claudeAgent", "opencode", "cursor"]);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
|
||||
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||
import { CursorAdapter } from "../Services/CursorAdapter.ts";
|
||||
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
|
||||
|
||||
const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* () {
|
||||
const registry = yield* ProviderInstanceRegistry;
|
||||
@@ -43,7 +44,12 @@ const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(fun
|
||||
const adapters =
|
||||
options?.adapters !== undefined
|
||||
? options.adapters
|
||||
: [yield* CodexAdapter, yield* ClaudeAdapter, yield* CursorAdapter];
|
||||
: [
|
||||
yield* CodexAdapter,
|
||||
yield* ClaudeAdapter,
|
||||
yield* OpenCodeAdapter,
|
||||
...(cursorAdapterOption._tag === "Some" ? [cursorAdapterOption.value] : []),
|
||||
];
|
||||
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
|
||||
|
||||
const getInstanceInfo: ProviderAdapterRegistryShape["getInstanceInfo"] = (instanceId) =>
|
||||
|
||||
Reference in new issue
Block a user