fix(server): link thread PRs without an open client (#10101)
Co-authored-by: Claude Fable 5.1 <[email protected]>
This commit is contained in:
1 parent
5fa35d2116
commit
223ff4490f
50 files changed
+2308
-1485
No files matched your search
@@ -67,6 +67,7 @@ import {
|
||||
} from "../src/orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ThreadDeletionReactor } from "../src/orchestration/Services/ThreadDeletionReactor.ts";
|
||||
import * as ThreadSettlementReactor from "../src/orchestration/ThreadSettlementReactor.ts";
|
||||
import * as ThreadPullRequestReactor from "../src/orchestration/ThreadPullRequestReactor.ts";
|
||||
import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts";
|
||||
import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
@@ -394,6 +395,12 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
drainThrough: () => Effect.void,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ThreadPullRequestReactor.ThreadPullRequestReactor, {
|
||||
start: () => Effect.void,
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ThreadSettlementReactor.ThreadSettlementReactor, {
|
||||
start: () => Effect.void,
|
||||
|
||||
@@ -13,6 +13,7 @@ import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as References from "effect/References";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { expect } from "vite-plus/test";
|
||||
@@ -30,10 +31,13 @@ import {
|
||||
TextGenerationError,
|
||||
} from "@t3tools/contracts";
|
||||
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
|
||||
import * as GitLabCli from "../sourceControl/GitLabCli.ts";
|
||||
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as GitHubSourceControlProvider from "../sourceControl/GitHubSourceControlProvider.ts";
|
||||
import * as GitLabSourceControlProvider from "../sourceControl/GitLabSourceControlProvider.ts";
|
||||
import type { SourceControlProvider } from "../sourceControl/SourceControlProvider.ts";
|
||||
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
|
||||
@@ -41,6 +45,8 @@ import * as ProviderRegistry from "../provider/Services/ProviderRegistry.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import * as GitManager from "./GitManager.ts";
|
||||
|
||||
const encodeCliJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
|
||||
|
||||
interface FakeGhScenario {
|
||||
prListSequence?: string[];
|
||||
prListByHeadSelector?: Record<string, string>;
|
||||
@@ -620,6 +626,7 @@ function preparePullRequestThread(
|
||||
|
||||
function makeManager(input?: {
|
||||
ghScenario?: FakeGhScenario;
|
||||
sourceControlProvider?: SourceControlProvider["Service"];
|
||||
textGeneration?: Partial<FakeGitTextGeneration>;
|
||||
serverSettings?: Parameters<typeof ServerSettings.layerTest>[0];
|
||||
setupScriptRunner?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"];
|
||||
@@ -659,7 +666,10 @@ function makeManager(input?: {
|
||||
);
|
||||
const sourceControlRegistryLayer = Layer.effect(
|
||||
SourceControlProviderRegistry.SourceControlProviderRegistry,
|
||||
GitHubSourceControlProvider.make.pipe(
|
||||
(input?.sourceControlProvider === undefined
|
||||
? GitHubSourceControlProvider.make
|
||||
: Effect.succeed(input.sourceControlProvider)
|
||||
).pipe(
|
||||
Effect.map((provider) =>
|
||||
SourceControlProviderRegistry.SourceControlProviderRegistry.of({
|
||||
get: () => Effect.succeed(provider),
|
||||
@@ -1146,7 +1156,12 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
branch: "feature/saved-branch",
|
||||
});
|
||||
|
||||
expect(pullRequest).toEqual({
|
||||
expect(pullRequest).toMatchObject({
|
||||
number: 216,
|
||||
title: "Saved branch PR",
|
||||
url: "https://github.com/pingdotgg/t3code/pull/216",
|
||||
baseRef: "main",
|
||||
headRef: "feature/saved-branch",
|
||||
state: "open",
|
||||
closedAt: null,
|
||||
mergedAt: null,
|
||||
@@ -1191,7 +1206,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const pullRequest = yield* manager.branchPullRequest({ cwd: repoDir, branch: "main" });
|
||||
|
||||
expect(pullRequest).toEqual({
|
||||
expect(pullRequest).toMatchObject({
|
||||
state: "merged",
|
||||
closedAt: null,
|
||||
mergedAt: "2026-04-07T15:00:00Z",
|
||||
@@ -1244,7 +1259,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
branch: "feature/deleted-local-branch",
|
||||
});
|
||||
|
||||
expect(pullRequest).toEqual({
|
||||
expect(pullRequest).toMatchObject({
|
||||
state: "merged",
|
||||
closedAt: null,
|
||||
mergedAt: null,
|
||||
@@ -1310,7 +1325,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
branch: "feature/deleted-fork-branch",
|
||||
});
|
||||
|
||||
expect(pullRequest).toEqual({
|
||||
expect(pullRequest).toMatchObject({
|
||||
state: "merged",
|
||||
closedAt: null,
|
||||
mergedAt: null,
|
||||
@@ -1432,6 +1447,17 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
updatedAt: "2026-04-07T15:00:00Z",
|
||||
},
|
||||
]),
|
||||
encodeCliJson([
|
||||
{
|
||||
number: 221,
|
||||
title: "New PR on the same branch",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/221",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/shared-pr-cache",
|
||||
state: "OPEN",
|
||||
updatedAt: "2026-04-08T15:00:00Z",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
@@ -1445,6 +1471,16 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
expect(status.pr?.state).toBe("merged");
|
||||
expect(pullRequest?.state).toBe("merged");
|
||||
expect(ghCalls.filter((call) => call.startsWith("pr list "))).toHaveLength(1);
|
||||
const refreshed = yield* manager.branchPullRequest(
|
||||
{ cwd: repoDir, branch: "feature/shared-pr-cache" },
|
||||
{ refresh: true },
|
||||
);
|
||||
expect(refreshed).toMatchObject({
|
||||
number: 221,
|
||||
state: "open",
|
||||
repositoryKey: "github.com/pingdotgg/codething-mvp",
|
||||
});
|
||||
expect(ghCalls.filter((call) => call.startsWith("pr list "))).toHaveLength(2);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1459,7 +1495,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/lookup-failure"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
command: "gh",
|
||||
@@ -1474,6 +1510,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error._tag).toBe("SourceControlProviderError");
|
||||
const refreshError = yield* manager
|
||||
.branchPullRequest({ cwd: repoDir, branch: "feature/lookup-failure" }, { refresh: true })
|
||||
.pipe(Effect.flip);
|
||||
expect(refreshError._tag).toBe("SourceControlProviderError");
|
||||
expect(ghCalls.filter((call) => call.startsWith("pr list "))).toHaveLength(1);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1594,6 +1635,186 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
expect(Duration.toMillis(GitManager.prLookupFailureTtl(20))).toBe(900_000);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"https://github.example.com/team/repository/pull/42?tab=files",
|
||||
"github.example.com/team/repository",
|
||||
],
|
||||
[
|
||||
"https://gitlab.example.com/group/subgroup/repository/-/merge_requests/42",
|
||||
"gitlab.example.com/group/subgroup/repository",
|
||||
],
|
||||
["https://bitbucket.org/team/repository/pull-requests/42", "bitbucket.org/team/repository"],
|
||||
[
|
||||
"https://dev.azure.com/org/project/_git/repository/pullrequest/42",
|
||||
"dev.azure.com/org/project/_git/repository",
|
||||
],
|
||||
[
|
||||
"https://org.visualstudio.com/project/_git/repository/pullrequest/42",
|
||||
"org.visualstudio.com/project/_git/repository",
|
||||
],
|
||||
[
|
||||
"https://gitlab.example/group/pull/123/repository/-/merge_requests/42",
|
||||
"gitlab.example/group/pull/123/repository",
|
||||
],
|
||||
["https://github.example.com/team/repository/issues/42", null],
|
||||
] as const)("reads the repository from the returned PR URL %s", (url, expected) => {
|
||||
expect(GitManager.pullRequestRepositoryKey(url)).toBe(expected);
|
||||
});
|
||||
|
||||
it.effect("distinguishes Enterprise forks with the same head branch", () =>
|
||||
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", forkDir]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "fork", "feature"]);
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(
|
||||
repoDir,
|
||||
"origin",
|
||||
"[email protected]:team/repository.git",
|
||||
originDir,
|
||||
);
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(
|
||||
repoDir,
|
||||
"fork",
|
||||
"[email protected]:alice/repository.git",
|
||||
forkDir,
|
||||
);
|
||||
const output = encodeCliJson([
|
||||
{
|
||||
number: 2,
|
||||
title: "Another fork",
|
||||
url: "https://github.example.com/team/repository/pull/2",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature",
|
||||
state: "OPEN",
|
||||
updatedAt: "2026-04-08T15:00:00Z",
|
||||
isCrossRepository: true,
|
||||
headRepository: { nameWithOwner: "bob/repository" },
|
||||
headRepositoryOwner: { login: "bob" },
|
||||
},
|
||||
{
|
||||
number: 1,
|
||||
title: "This fork",
|
||||
url: "https://github.example.com/team/repository/pull/1",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature",
|
||||
state: "OPEN",
|
||||
updatedAt: "2026-04-07T15:00:00Z",
|
||||
isCrossRepository: true,
|
||||
headRepository: { nameWithOwner: "alice/repository" },
|
||||
headRepositoryOwner: { login: "alice" },
|
||||
},
|
||||
]);
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListByHeadSelector: {
|
||||
"alice:feature": output,
|
||||
"fork:feature": output,
|
||||
feature: output,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(yield* manager.branchPullRequest({ cwd: repoDir, branch: "feature" })).toMatchObject({
|
||||
number: 1,
|
||||
repositoryKey: "github.example.com/team/repository",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect.each([
|
||||
"[email protected]:Group/Subgroup/Fork.git",
|
||||
"https://gitlab.com/Group/Subgroup/Fork.git",
|
||||
])("matches nested GitLab forks through the adapter for %s", (remoteUrl) =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const originDir = yield* createBareRemote();
|
||||
const forkDir = yield* createBareRemote();
|
||||
const branch = "feature/NestedGroups";
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
yield* runGit(repoDir, ["remote", "add", "fork", forkDir]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", branch]);
|
||||
yield* runGit(repoDir, ["push", "-u", "fork", branch]);
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(
|
||||
repoDir,
|
||||
"origin",
|
||||
"[email protected]:Group/Upstream/Repository.git",
|
||||
originDir,
|
||||
);
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(repoDir, "fork", remoteUrl, forkDir);
|
||||
const output = encodeCliJson([
|
||||
{
|
||||
iid: 2,
|
||||
title: "Another subgroup's fork",
|
||||
web_url: "https://gitlab.com/Group/Upstream/Repository/-/merge_requests/2",
|
||||
target_branch: "main",
|
||||
source_branch: branch,
|
||||
state: "opened",
|
||||
updated_at: "2026-04-08T15:00:00Z",
|
||||
source_project_id: 102,
|
||||
target_project_id: 100,
|
||||
source_project: { path_with_namespace: "Group/Other/Fork" },
|
||||
},
|
||||
{
|
||||
iid: 1,
|
||||
title: "This subgroup's fork",
|
||||
web_url: "https://gitlab.com/Group/Upstream/Repository/-/merge_requests/1",
|
||||
target_branch: "main",
|
||||
source_branch: branch,
|
||||
state: "opened",
|
||||
updated_at: "2026-04-07T15:00:00Z",
|
||||
source_project_id: 101,
|
||||
target_project_id: 100,
|
||||
source_project: { path_with_namespace: "Group/Subgroup/Fork" },
|
||||
},
|
||||
]);
|
||||
const calls: VcsProcess.VcsProcessInput[] = [];
|
||||
const provider = yield* GitLabSourceControlProvider.make.pipe(
|
||||
Effect.provide(
|
||||
GitLabCli.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProcess.VcsProcess)({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
calls.push(input);
|
||||
return fakeGhOutput(output);
|
||||
}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const { manager } = yield* makeManager({ sourceControlProvider: provider });
|
||||
|
||||
expect(yield* manager.branchPullRequest({ cwd: repoDir, branch })).toMatchObject({
|
||||
number: 1,
|
||||
repositoryKey: "gitlab.com/group/upstream/repository",
|
||||
});
|
||||
expect(calls.length).toBeGreaterThan(0);
|
||||
for (const call of calls) {
|
||||
expect(call.command).toBe("glab");
|
||||
expect(call.args).toEqual([
|
||||
"mr",
|
||||
"list",
|
||||
"--source-branch",
|
||||
branch,
|
||||
"--all",
|
||||
"--per-page",
|
||||
"20",
|
||||
"--output",
|
||||
"json",
|
||||
]);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"status ignores unrelated fork PRs when the current branch tracks the same repository",
|
||||
() =>
|
||||
@@ -2149,7 +2370,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
branch: "feature/fork-settle",
|
||||
});
|
||||
|
||||
expect(pullRequest).toEqual({
|
||||
expect(pullRequest).toMatchObject({
|
||||
state: "merged",
|
||||
closedAt: null,
|
||||
mergedAt: null,
|
||||
|
||||
@@ -77,6 +77,13 @@ export interface GitRemoteStatusOptions extends GitVcsDriver.GitRemoteStatusOpti
|
||||
readonly refreshMissingPullRequest?: boolean;
|
||||
}
|
||||
|
||||
export type GitBranchPullRequest = NonNullable<VcsStatusResult["pr"]> & {
|
||||
readonly repositoryKey: string | null;
|
||||
readonly updatedAt: string | null;
|
||||
readonly closedAt?: string | null;
|
||||
readonly mergedAt?: string | null;
|
||||
};
|
||||
|
||||
interface SourceControlTextGenerationSettings {
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly style: SourceControlWritingStyleSettings;
|
||||
@@ -96,18 +103,10 @@ export class GitManager extends Context.Service<
|
||||
options?: GitRemoteStatusOptions,
|
||||
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
|
||||
/** Resolve the PR for a saved branch without changing the current checkout. */
|
||||
readonly branchPullRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly branch: string;
|
||||
}) => Effect.Effect<
|
||||
{
|
||||
readonly state: "open" | "closed" | "merged";
|
||||
readonly updatedAt: string | null;
|
||||
readonly closedAt?: string | null;
|
||||
readonly mergedAt?: string | null;
|
||||
} | null,
|
||||
GitManagerServiceError
|
||||
>;
|
||||
readonly branchPullRequest: (
|
||||
input: { readonly cwd: string; readonly branch: string },
|
||||
options?: { readonly refresh?: boolean },
|
||||
) => Effect.Effect<GitBranchPullRequest | null, GitManagerServiceError>;
|
||||
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
@@ -214,9 +213,26 @@ interface BranchHeadContext {
|
||||
isCrossRepository: boolean;
|
||||
}
|
||||
|
||||
export function pullRequestRepositoryKey(value: string): string | null {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
const match =
|
||||
/^(.*)(?:\/pull\/|\/-\/merge_requests\/|\/pull-requests\/|\/pullrequest\/)\d+(?:\/.*)?$/iu.exec(
|
||||
url.pathname,
|
||||
);
|
||||
if (match?.[1] === undefined) return null;
|
||||
url.pathname = match[1];
|
||||
url.search = "";
|
||||
url.hash = "";
|
||||
return normalizeGitRemoteUrl(url.toString());
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseRepositoryNameFromPullRequestUrl(url: string): string | null {
|
||||
const trimmed = url.trim();
|
||||
const match = /^https:\/\/github\.com\/[^/]+\/([^/]+)\/pull\/\d+(?:\/.*)?$/i.exec(trimmed);
|
||||
const match = /^https?:\/\/[^/]+\/[^/]+\/([^/]+)\/pull\/\d+(?:\/.*)?$/i.exec(trimmed);
|
||||
const repositoryName = match?.[1]?.trim() ?? "";
|
||||
return repositoryName.length > 0 ? repositoryName : null;
|
||||
}
|
||||
@@ -254,14 +270,14 @@ function resolvePullRequestWorktreeLocalBranchName(
|
||||
return `t3code/pr-${pullRequest.number}/${suffix}`;
|
||||
}
|
||||
|
||||
function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
|
||||
function parseRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
|
||||
const trimmed = url?.trim() ?? "";
|
||||
if (trimmed.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const match =
|
||||
/^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(
|
||||
/^(?:[^@/\s]+@[^:/\s]+:|(?:ssh|https?|git):\/\/[^/]+\/)((?:[^/\s]+\/)+[^/\s]+?)(?:\.git)?\/?$/iu.exec(
|
||||
trimmed,
|
||||
);
|
||||
const repositoryNameWithOwner = match?.[1]?.trim() ?? "";
|
||||
@@ -273,6 +289,7 @@ function parseRepositoryOwnerLogin(nameWithOwner: string | null): string | null
|
||||
if (trimmed.length === 0) {
|
||||
return null;
|
||||
}
|
||||
// GitLab reports the top-level group as owner. The full path distinguishes subgroups.
|
||||
const [ownerLogin] = trimmed.split("/");
|
||||
const normalizedOwnerLogin = ownerLogin?.trim() ?? "";
|
||||
return normalizedOwnerLogin.length > 0 ? normalizedOwnerLogin : null;
|
||||
@@ -1261,7 +1278,7 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
const remoteUrl = yield* readConfigValueNullable(cwd, `remote.${remoteName}.url`);
|
||||
const repositoryNameWithOwner = parseGitHubRepositoryNameWithOwnerFromRemoteUrl(remoteUrl);
|
||||
const repositoryNameWithOwner = parseRepositoryNameWithOwnerFromRemoteUrl(remoteUrl);
|
||||
return {
|
||||
remoteUrlKey: remoteUrl ? normalizeGitRemoteUrl(remoteUrl) : null,
|
||||
repositoryNameWithOwner,
|
||||
@@ -2031,7 +2048,7 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
const branchPullRequest: GitManager["Service"]["branchPullRequest"] = Effect.fn(
|
||||
"branchPullRequest",
|
||||
)(function* ({ cwd, branch }) {
|
||||
)(function* ({ cwd, branch }, options) {
|
||||
const cacheCwd = yield* normalizeStatusCacheKey(cwd);
|
||||
const remotes = yield* gitCore.execute({
|
||||
operation: "GitManager.branchPullRequest.remotes",
|
||||
@@ -2111,6 +2128,14 @@ export const make = Effect.gen(function* () {
|
||||
localBranchExists,
|
||||
...(localBranchExists ? {} : { remoteName }),
|
||||
});
|
||||
if (options?.refresh) {
|
||||
// A completed turn can create a PR or reuse a merged PR's branch.
|
||||
// Refresh successful answers, but keep failed lookups' retry backoff.
|
||||
const cached = yield* Cache.getOption(prLookupCache, cacheKey).pipe(
|
||||
Effect.orElseSucceed(() => Option.none()),
|
||||
);
|
||||
if (Option.isSome(cached)) yield* Cache.invalidate(prLookupCache, cacheKey);
|
||||
}
|
||||
let cached = yield* Cache.get(prLookupCache, cacheKey);
|
||||
// The cached head context may have resolved on a different remote than
|
||||
// the saved upstream: a branch tracking origin/main but pushed to a fork
|
||||
@@ -2165,12 +2190,13 @@ export const make = Effect.gen(function* () {
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const statusPr = toStatusPr(latest);
|
||||
return {
|
||||
state: statusPr.state,
|
||||
updatedAt: statusPr.updatedAt,
|
||||
...toStatusPr(latest),
|
||||
closedAt: latest.closedAt ?? null,
|
||||
mergedAt: latest.mergedAt ?? null,
|
||||
// Hosting CLIs can select an upstream repository instead of origin.
|
||||
// The returned PR URL names the repository that actually owns it.
|
||||
repositoryKey: pullRequestRepositoryKey(latest.url),
|
||||
};
|
||||
});
|
||||
const invalidateLocalStatus: GitManager["Service"]["invalidateLocalStatus"] = Effect.fn(
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationCommand,
|
||||
type OrchestrationEvent,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -993,6 +994,216 @@ describe("OrchestrationEngine", () => {
|
||||
await system.dispose();
|
||||
});
|
||||
|
||||
it.each(["unlink", "relink", "branch", "worktree", "project", "delete"] as const)(
|
||||
"rejects PR discovery completed after a newer %s command",
|
||||
async (change) => {
|
||||
const system = await createOrchestrationSystem();
|
||||
try {
|
||||
const projectId = ProjectId.make("pr-race-project");
|
||||
const threadId = ThreadId.make("pr-race-thread");
|
||||
const previous = {
|
||||
projectId,
|
||||
repository: "owner/repository",
|
||||
number: 1,
|
||||
url: "https://example.test/owner/repository/pull/1",
|
||||
};
|
||||
const replacement = {
|
||||
...previous,
|
||||
number: 2,
|
||||
url: "https://example.test/owner/repository/pull/2",
|
||||
};
|
||||
await system.run(
|
||||
system.engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("pr-race-project-create"),
|
||||
projectId,
|
||||
title: "PR race project",
|
||||
workspaceRoot: "/tmp/pr-race-project",
|
||||
defaultModelSelection: null,
|
||||
createdAt: now(),
|
||||
}),
|
||||
);
|
||||
await system.run(
|
||||
system.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("pr-race-thread-create"),
|
||||
threadId,
|
||||
projectId,
|
||||
title: "PR race thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: "feature",
|
||||
worktreePath: null,
|
||||
createdAt: now(),
|
||||
}),
|
||||
);
|
||||
const observed = await system.run(
|
||||
system.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.make("pr-race-link"),
|
||||
threadId,
|
||||
linkedPullRequest: previous,
|
||||
}),
|
||||
);
|
||||
const metadataChanges = {
|
||||
unlink: { linkedPullRequest: null },
|
||||
relink: {
|
||||
linkedPullRequest: {
|
||||
...previous,
|
||||
number: 3,
|
||||
url: "https://example.test/owner/repository/pull/3",
|
||||
},
|
||||
},
|
||||
branch: { branch: "another-feature" },
|
||||
worktree: { worktreePath: "/tmp/another-worktree" },
|
||||
project: {},
|
||||
};
|
||||
await system.run(
|
||||
system.engine.dispatch(
|
||||
change === "project"
|
||||
? {
|
||||
type: "project.meta.update",
|
||||
commandId: CommandId.make("pr-race-project-move"),
|
||||
projectId,
|
||||
workspaceRoot: "/tmp/another-project-root",
|
||||
}
|
||||
: change === "delete"
|
||||
? { type: "thread.delete", commandId: CommandId.make("pr-race-delete"), threadId }
|
||||
: {
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.make(`pr-race-${change}`),
|
||||
threadId,
|
||||
...metadataChanges[change],
|
||||
},
|
||||
),
|
||||
);
|
||||
const command = {
|
||||
type: "thread.pull-request.sync",
|
||||
commandId: CommandId.make("pr-race-stale-sync"),
|
||||
threadId,
|
||||
projectId,
|
||||
snapshotSequence: observed.sequence,
|
||||
expected: {
|
||||
workspaceRoot: "/tmp/pr-race-project",
|
||||
branch: "feature",
|
||||
worktreePath: null,
|
||||
linkedPullRequest: previous,
|
||||
branchPullRequest: null,
|
||||
},
|
||||
branchPullRequest: replacement,
|
||||
linkedPullRequest: replacement,
|
||||
} satisfies OrchestrationCommand;
|
||||
const error = await system.run(system.engine.dispatch(command).pipe(Effect.flip));
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
if (change === "delete") return;
|
||||
const current = (await system.readModel()).threads[0];
|
||||
expect(current?.branchPullRequest ?? null).toBeNull();
|
||||
expect(current?.linkedPullRequest ?? null).toEqual(
|
||||
change === "unlink"
|
||||
? null
|
||||
: change === "relink"
|
||||
? metadataChanges.relink.linkedPullRequest
|
||||
: previous,
|
||||
);
|
||||
} finally {
|
||||
await system.dispose();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("saves PR associations through streaming and unrelated metadata edits", async () => {
|
||||
const system = await createOrchestrationSystem();
|
||||
try {
|
||||
const projectId = ProjectId.make("pr-sync-project");
|
||||
const threadId = ThreadId.make("pr-sync-thread");
|
||||
await system.run(
|
||||
system.engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("pr-sync-project-create"),
|
||||
projectId,
|
||||
title: "PR sync project",
|
||||
workspaceRoot: "/tmp/pr-sync-project",
|
||||
defaultModelSelection: null,
|
||||
createdAt: now(),
|
||||
}),
|
||||
);
|
||||
const created = await system.run(
|
||||
system.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("pr-sync-thread-create"),
|
||||
threadId,
|
||||
projectId,
|
||||
title: "PR sync thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: "feature",
|
||||
worktreePath: null,
|
||||
createdAt: now(),
|
||||
}),
|
||||
);
|
||||
const reference = {
|
||||
projectId,
|
||||
repository: "owner/repository",
|
||||
number: 42,
|
||||
url: "https://example.test/owner/repository/pull/42",
|
||||
};
|
||||
const activityAt = "2026-01-01T01:00:00.000Z";
|
||||
await system.run(
|
||||
system.engine.dispatch({
|
||||
type: "thread.message.assistant.delta",
|
||||
commandId: CommandId.make("pr-sync-streaming-message"),
|
||||
threadId,
|
||||
messageId: MessageId.make("pr-sync-message"),
|
||||
delta: "The PR is ready.",
|
||||
createdAt: activityAt,
|
||||
}),
|
||||
);
|
||||
await system.run(
|
||||
system.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.make("pr-sync-title-and-model"),
|
||||
threadId,
|
||||
title: "Renamed thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
}),
|
||||
);
|
||||
await system.run(
|
||||
system.engine.dispatch({
|
||||
type: "project.meta.update",
|
||||
commandId: CommandId.make("pr-sync-project-title"),
|
||||
projectId,
|
||||
title: "Renamed project",
|
||||
}),
|
||||
);
|
||||
const beforeSync = (await system.readModel()).threads[0];
|
||||
await system.run(
|
||||
system.engine.dispatch({
|
||||
type: "thread.pull-request.sync",
|
||||
commandId: CommandId.make("pr-sync-discovery"),
|
||||
projectId,
|
||||
threadId,
|
||||
snapshotSequence: created.sequence,
|
||||
expected: {
|
||||
workspaceRoot: "/tmp/pr-sync-project",
|
||||
branch: "feature",
|
||||
worktreePath: null,
|
||||
linkedPullRequest: null,
|
||||
branchPullRequest: null,
|
||||
},
|
||||
branchPullRequest: reference,
|
||||
}),
|
||||
);
|
||||
const current = (await system.readModel()).threads[0];
|
||||
expect(current?.branchPullRequest).toEqual(reference);
|
||||
expect(current?.linkedPullRequest ?? null).toBeNull();
|
||||
expect(current?.updatedAt).toBe(beforeSync?.updatedAt);
|
||||
} finally {
|
||||
await system.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("allows authoritative worktree bootstrap to assign a temporary branch", async () => {
|
||||
const system = await createOrchestrationSystem();
|
||||
const { engine } = system;
|
||||
|
||||
@@ -185,6 +185,23 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
// The decider compares the lookup inputs. Only recreation needs an
|
||||
// event check, since it can reset a thread to the same field values.
|
||||
if (
|
||||
envelope.command.type === "thread.pull-request.sync" &&
|
||||
(yield* eventStore.hasEventAfter({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: envelope.command.threadId,
|
||||
sequenceExclusive: envelope.command.snapshotSequence,
|
||||
type: "thread.created",
|
||||
}))
|
||||
) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: envelope.command.type,
|
||||
detail: `thread ${envelope.command.threadId} was recreated before pull request discovery`,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
envelope.command.type === "thread.auto-settle" &&
|
||||
threadBackgroundLiveness.getThreadBackgroundLiveness(envelope.command.threadId) !== null
|
||||
|
||||
@@ -10,6 +10,7 @@ import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
|
||||
import * as ThreadSettlementReactor from "../ThreadSettlementReactor.ts";
|
||||
import * as ThreadPullRequestReactor from "../ThreadPullRequestReactor.ts";
|
||||
import { OrchestrationReactor } from "../Services/OrchestrationReactor.ts";
|
||||
import { makeOrchestrationReactor } from "./OrchestrationReactor.ts";
|
||||
import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts";
|
||||
@@ -65,6 +66,15 @@ describe("OrchestrationReactor", () => {
|
||||
drainThrough: () => Effect.void,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ThreadPullRequestReactor.ThreadPullRequestReactor, {
|
||||
start: () => {
|
||||
started.push("thread-pull-request-reactor");
|
||||
return Effect.void;
|
||||
},
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ThreadSettlementReactor.ThreadSettlementReactor, {
|
||||
start: () => {
|
||||
@@ -95,6 +105,7 @@ describe("OrchestrationReactor", () => {
|
||||
"provider-command-reactor",
|
||||
"checkpoint-reactor",
|
||||
"thread-deletion-reactor",
|
||||
"thread-pull-request-reactor",
|
||||
"thread-settlement-reactor",
|
||||
"agent-awareness-relay",
|
||||
]);
|
||||
|
||||
@@ -10,6 +10,7 @@ import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
|
||||
import * as ThreadSettlementReactor from "../ThreadSettlementReactor.ts";
|
||||
import * as ThreadPullRequestReactor from "../ThreadPullRequestReactor.ts";
|
||||
import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts";
|
||||
|
||||
export const makeOrchestrationReactor = Effect.gen(function* () {
|
||||
@@ -18,6 +19,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () {
|
||||
const checkpointReactor = yield* CheckpointReactor;
|
||||
const threadDeletionReactor = yield* ThreadDeletionReactor;
|
||||
const threadSettlementReactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
|
||||
const threadPullRequestReactor = yield* ThreadPullRequestReactor.ThreadPullRequestReactor;
|
||||
const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
|
||||
|
||||
const start: OrchestrationReactorShape["start"] = Effect.fn("start")(function* () {
|
||||
@@ -25,6 +27,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () {
|
||||
yield* providerCommandReactor.start();
|
||||
yield* checkpointReactor.start();
|
||||
yield* threadDeletionReactor.start();
|
||||
yield* threadPullRequestReactor.start();
|
||||
yield* threadSettlementReactor.start();
|
||||
yield* agentAwarenessRelay.start();
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
ThreadLinkedPullRequest,
|
||||
TurnId,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -18,6 +19,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { makeSqlStatementCounter } from "../../../integration/SqlStatementCounter.integration.ts";
|
||||
@@ -59,6 +61,9 @@ const exists = (filePath: string) =>
|
||||
});
|
||||
|
||||
const BaseTestLayer = makeProjectionPipelinePrefixedTestLayer("t3-projection-pipeline-test-");
|
||||
const encodeThreadLinkedPullRequest = Schema.encodeSync(
|
||||
Schema.fromJsonString(ThreadLinkedPullRequest),
|
||||
);
|
||||
|
||||
it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-cursor-batch-")))(
|
||||
"OrchestrationProjectionPipeline cursor batches",
|
||||
@@ -204,6 +209,93 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-import-shell-")
|
||||
},
|
||||
);
|
||||
|
||||
it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-branch-pr-projection-")))(
|
||||
"branch pull request projection",
|
||||
(it) => {
|
||||
it.effect("persists branch pull request updates without changing manual links", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const threadId = ThreadId.make("thread-pull-request");
|
||||
const projectId = ProjectId.make("project-pull-request");
|
||||
const eventFields = {
|
||||
aggregateKind: "thread" as const,
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: null,
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
};
|
||||
const created = yield* eventStore.append({
|
||||
...eventFields,
|
||||
type: "thread.created",
|
||||
eventId: EventId.make("evt-pull-request-created"),
|
||||
payload: {
|
||||
threadId,
|
||||
projectId,
|
||||
title: "Pull request thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: "feature",
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
yield* projectionPipeline.projectEvent(created);
|
||||
const linkedPullRequest = {
|
||||
projectId,
|
||||
repository: "pingdotgg/t3code",
|
||||
number: 42,
|
||||
url: "https://github.com/pingdotgg/t3code/pull/42",
|
||||
};
|
||||
const branchPullRequest = {
|
||||
...linkedPullRequest,
|
||||
number: 43,
|
||||
url: "https://github.com/pingdotgg/t3code/pull/43",
|
||||
};
|
||||
const updates = [
|
||||
{ payload: { linkedPullRequest, branchPullRequest }, expected: branchPullRequest },
|
||||
{ payload: { title: "Renamed thread" }, expected: branchPullRequest },
|
||||
{ payload: { branchPullRequest: null }, expected: null },
|
||||
];
|
||||
|
||||
for (const [index, update] of updates.entries()) {
|
||||
const event = yield* eventStore.append({
|
||||
...eventFields,
|
||||
type: "thread.meta-updated",
|
||||
eventId: EventId.make(`evt-pull-request-update-${index}`),
|
||||
payload: { threadId, updatedAt: now, ...update.payload },
|
||||
});
|
||||
yield* projectionPipeline.projectEvent(event);
|
||||
|
||||
const rows = yield* sql<{
|
||||
readonly linkedPullRequest: string | null;
|
||||
readonly branchPullRequest: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
linked_pull_request_json AS "linkedPullRequest",
|
||||
branch_pull_request_json AS "branchPullRequest"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = ${threadId}
|
||||
`;
|
||||
assert.deepEqual(rows, [
|
||||
{
|
||||
linkedPullRequest: encodeThreadLinkedPullRequest(linkedPullRequest),
|
||||
branchPullRequest:
|
||||
update.expected === null ? null : encodeThreadLinkedPullRequest(update.expected),
|
||||
},
|
||||
]);
|
||||
}
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
it.effect("bootstraps all projection states and writes projection rows", () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -605,6 +605,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
branch: event.payload.branch,
|
||||
worktreePath: event.payload.worktreePath,
|
||||
linkedPullRequest: null,
|
||||
branchPullRequest: null,
|
||||
latestTurnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
@@ -805,6 +806,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
...(event.payload.linkedPullRequest !== undefined
|
||||
? { linkedPullRequest: event.payload.linkedPullRequest }
|
||||
: {}),
|
||||
...(event.payload.branchPullRequest !== undefined
|
||||
? { branchPullRequest: event.payload.branchPullRequest }
|
||||
: {}),
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
ThreadLinkedPullRequest,
|
||||
TurnId,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -36,6 +37,9 @@ const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(val
|
||||
const encodeChatAttachments = Schema.encodeEffect(
|
||||
Schema.fromJsonString(Schema.Array(ChatAttachment)),
|
||||
);
|
||||
const encodeThreadLinkedPullRequest = Schema.encodeSync(
|
||||
Schema.fromJsonString(ThreadLinkedPullRequest),
|
||||
);
|
||||
|
||||
const projectionSnapshotLayer = it.layer(
|
||||
OrchestrationProjectionSnapshotQueryLive.pipe(
|
||||
@@ -52,6 +56,12 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const branchPullRequest = {
|
||||
projectId: asProjectId("project-1"),
|
||||
repository: "pingdotgg/t3code",
|
||||
number: 43,
|
||||
url: "https://github.com/pingdotgg/t3code/pull/43",
|
||||
};
|
||||
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
yield* sql`DELETE FROM projection_state`;
|
||||
@@ -92,6 +102,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
branch,
|
||||
worktree_path,
|
||||
linked_pull_request_json,
|
||||
branch_pull_request_json,
|
||||
latest_turn_id,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
@@ -113,6 +124,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
NULL,
|
||||
NULL,
|
||||
'{"projectId":"project-1","repository":"pingdotgg/t3code","number":42,"url":"https://github.com/pingdotgg/t3code/pull/42"}',
|
||||
${encodeThreadLinkedPullRequest(branchPullRequest)},
|
||||
'turn-1',
|
||||
'2026-02-24T00:00:04.000Z',
|
||||
1,
|
||||
@@ -323,6 +335,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
number: 42,
|
||||
url: "https://github.com/pingdotgg/t3code/pull/42",
|
||||
},
|
||||
branchPullRequest,
|
||||
latestTurn: {
|
||||
turnId: asTurnId("turn-1"),
|
||||
state: "completed",
|
||||
@@ -451,6 +464,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
number: 42,
|
||||
url: "https://github.com/pingdotgg/t3code/pull/42",
|
||||
},
|
||||
branchPullRequest,
|
||||
latestTurn: {
|
||||
turnId: asTurnId("turn-1"),
|
||||
state: "completed",
|
||||
@@ -498,6 +512,14 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
assert.deepEqual(threadDetail.value, snapshot.threads[0]);
|
||||
}
|
||||
|
||||
const commandSnapshot = yield* snapshotQuery.getCommandReadModel();
|
||||
assert.deepEqual(commandSnapshot.threads[0]?.branchPullRequest, branchPullRequest);
|
||||
const threadShell = yield* snapshotQuery.getThreadShellById(ThreadId.make("thread-1"));
|
||||
assert.equal(threadShell._tag, "Some");
|
||||
if (threadShell._tag === "Some") {
|
||||
assert.deepEqual(threadShell.value.branchPullRequest, branchPullRequest);
|
||||
}
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_activities (
|
||||
activity_id,
|
||||
@@ -743,6 +765,12 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const branchPullRequest = {
|
||||
projectId: asProjectId("project-archive-test"),
|
||||
repository: "pingdotgg/t3code",
|
||||
number: 43,
|
||||
url: "https://github.com/pingdotgg/t3code/pull/43",
|
||||
};
|
||||
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
yield* sql`DELETE FROM projection_threads`;
|
||||
@@ -849,6 +877,13 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
shellSnapshot.threads.map((thread) => thread.id),
|
||||
[ThreadId.make("thread-active")],
|
||||
);
|
||||
assert.equal(shellSnapshot.threads[0]?.branchPullRequest, null);
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_threads
|
||||
SET branch_pull_request_json = ${encodeThreadLinkedPullRequest(branchPullRequest)}
|
||||
WHERE thread_id = 'thread-archived'
|
||||
`;
|
||||
|
||||
const archivedShellSnapshot = yield* snapshotQuery.getArchivedShellSnapshot();
|
||||
assert.deepEqual(
|
||||
@@ -856,6 +891,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
[ThreadId.make("thread-archived")],
|
||||
);
|
||||
assert.equal(archivedShellSnapshot.threads[0]?.archivedAt, "2026-04-06T00:00:06.000Z");
|
||||
assert.deepEqual(archivedShellSnapshot.threads[0]?.branchPullRequest, branchPullRequest);
|
||||
const activeContext = yield* snapshotQuery.getThreadRuntimeContext(
|
||||
ThreadId.make("thread-active"),
|
||||
);
|
||||
|
||||
@@ -116,6 +116,7 @@ const ProjectionThreadDbRowSchema = ProjectionThread.mapFields(
|
||||
Struct.assign({
|
||||
modelSelection: Schema.fromJsonString(ModelSelection),
|
||||
linkedPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),
|
||||
branchPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||
@@ -500,6 +501,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
branch,
|
||||
worktree_path AS "worktreePath",
|
||||
linked_pull_request_json AS "linkedPullRequest",
|
||||
branch_pull_request_json AS "branchPullRequest",
|
||||
latest_turn_id AS "latestTurnId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -538,6 +540,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
branch,
|
||||
worktree_path AS "worktreePath",
|
||||
linked_pull_request_json AS "linkedPullRequest",
|
||||
branch_pull_request_json AS "branchPullRequest",
|
||||
latest_turn_id AS "latestTurnId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -578,6 +581,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
branch,
|
||||
worktree_path AS "worktreePath",
|
||||
linked_pull_request_json AS "linkedPullRequest",
|
||||
branch_pull_request_json AS "branchPullRequest",
|
||||
latest_turn_id AS "latestTurnId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -1067,6 +1071,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
branch,
|
||||
worktree_path AS "worktreePath",
|
||||
linked_pull_request_json AS "linkedPullRequest",
|
||||
branch_pull_request_json AS "branchPullRequest",
|
||||
latest_turn_id AS "latestTurnId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -2062,6 +2067,7 @@ pending_approval_requests AS (
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
branchPullRequest: row.branchPullRequest,
|
||||
...(row.linkedPullRequest === null
|
||||
? {}
|
||||
: { linkedPullRequest: row.linkedPullRequest }),
|
||||
@@ -2275,6 +2281,7 @@ pending_approval_requests AS (
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
branchPullRequest: row.branchPullRequest,
|
||||
...(row.linkedPullRequest === null
|
||||
? {}
|
||||
: { linkedPullRequest: row.linkedPullRequest }),
|
||||
@@ -2415,6 +2422,7 @@ pending_approval_requests AS (
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
branchPullRequest: row.branchPullRequest,
|
||||
...(row.linkedPullRequest === null
|
||||
? {}
|
||||
: { linkedPullRequest: row.linkedPullRequest }),
|
||||
@@ -2563,6 +2571,7 @@ pending_approval_requests AS (
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
branchPullRequest: row.branchPullRequest,
|
||||
...(row.linkedPullRequest === null
|
||||
? {}
|
||||
: { linkedPullRequest: row.linkedPullRequest }),
|
||||
@@ -2884,6 +2893,7 @@ pending_approval_requests AS (
|
||||
interactionMode: threadRow.value.interactionMode,
|
||||
branch: threadRow.value.branch,
|
||||
worktreePath: threadRow.value.worktreePath,
|
||||
branchPullRequest: threadRow.value.branchPullRequest,
|
||||
...(threadRow.value.linkedPullRequest === null
|
||||
? {}
|
||||
: { linkedPullRequest: threadRow.value.linkedPullRequest }),
|
||||
@@ -3165,6 +3175,7 @@ pending_approval_requests AS (
|
||||
interactionMode: threadRow.value.interactionMode,
|
||||
branch: threadRow.value.branch,
|
||||
worktreePath: threadRow.value.worktreePath,
|
||||
branchPullRequest: threadRow.value.branchPullRequest,
|
||||
...(threadRow.value.linkedPullRequest === null
|
||||
? {}
|
||||
: { linkedPullRequest: threadRow.value.linkedPullRequest }),
|
||||
|
||||
@@ -0,0 +1,613 @@
|
||||
import {
|
||||
EventId,
|
||||
GitManagerError,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationCommand,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationProjectShell,
|
||||
type OrchestrationShellSnapshot,
|
||||
type OrchestrationThreadShell,
|
||||
type PullRequestRef,
|
||||
type PullRequestSummary,
|
||||
type ThreadLinkedPullRequest,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { TestClock } from "effect/testing";
|
||||
|
||||
import { GitManager, type GitBranchPullRequest } from "../git/GitManager.ts";
|
||||
import { PullRequestService } from "../pullRequest/PullRequestService.ts";
|
||||
import { RepositoryIdentityResolver } from "../project/RepositoryIdentityResolver.ts";
|
||||
import { ServerActivation } from "../serverActivation.ts";
|
||||
import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
|
||||
import * as ThreadPullRequestReactor from "./ThreadPullRequestReactor.ts";
|
||||
|
||||
const NOW = "2026-09-01T12:00:00.000Z";
|
||||
const PROJECT_ID = ProjectId.make("project");
|
||||
const REPOSITORY = "owner/repository";
|
||||
const REPOSITORY_KEY = `github.com/${REPOSITORY}`;
|
||||
type SyncCommand = Extract<OrchestrationCommand, { type: "thread.pull-request.sync" }>;
|
||||
|
||||
function reference(number: number): ThreadLinkedPullRequest {
|
||||
return {
|
||||
projectId: PROJECT_ID,
|
||||
repository: REPOSITORY,
|
||||
number,
|
||||
url: `https://github.com/${REPOSITORY}/pull/${number}`,
|
||||
};
|
||||
}
|
||||
|
||||
function branchPullRequest(
|
||||
number = 42,
|
||||
state: GitBranchPullRequest["state"] = "open",
|
||||
): GitBranchPullRequest {
|
||||
return {
|
||||
...reference(number),
|
||||
title: "Branch pull request",
|
||||
baseRef: "main",
|
||||
headRef: "feature",
|
||||
state,
|
||||
updatedAt: NOW,
|
||||
repositoryKey: REPOSITORY_KEY,
|
||||
};
|
||||
}
|
||||
|
||||
function summary(input: PullRequestRef, state: PullRequestSummary["state"]): PullRequestSummary {
|
||||
return {
|
||||
...input,
|
||||
provider: "github",
|
||||
title: "Pull request",
|
||||
url: reference(input.number).url,
|
||||
state,
|
||||
headBranch: "feature",
|
||||
baseBranch: "main",
|
||||
updatedAt: NOW,
|
||||
};
|
||||
}
|
||||
|
||||
function thread(
|
||||
id: string,
|
||||
overrides: Partial<OrchestrationThreadShell> = {},
|
||||
): OrchestrationThreadShell {
|
||||
return {
|
||||
id: ThreadId.make(id),
|
||||
projectId: PROJECT_ID,
|
||||
title: id,
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: "feature",
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: NOW,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const project = {
|
||||
id: PROJECT_ID,
|
||||
title: "Project",
|
||||
workspaceRoot: "/workspace/project",
|
||||
repositoryIdentity: {
|
||||
canonicalKey: REPOSITORY_KEY,
|
||||
displayName: REPOSITORY,
|
||||
rootPath: "/workspace/project",
|
||||
locator: {
|
||||
source: "git-remote",
|
||||
remoteName: "origin",
|
||||
remoteUrl: `[email protected]:${REPOSITORY}.git`,
|
||||
},
|
||||
},
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
} satisfies OrchestrationProjectShell;
|
||||
|
||||
const makeHarness = Effect.fn("makeThreadPullRequestHarness")(function* (options: {
|
||||
readonly threads: ReadonlyArray<OrchestrationThreadShell>;
|
||||
readonly branchPullRequest?: GitManager["Service"]["branchPullRequest"];
|
||||
readonly summary?: PullRequestService["Service"]["summary"];
|
||||
readonly existingWorktrees?: ReadonlyArray<string>;
|
||||
readonly project?: OrchestrationProjectShell;
|
||||
readonly resolveRepositoryIdentity?: RepositoryIdentityResolver["Service"]["resolve"];
|
||||
}) {
|
||||
const activation = yield* Deferred.make<void>();
|
||||
const snapshots = yield* Ref.make<OrchestrationShellSnapshot>({
|
||||
snapshotSequence: 1,
|
||||
projects: [options.project ?? project],
|
||||
threads: options.threads,
|
||||
updatedAt: NOW,
|
||||
});
|
||||
const reads = yield* Queue.unbounded<void>();
|
||||
const events = yield* PubSub.unbounded<OrchestrationEvent>();
|
||||
const commands = yield* Ref.make<ReadonlyArray<SyncCommand>>([]);
|
||||
const branchCalls = yield* Ref.make<
|
||||
ReadonlyArray<{ readonly cwd: string; readonly branch: string; readonly refresh: boolean }>
|
||||
>([]);
|
||||
const summaryCalls = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]);
|
||||
let uuid = 0;
|
||||
const dependencies = Layer.mergeAll(
|
||||
Layer.mock(ProjectionSnapshotQuery)({
|
||||
getShellSnapshot: () =>
|
||||
Ref.get(snapshots).pipe(Effect.tap(() => Queue.offer(reads, undefined))),
|
||||
}),
|
||||
Layer.mock(GitManager)({
|
||||
branchPullRequest: (input, readOptions) =>
|
||||
Ref.update(branchCalls, (calls) => [
|
||||
...calls,
|
||||
{ ...input, refresh: readOptions?.refresh === true },
|
||||
]).pipe(
|
||||
Effect.andThen(options.branchPullRequest?.(input, readOptions) ?? Effect.succeed(null)),
|
||||
),
|
||||
}),
|
||||
Layer.mock(PullRequestService)({
|
||||
summary: (input, readOptions) =>
|
||||
Ref.update(summaryCalls, (calls) => [...calls, input]).pipe(
|
||||
Effect.andThen(
|
||||
options.summary?.(input, readOptions) ?? Effect.succeed(summary(input, "open")),
|
||||
),
|
||||
),
|
||||
}),
|
||||
Layer.mock(RepositoryIdentityResolver)({
|
||||
resolve:
|
||||
options.resolveRepositoryIdentity ??
|
||||
(() => Effect.succeed(options.project?.repositoryIdentity ?? project.repositoryIdentity)),
|
||||
}),
|
||||
Layer.mock(OrchestrationEngineService)({
|
||||
subscribeDomainEvents: PubSub.subscribe(events).pipe(
|
||||
Effect.map((subscription) => Stream.fromSubscription(subscription)),
|
||||
),
|
||||
dispatch: (command) => {
|
||||
if (command.type !== "thread.pull-request.sync") {
|
||||
return Effect.die(`Unexpected command: ${command.type}`);
|
||||
}
|
||||
return Ref.update(commands, (current) => [...current, command]).pipe(
|
||||
Effect.andThen(
|
||||
Ref.updateAndGet(snapshots, (snapshot) => ({
|
||||
...snapshot,
|
||||
snapshotSequence: snapshot.snapshotSequence + 1,
|
||||
threads: snapshot.threads.map((current) =>
|
||||
current.id === command.threadId
|
||||
? {
|
||||
...current,
|
||||
branchPullRequest: command.branchPullRequest,
|
||||
...(command.linkedPullRequest !== undefined
|
||||
? { linkedPullRequest: command.linkedPullRequest }
|
||||
: {}),
|
||||
}
|
||||
: current,
|
||||
),
|
||||
})),
|
||||
),
|
||||
Effect.map((snapshot) => ({ sequence: snapshot.snapshotSequence })),
|
||||
);
|
||||
},
|
||||
}),
|
||||
Layer.succeed(ServerActivation, Deferred.await(activation)),
|
||||
Layer.succeed(
|
||||
Crypto.Crypto,
|
||||
Crypto.make({
|
||||
randomBytes: (size) => new Uint8Array(size).fill(++uuid),
|
||||
digest: (_algorithm, data) => Effect.succeed(data),
|
||||
}),
|
||||
),
|
||||
FileSystem.layerNoop({
|
||||
exists: (path) => Effect.succeed(options.existingWorktrees?.includes(path) ?? false),
|
||||
}),
|
||||
);
|
||||
|
||||
const start = Effect.fn("startThreadPullRequestHarness")(function* () {
|
||||
const reactor = yield* ThreadPullRequestReactor.ThreadPullRequestReactor;
|
||||
yield* reactor.start();
|
||||
yield* Deferred.succeed(activation, undefined);
|
||||
yield* Queue.take(reads);
|
||||
yield* reactor.drain;
|
||||
return reactor;
|
||||
});
|
||||
|
||||
return {
|
||||
start,
|
||||
reads,
|
||||
snapshots,
|
||||
commands,
|
||||
branchCalls,
|
||||
summaryCalls,
|
||||
publish: (event: OrchestrationEvent) => PubSub.publish(events, event),
|
||||
layer: ThreadPullRequestReactor.layer.pipe(Layer.provide(dependencies)),
|
||||
};
|
||||
});
|
||||
|
||||
describe("ThreadPullRequestReactor", () => {
|
||||
it.effect("discovers saved branch PRs without a client and shares branch lookups", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeHarness({
|
||||
threads: [
|
||||
thread("first"),
|
||||
thread("second"),
|
||||
thread("archived", { archivedAt: NOW }),
|
||||
thread("no-branch", { branch: null }),
|
||||
],
|
||||
branchPullRequest: () => Effect.succeed(branchPullRequest()),
|
||||
});
|
||||
yield* Effect.gen(function* () {
|
||||
const reactor = yield* fixture.start();
|
||||
expect(yield* Ref.get(fixture.branchCalls)).toEqual([
|
||||
{ cwd: project.workspaceRoot, branch: "feature", refresh: false },
|
||||
{ cwd: project.workspaceRoot, branch: "feature", refresh: false },
|
||||
]);
|
||||
expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
|
||||
"first",
|
||||
"second",
|
||||
]);
|
||||
expect((yield* Ref.get(fixture.snapshots)).threads[0]?.branchPullRequest).toEqual(
|
||||
reference(42),
|
||||
);
|
||||
|
||||
yield* TestClock.adjust("1 minute");
|
||||
yield* Queue.take(fixture.reads);
|
||||
yield* reactor.drain;
|
||||
expect(yield* Ref.get(fixture.commands)).toHaveLength(2);
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("replaces terminal manual links but preserves open links and explicit unlink", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeHarness({
|
||||
threads: [
|
||||
thread("merged", { linkedPullRequest: reference(1) }),
|
||||
thread("closed", { linkedPullRequest: reference(2) }),
|
||||
thread("open", { linkedPullRequest: reference(3) }),
|
||||
thread("unlinked", { linkedPullRequest: null }),
|
||||
],
|
||||
branchPullRequest: () => Effect.succeed(branchPullRequest()),
|
||||
summary: (input) =>
|
||||
Effect.succeed(
|
||||
summary(
|
||||
input,
|
||||
input.number === 1 ? "merged" : input.number === 2 ? "closed" : "open",
|
||||
),
|
||||
),
|
||||
});
|
||||
yield* Effect.gen(function* () {
|
||||
yield* fixture.start();
|
||||
const snapshot = yield* Ref.get(fixture.snapshots);
|
||||
expect(snapshot.threads.map((current) => current.linkedPullRequest)).toEqual([
|
||||
reference(42),
|
||||
reference(42),
|
||||
reference(3),
|
||||
null,
|
||||
]);
|
||||
expect(
|
||||
snapshot.threads.every((current) => current.branchPullRequest?.number === 42),
|
||||
).toBe(true);
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("refreshes discovery after a turn ends without client demand", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const current = thread("turn-thread");
|
||||
const detected = yield* Ref.make<GitBranchPullRequest | null>(null);
|
||||
const fixture = yield* makeHarness({
|
||||
threads: [current],
|
||||
branchPullRequest: (_input, options) =>
|
||||
options?.refresh
|
||||
? Ref.set(detected, branchPullRequest()).pipe(Effect.andThen(Ref.get(detected)))
|
||||
: Ref.get(detected),
|
||||
});
|
||||
yield* Effect.gen(function* () {
|
||||
const reactor = yield* fixture.start();
|
||||
expect(yield* Ref.get(fixture.commands)).toHaveLength(0);
|
||||
yield* fixture.publish({
|
||||
type: "thread.session-set",
|
||||
sequence: 2,
|
||||
eventId: EventId.make("turn-finished"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: current.id,
|
||||
occurredAt: NOW,
|
||||
commandId: null,
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: current.id,
|
||||
session: {
|
||||
threadId: current.id,
|
||||
status: "ready",
|
||||
providerName: "Codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: NOW,
|
||||
},
|
||||
},
|
||||
});
|
||||
yield* Queue.take(fixture.reads);
|
||||
yield* reactor.drain;
|
||||
expect((yield* Ref.get(fixture.commands))[0]?.branchPullRequest).toEqual(reference(42));
|
||||
expect((yield* Ref.get(fixture.branchCalls)).filter((call) => call.refresh)).toHaveLength(
|
||||
1,
|
||||
);
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses live worktrees and falls back to the project for removed worktrees", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeHarness({
|
||||
threads: [
|
||||
thread("live", { worktreePath: "/workspace/worktree" }),
|
||||
thread("removed", { worktreePath: "/workspace/removed" }),
|
||||
],
|
||||
existingWorktrees: ["/workspace/worktree"],
|
||||
branchPullRequest: () => Effect.succeed(branchPullRequest()),
|
||||
});
|
||||
yield* Effect.gen(function* () {
|
||||
yield* fixture.start();
|
||||
expect(new Set((yield* Ref.get(fixture.branchCalls)).map((call) => call.cwd))).toEqual(
|
||||
new Set(["/workspace/project", "/workspace/worktree"]),
|
||||
);
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("retains only terminal PRs on shared checkouts and clears a removed branch", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeHarness({
|
||||
threads: [
|
||||
thread("terminal", { branch: "main", branchPullRequest: reference(1) }),
|
||||
thread("open", { branchPullRequest: reference(2) }),
|
||||
thread("worktree", {
|
||||
worktreePath: "/workspace/worktree",
|
||||
branchPullRequest: reference(1),
|
||||
}),
|
||||
thread("cleared", {
|
||||
branch: null,
|
||||
branchPullRequest: reference(1),
|
||||
linkedPullRequest: reference(3),
|
||||
}),
|
||||
],
|
||||
summary: (input) =>
|
||||
Effect.succeed(summary(input, input.number === 1 ? "merged" : "open")),
|
||||
});
|
||||
yield* Effect.gen(function* () {
|
||||
yield* fixture.start();
|
||||
const snapshot = yield* Ref.get(fixture.snapshots);
|
||||
expect(snapshot.threads.map((current) => current.branchPullRequest)).toEqual([
|
||||
reference(1),
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
]);
|
||||
expect(snapshot.threads[3]?.linkedPullRequest).toEqual(reference(3));
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("keeps saved links on lookup failures and rejects a different repository", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeHarness({
|
||||
threads: [
|
||||
thread("failed", { branch: "failed", branchPullRequest: reference(1) }),
|
||||
thread("wrong-repository", {
|
||||
branch: "wrong-repository",
|
||||
branchPullRequest: reference(2),
|
||||
}),
|
||||
thread("healthy"),
|
||||
],
|
||||
branchPullRequest: ({ cwd, branch }) =>
|
||||
branch === "failed"
|
||||
? Effect.fail(
|
||||
new GitManagerError({
|
||||
operation: "branchPullRequest",
|
||||
cwd,
|
||||
detail: "Lookup failed",
|
||||
}),
|
||||
)
|
||||
: Effect.succeed({
|
||||
...branchPullRequest(),
|
||||
repositoryKey:
|
||||
branch === "wrong-repository" ? "github.com/other/repository" : REPOSITORY_KEY,
|
||||
}),
|
||||
});
|
||||
yield* Effect.gen(function* () {
|
||||
yield* fixture.start();
|
||||
expect(
|
||||
(yield* Ref.get(fixture.snapshots)).threads.map((current) => current.branchPullRequest),
|
||||
).toEqual([reference(1), reference(2), reference(42)]);
|
||||
expect(yield* Ref.get(fixture.commands)).toHaveLength(1);
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("retries failed settled backfills and stops querying them after success", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const online = yield* Ref.make(false);
|
||||
const fixture = yield* makeHarness({
|
||||
threads: [
|
||||
thread("backfill", { settledOverride: "settled", settledAt: NOW }),
|
||||
thread("known", {
|
||||
branch: "known",
|
||||
settledOverride: "settled",
|
||||
settledAt: NOW,
|
||||
branchPullRequest: reference(1),
|
||||
}),
|
||||
],
|
||||
branchPullRequest: ({ cwd }) =>
|
||||
Ref.get(online).pipe(
|
||||
Effect.flatMap((connected) =>
|
||||
connected
|
||||
? Effect.succeed(branchPullRequest(42, "merged"))
|
||||
: Effect.fail(
|
||||
new GitManagerError({
|
||||
operation: "branchPullRequest",
|
||||
cwd,
|
||||
detail: "Offline",
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
yield* Effect.gen(function* () {
|
||||
const reactor = yield* fixture.start();
|
||||
expect(yield* Ref.get(fixture.commands)).toHaveLength(0);
|
||||
yield* Ref.set(online, true);
|
||||
yield* TestClock.adjust("1 minute");
|
||||
yield* Queue.take(fixture.reads);
|
||||
yield* reactor.drain;
|
||||
expect((yield* Ref.get(fixture.commands))[0]?.threadId).toBe("backfill");
|
||||
yield* TestClock.adjust("1 minute");
|
||||
yield* Queue.take(fixture.reads);
|
||||
yield* reactor.drain;
|
||||
expect((yield* Ref.get(fixture.branchCalls)).map((call) => call.branch)).toEqual([
|
||||
"feature",
|
||||
"feature",
|
||||
"feature",
|
||||
]);
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("stops retrying a settled backfill after repeated lookup failures", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeHarness({
|
||||
threads: [thread("backfill", { settledOverride: "settled", settledAt: NOW })],
|
||||
branchPullRequest: ({ cwd }) =>
|
||||
Effect.fail(
|
||||
new GitManagerError({ operation: "branchPullRequest", cwd, detail: "No gh" }),
|
||||
),
|
||||
});
|
||||
yield* Effect.gen(function* () {
|
||||
const reactor = yield* fixture.start();
|
||||
for (
|
||||
let attempt = 1;
|
||||
attempt < ThreadPullRequestReactor.BACKFILL_ATTEMPTS + 2;
|
||||
attempt++
|
||||
) {
|
||||
yield* TestClock.adjust("1 minute");
|
||||
yield* Queue.take(fixture.reads);
|
||||
yield* reactor.drain;
|
||||
}
|
||||
expect(yield* Ref.get(fixture.branchCalls)).toHaveLength(
|
||||
ThreadPullRequestReactor.BACKFILL_ATTEMPTS,
|
||||
);
|
||||
expect(yield* Ref.get(fixture.commands)).toHaveLength(0);
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("matches Azure SSH projects to HTTPS PRs with the provider repository selector", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeHarness({
|
||||
threads: [thread("azure")],
|
||||
project: {
|
||||
...project,
|
||||
repositoryIdentity: {
|
||||
canonicalKey: "ssh.dev.azure.com/v3/org/project/repository",
|
||||
displayName: "v3/org/project/repository",
|
||||
name: "repository",
|
||||
provider: "azure-devops",
|
||||
rootPath: project.workspaceRoot,
|
||||
locator: {
|
||||
source: "git-remote",
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:v3/org/project/repository",
|
||||
},
|
||||
},
|
||||
},
|
||||
branchPullRequest: () =>
|
||||
Effect.succeed({
|
||||
...branchPullRequest(),
|
||||
repositoryKey: "dev.azure.com/org/project/_git/repository",
|
||||
url: "https://dev.azure.com/org/project/_git/repository/pullrequest/42",
|
||||
}),
|
||||
});
|
||||
yield* Effect.gen(function* () {
|
||||
yield* fixture.start();
|
||||
expect((yield* Ref.get(fixture.commands))[0]?.branchPullRequest).toEqual({
|
||||
projectId: PROJECT_ID,
|
||||
repository: "repository",
|
||||
number: 42,
|
||||
url: "https://dev.azure.com/org/project/_git/repository/pullrequest/42",
|
||||
});
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect.each(["primary", "branch"] as const)(
|
||||
"rejects the group's links if the %s remote changes during a summary read",
|
||||
(changedRemote) =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const identity = yield* Ref.make(project.repositoryIdentity);
|
||||
const detected = yield* Ref.make(branchPullRequest());
|
||||
const fixture = yield* makeHarness({
|
||||
threads: [thread("manual", { linkedPullRequest: reference(1) }), thread("automatic")],
|
||||
branchPullRequest: () => Ref.get(detected),
|
||||
resolveRepositoryIdentity: (_cwd, options) =>
|
||||
options?.refresh ? Ref.get(identity) : Effect.succeed(project.repositoryIdentity),
|
||||
summary: (input) =>
|
||||
(changedRemote === "primary"
|
||||
? Ref.set(identity, {
|
||||
...project.repositoryIdentity,
|
||||
canonicalKey: "github.com/other/repository",
|
||||
displayName: "other/repository",
|
||||
})
|
||||
: Ref.set(detected, {
|
||||
...branchPullRequest(99),
|
||||
repositoryKey: "github.com/other/repository",
|
||||
url: "https://github.com/other/repository/pull/99",
|
||||
})
|
||||
).pipe(Effect.as(summary(input, "merged"))),
|
||||
});
|
||||
yield* Effect.gen(function* () {
|
||||
yield* fixture.start();
|
||||
expect(yield* Ref.get(fixture.commands)).toEqual([]);
|
||||
expect((yield* Ref.get(fixture.snapshots)).threads[0]?.linkedPullRequest).toEqual(
|
||||
reference(1),
|
||||
);
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,371 @@
|
||||
import {
|
||||
CommandId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationProjectShell,
|
||||
type ThreadId,
|
||||
type ThreadLinkedPullRequest,
|
||||
} from "@t3tools/contracts";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as GitManager from "../git/GitManager.ts";
|
||||
import * as PullRequestService from "../pullRequest/PullRequestService.ts";
|
||||
import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
|
||||
import { forkParked } from "../serverActivation.ts";
|
||||
import * as OrchestrationEngine from "./Services/OrchestrationEngine.ts";
|
||||
import * as ProjectionSnapshotQuery from "./Services/ProjectionSnapshotQuery.ts";
|
||||
|
||||
export class ThreadPullRequestReactor extends Context.Service<
|
||||
ThreadPullRequestReactor,
|
||||
{
|
||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly drain: Effect.Effect<void>;
|
||||
}
|
||||
>()("t3/orchestration/ThreadPullRequestReactor") {}
|
||||
|
||||
function samePullRequest(
|
||||
left: ThreadLinkedPullRequest | null | undefined,
|
||||
right: ThreadLinkedPullRequest | null,
|
||||
): boolean {
|
||||
if (left == null || right === null) return left == null && right === null;
|
||||
return (
|
||||
left.projectId === right.projectId &&
|
||||
left.repository.toLowerCase() === right.repository.toLowerCase() &&
|
||||
left.number === right.number &&
|
||||
left.url === right.url
|
||||
);
|
||||
}
|
||||
|
||||
/** Startup lookups per settled thread before discovery gives up on it. */
|
||||
export const BACKFILL_ATTEMPTS = 5;
|
||||
|
||||
interface RefreshRequest {
|
||||
readonly threadId: ThreadId | null;
|
||||
readonly refresh: boolean;
|
||||
readonly backfill?: boolean;
|
||||
}
|
||||
|
||||
function canonicalRepositoryKey(key: string): string {
|
||||
return key
|
||||
.replace(
|
||||
/^(?:ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)\/v3\/([^/]+)\/([^/]+)\/([^/]+)$/u,
|
||||
"dev.azure.com/$1/$2/_git/$3",
|
||||
)
|
||||
.replace(
|
||||
/^([^.]+)\.visualstudio\.com\/(?:defaultcollection\/)?([^/]+)\/_git\/([^/]+)$/u,
|
||||
"dev.azure.com/$1/$2/_git/$3",
|
||||
);
|
||||
}
|
||||
|
||||
export function pullRequestMatchesProject(
|
||||
pullRequest: GitManager.GitBranchPullRequest,
|
||||
project: OrchestrationProjectShell,
|
||||
): boolean {
|
||||
return (
|
||||
pullRequest.repositoryKey !== null &&
|
||||
project.repositoryIdentity != null &&
|
||||
canonicalRepositoryKey(pullRequest.repositoryKey) ===
|
||||
canonicalRepositoryKey(project.repositoryIdentity.canonicalKey)
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const engine = yield* OrchestrationEngine.OrchestrationEngineService;
|
||||
const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
const git = yield* GitManager.GitManager;
|
||||
const pullRequests = yield* PullRequestService.PullRequestService;
|
||||
const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
// Settled threads get one link discovery at startup. Failed lookups retry on
|
||||
// the periodic pass a few times, then stop until the thread changes or the
|
||||
// server restarts, so a missing or logged-out CLI cannot loop forever.
|
||||
const pendingBackfill = new Map<ThreadId, number>();
|
||||
const finishBackfill = (threads: ReadonlyArray<{ readonly id: ThreadId }>) => {
|
||||
for (const thread of threads) pendingBackfill.delete(thread.id);
|
||||
};
|
||||
const failBackfill = (threads: ReadonlyArray<{ readonly id: ThreadId }>) => {
|
||||
for (const thread of threads) {
|
||||
const remaining = pendingBackfill.get(thread.id);
|
||||
if (remaining === undefined) continue;
|
||||
if (remaining <= 1) pendingBackfill.delete(thread.id);
|
||||
else pendingBackfill.set(thread.id, remaining - 1);
|
||||
}
|
||||
};
|
||||
|
||||
const synchronize = Effect.fn("ThreadPullRequestReactor.synchronize")(function* (
|
||||
request: RefreshRequest,
|
||||
) {
|
||||
const snapshot = yield* snapshots.getShellSnapshot();
|
||||
const projects = new Map(snapshot.projects.map((project) => [project.id, project]));
|
||||
if (request.backfill) {
|
||||
for (const thread of snapshot.threads) {
|
||||
if (thread.settledOverride === "settled" && thread.branchPullRequest == null) {
|
||||
pendingBackfill.set(thread.id, BACKFILL_ATTEMPTS);
|
||||
}
|
||||
}
|
||||
}
|
||||
const threadIds = new Set(snapshot.threads.map((thread) => thread.id));
|
||||
for (const threadId of pendingBackfill.keys()) {
|
||||
if (!threadIds.has(threadId)) pendingBackfill.delete(threadId);
|
||||
}
|
||||
const threads = snapshot.threads.filter(
|
||||
(thread) =>
|
||||
thread.archivedAt === null &&
|
||||
(request.threadId === null || thread.id === request.threadId) &&
|
||||
(thread.settledOverride !== "settled" ||
|
||||
request.threadId !== null ||
|
||||
pendingBackfill.has(thread.id)) &&
|
||||
(thread.branch !== null || thread.branchPullRequest != null),
|
||||
);
|
||||
const groups = Map.groupBy(threads, (thread) =>
|
||||
JSON.stringify([thread.projectId, thread.worktreePath, thread.branch]),
|
||||
);
|
||||
|
||||
yield* Effect.forEach(
|
||||
groups.values(),
|
||||
(group) =>
|
||||
Effect.gen(function* () {
|
||||
const first = group[0]!;
|
||||
const project = projects.get(first.projectId);
|
||||
if (project === undefined) return finishBackfill(group);
|
||||
const repository = PullRequestService.repositoryIdentityOf(project);
|
||||
if (first.branch !== null && repository === null) return finishBackfill(group);
|
||||
const worktreeExists =
|
||||
first.worktreePath !== null && (yield* fileSystem.exists(first.worktreePath));
|
||||
const cwd =
|
||||
worktreeExists && first.worktreePath !== null
|
||||
? first.worktreePath
|
||||
: project.workspaceRoot;
|
||||
const detected =
|
||||
first.branch === null
|
||||
? null
|
||||
: yield* git.branchPullRequest(
|
||||
{ cwd, branch: first.branch },
|
||||
{ refresh: request.refresh },
|
||||
);
|
||||
// A worktree can have different remotes, and the project identity
|
||||
// can lag a remote edit. Do not attach its PR to the wrong repository.
|
||||
if (detected !== null && !pullRequestMatchesProject(detected, project)) {
|
||||
return finishBackfill(group);
|
||||
}
|
||||
const detectedReference =
|
||||
detected !== null && repository !== null
|
||||
? {
|
||||
projectId: project.id,
|
||||
repository,
|
||||
number: detected.number,
|
||||
url: detected.url,
|
||||
}
|
||||
: null;
|
||||
|
||||
const plans = yield* Effect.forEach(group, (thread) =>
|
||||
Effect.gen(function* () {
|
||||
let branchPullRequest = detectedReference;
|
||||
// Shared checkouts often return to the default branch after
|
||||
// a merge. Keep that thread's terminal PR across the change.
|
||||
if (
|
||||
branchPullRequest === null &&
|
||||
thread.branch !== null &&
|
||||
thread.worktreePath === null &&
|
||||
thread.branchPullRequest != null
|
||||
) {
|
||||
const previous = yield* pullRequests.summary(thread.branchPullRequest, {
|
||||
recoverTransientFailure: false,
|
||||
});
|
||||
if (previous.state === "merged" || previous.state === "closed") {
|
||||
branchPullRequest = thread.branchPullRequest;
|
||||
}
|
||||
}
|
||||
|
||||
let replacement: ThreadLinkedPullRequest | undefined;
|
||||
if (
|
||||
thread.linkedPullRequest != null &&
|
||||
detected?.state === "open" &&
|
||||
detectedReference !== null &&
|
||||
!samePullRequest(thread.linkedPullRequest, detectedReference)
|
||||
) {
|
||||
const linked = yield* pullRequests.summary(thread.linkedPullRequest, {
|
||||
recoverTransientFailure: false,
|
||||
});
|
||||
if (linked.state === "merged" || linked.state === "closed") {
|
||||
replacement = detectedReference;
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
samePullRequest(thread.branchPullRequest, branchPullRequest) &&
|
||||
replacement === undefined
|
||||
) {
|
||||
pendingBackfill.delete(thread.id);
|
||||
return null;
|
||||
}
|
||||
return { thread, branchPullRequest, replacement };
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterruptsOnly(cause)
|
||||
? Effect.failCause(cause)
|
||||
: Effect.logWarning("thread pull request discovery failed", {
|
||||
threadId: thread.id,
|
||||
cause: Cause.pretty(cause),
|
||||
}).pipe(
|
||||
Effect.tap(() => Effect.sync(() => failBackfill([thread]))),
|
||||
Effect.as(null),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const updates = plans.filter((plan) => plan !== null);
|
||||
if (updates.length === 0) return;
|
||||
|
||||
if (detected !== null && first.branch !== null) {
|
||||
// Summary reads can outlast a remote edit. Recheck the branch and
|
||||
// the project's primary remote before saving the group's links.
|
||||
const current = yield* git.branchPullRequest({ cwd, branch: first.branch });
|
||||
const currentIdentity = yield* repositoryIdentities.resolve(project.workspaceRoot, {
|
||||
refresh: true,
|
||||
});
|
||||
if (
|
||||
current === null ||
|
||||
current.number !== detected.number ||
|
||||
current.url !== detected.url ||
|
||||
current.state !== detected.state ||
|
||||
current.repositoryKey !== detected.repositoryKey ||
|
||||
!pullRequestMatchesProject(current, {
|
||||
...project,
|
||||
repositoryIdentity: currentIdentity,
|
||||
})
|
||||
) {
|
||||
return failBackfill(updates.map((update) => update.thread));
|
||||
}
|
||||
}
|
||||
|
||||
yield* Effect.forEach(
|
||||
updates,
|
||||
({ thread, branchPullRequest, replacement }) =>
|
||||
Effect.gen(function* () {
|
||||
const uuid = yield* crypto.randomUUIDv4;
|
||||
yield* engine.dispatch({
|
||||
type: "thread.pull-request.sync",
|
||||
commandId: CommandId.make(`server:thread-pull-request:${thread.id}:${uuid}`),
|
||||
threadId: thread.id,
|
||||
projectId: project.id,
|
||||
snapshotSequence: snapshot.snapshotSequence,
|
||||
expected: {
|
||||
workspaceRoot: project.workspaceRoot,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
linkedPullRequest: thread.linkedPullRequest ?? null,
|
||||
branchPullRequest: thread.branchPullRequest ?? null,
|
||||
},
|
||||
branchPullRequest,
|
||||
...(replacement !== undefined ? { linkedPullRequest: replacement } : {}),
|
||||
});
|
||||
pendingBackfill.delete(thread.id);
|
||||
}).pipe(
|
||||
// The thread changed since the lookup. Its own events requeue it.
|
||||
Effect.catchTags({
|
||||
OrchestrationCommandInvariantError: () =>
|
||||
Effect.sync(() => finishBackfill([thread])),
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterruptsOnly(cause)
|
||||
? Effect.failCause(cause)
|
||||
: Effect.logWarning("thread pull request update failed", {
|
||||
threadId: thread.id,
|
||||
cause: Cause.pretty(cause),
|
||||
}).pipe(Effect.tap(() => Effect.sync(() => failBackfill([thread])))),
|
||||
),
|
||||
),
|
||||
{ discard: true },
|
||||
);
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterruptsOnly(cause)
|
||||
? Effect.failCause(cause)
|
||||
: Effect.logWarning("thread branch pull request lookup failed", {
|
||||
threadIds: group.map((thread) => thread.id),
|
||||
cause: Cause.pretty(cause),
|
||||
}).pipe(Effect.tap(() => Effect.sync(() => failBackfill(group)))),
|
||||
),
|
||||
),
|
||||
{ concurrency: 8, discard: true },
|
||||
);
|
||||
});
|
||||
|
||||
const worker = yield* makeDrainableWorker((request: RefreshRequest) =>
|
||||
synchronize(request).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterruptsOnly(cause)
|
||||
? Effect.failCause(cause)
|
||||
: Effect.logWarning("thread pull request refresh failed", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const processEvent = (event: OrchestrationEvent) => {
|
||||
switch (event.type) {
|
||||
case "thread.created":
|
||||
case "thread.unarchived":
|
||||
return worker.enqueue({ threadId: event.payload.threadId, refresh: false });
|
||||
case "thread.meta-updated":
|
||||
if (
|
||||
event.payload.branchPullRequest === undefined &&
|
||||
(event.payload.branch !== undefined ||
|
||||
event.payload.worktreePath !== undefined ||
|
||||
event.payload.linkedPullRequest !== undefined)
|
||||
) {
|
||||
return worker.enqueue({ threadId: event.payload.threadId, refresh: false });
|
||||
}
|
||||
break;
|
||||
case "thread.session-set":
|
||||
if (
|
||||
event.payload.session.status !== "running" &&
|
||||
event.payload.session.status !== "starting"
|
||||
) {
|
||||
return worker.enqueue({ threadId: event.payload.threadId, refresh: true });
|
||||
}
|
||||
break;
|
||||
case "thread.turn-diff-completed":
|
||||
case "thread.unsettled":
|
||||
return worker.enqueue({ threadId: event.payload.threadId, refresh: true });
|
||||
case "project.meta-updated":
|
||||
if (event.payload.workspaceRoot !== undefined) {
|
||||
return worker.enqueue({ threadId: null, refresh: false });
|
||||
}
|
||||
break;
|
||||
}
|
||||
return Effect.void;
|
||||
};
|
||||
|
||||
const start = Effect.fn("ThreadPullRequestReactor.start")(function* () {
|
||||
const events = yield* engine.subscribeDomainEvents;
|
||||
yield* forkParked(Stream.runForEach(events, processEvent));
|
||||
// Run without client demand. Saved branch lookups share GitManager's
|
||||
// provider cache and retry backoff with status and automatic settlement.
|
||||
yield* forkParked(
|
||||
Effect.gen(function* () {
|
||||
yield* worker.enqueue({ threadId: null, refresh: false, backfill: true });
|
||||
yield* worker.drain;
|
||||
yield* Effect.gen(function* () {
|
||||
yield* worker.enqueue({ threadId: null, refresh: false });
|
||||
yield* worker.drain;
|
||||
}).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.delay("1 minute"));
|
||||
}).pipe(Effect.asVoid),
|
||||
);
|
||||
});
|
||||
|
||||
return { start, drain: worker.drain } satisfies ThreadPullRequestReactor["Service"];
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ThreadPullRequestReactor, make);
|
||||
@@ -25,7 +25,7 @@ import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { TestClock } from "effect/testing";
|
||||
|
||||
import { GitManager } from "../git/GitManager.ts";
|
||||
import { GitManager, type GitBranchPullRequest } from "../git/GitManager.ts";
|
||||
import {
|
||||
PullRequestService,
|
||||
type PullRequestMergeEvent,
|
||||
@@ -132,6 +132,24 @@ function makePullRequestSummary(input: {
|
||||
};
|
||||
}
|
||||
|
||||
function makeBranchPullRequest(
|
||||
state: GitBranchPullRequest["state"],
|
||||
updatedAt: string | null = NOW,
|
||||
): GitBranchPullRequest {
|
||||
return {
|
||||
number: 42,
|
||||
title: "Branch pull request",
|
||||
url: "https://example.test/owner/repository/pull/42",
|
||||
baseRef: "main",
|
||||
headRef: "saved-feature",
|
||||
repositoryKey: "example.test/owner/repository",
|
||||
state,
|
||||
updatedAt,
|
||||
closedAt: state === "closed" ? updatedAt : null,
|
||||
mergedAt: state === "merged" ? updatedAt : null,
|
||||
};
|
||||
}
|
||||
|
||||
interface HarnessOptions {
|
||||
readonly snapshot: OrchestrationShellSnapshot;
|
||||
readonly settings?: ServerSettings;
|
||||
@@ -173,9 +191,9 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
|
||||
return next;
|
||||
});
|
||||
|
||||
const branchPullRequest: GitManager["Service"]["branchPullRequest"] = (input) =>
|
||||
const branchPullRequest: GitManager["Service"]["branchPullRequest"] = (input, readOptions) =>
|
||||
Ref.update(branchCalls, (calls) => [...calls, input]).pipe(
|
||||
Effect.andThen(options.branchPullRequest?.(input) ?? Effect.succeed(null)),
|
||||
Effect.andThen(options.branchPullRequest?.(input, readOptions) ?? Effect.succeed(null)),
|
||||
);
|
||||
const pullRequestSummary: PullRequestService["Service"]["summary"] = (input, readOptions) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -281,6 +299,83 @@ const startHarness = Effect.fn("startThreadSettlementHarness")(function* (
|
||||
});
|
||||
|
||||
describe("ThreadSettlementReactor", () => {
|
||||
it.effect("uses saved PRs without settling resumed threads or branches with newer PRs", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
yield* TestClock.setTime(Date.parse(NOW));
|
||||
const previous = {
|
||||
projectId: PROJECT_ID,
|
||||
repository: "owner/repository",
|
||||
number: 1,
|
||||
url: "https://example.test/owner/repository/pull/1",
|
||||
};
|
||||
const project = {
|
||||
...makeProject(),
|
||||
repositoryIdentity: {
|
||||
canonicalKey: "example.test/owner/repository",
|
||||
rootPath: "/workspace/project",
|
||||
displayName: "owner/repository",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "https://example.test/owner/repository.git",
|
||||
},
|
||||
},
|
||||
};
|
||||
const fixture = yield* makeHarness({
|
||||
snapshot: makeSnapshot(
|
||||
[
|
||||
makeThread("retained-terminal", { branch: "main", branchPullRequest: previous }),
|
||||
makeThread("reused-manual", { branch: "reused", linkedPullRequest: previous }),
|
||||
makeThread("reused-detected", { branch: "reused", branchPullRequest: previous }),
|
||||
makeThread("foreign-branch-pr", { branch: "foreign", linkedPullRequest: previous }),
|
||||
makeThread("resumed-manual", {
|
||||
branch: "main",
|
||||
linkedPullRequest: previous,
|
||||
latestUserMessageAt: "2026-08-28T00:00:00.000Z",
|
||||
}),
|
||||
makeThread("resumed-detected", {
|
||||
branch: "main",
|
||||
branchPullRequest: previous,
|
||||
latestUserMessageAt: "2026-08-28T00:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
[project],
|
||||
),
|
||||
settings: {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
sidebarAutoSettleAfterDays: null,
|
||||
sidebarAutoSettleOnMerge: true,
|
||||
},
|
||||
branchPullRequest: ({ branch }, options) =>
|
||||
Effect.succeed(
|
||||
branch === "reused"
|
||||
? makeBranchPullRequest(options?.refresh ? "open" : "merged")
|
||||
: branch === "foreign"
|
||||
? {
|
||||
...makeBranchPullRequest("open"),
|
||||
repositoryKey: "example.test/another/repository",
|
||||
}
|
||||
: null,
|
||||
),
|
||||
pullRequestSummary: (input) =>
|
||||
Effect.succeed({
|
||||
...makePullRequestSummary({ ...input, state: "merged" }),
|
||||
mergedAt: "2026-08-27T00:00:00.000Z",
|
||||
}),
|
||||
});
|
||||
yield* Effect.gen(function* () {
|
||||
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
|
||||
yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
|
||||
assert.deepStrictEqual(
|
||||
new Set((yield* Ref.get(fixture.commands)).map((command) => command.threadId)),
|
||||
new Set([ThreadId.make("retained-terminal"), ThreadId.make("foreign-branch-pr")]),
|
||||
);
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("starts without clients and skips protected threads before pull request lookup", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
@@ -375,9 +470,7 @@ describe("ThreadSettlementReactor", () => {
|
||||
}),
|
||||
]),
|
||||
branchPullRequest: () =>
|
||||
Ref.get(pullRequest).pipe(
|
||||
Effect.map((state) => ({ state, updatedAt: NOW, closedAt: NOW, mergedAt: NOW })),
|
||||
),
|
||||
Ref.get(pullRequest).pipe(Effect.map((state) => makeBranchPullRequest(state))),
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
@@ -430,10 +523,10 @@ describe("ThreadSettlementReactor", () => {
|
||||
Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
|
||||
Effect.flatMap((count) =>
|
||||
count === 1
|
||||
? Effect.succeed({ state: "open" as const, updatedAt: NOW })
|
||||
? Effect.succeed(makeBranchPullRequest("open"))
|
||||
: Deferred.succeed(periodicLookupStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(releasePeriodicLookup)),
|
||||
Effect.as({ state: "open" as const, updatedAt: NOW }),
|
||||
Effect.as(makeBranchPullRequest("open")),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -477,12 +570,7 @@ describe("ThreadSettlementReactor", () => {
|
||||
]),
|
||||
branchPullRequest: () =>
|
||||
Ref.get(state).pipe(
|
||||
Effect.map((pullRequestState) => ({
|
||||
state: pullRequestState,
|
||||
updatedAt: NOW,
|
||||
closedAt: NOW,
|
||||
mergedAt: NOW,
|
||||
})),
|
||||
Effect.map((pullRequestState) => makeBranchPullRequest(pullRequestState)),
|
||||
),
|
||||
onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
|
||||
});
|
||||
@@ -618,12 +706,7 @@ describe("ThreadSettlementReactor", () => {
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.andThen(Ref.get(state)),
|
||||
Effect.map((pullRequestState) => ({
|
||||
state: pullRequestState,
|
||||
updatedAt: NOW,
|
||||
closedAt: NOW,
|
||||
mergedAt: NOW,
|
||||
})),
|
||||
Effect.map((pullRequestState) => makeBranchPullRequest(pullRequestState)),
|
||||
),
|
||||
});
|
||||
|
||||
@@ -896,8 +979,7 @@ describe("ThreadSettlementReactor", () => {
|
||||
makeProject(LINKED_PROJECT_ID, "/workspace/linked-root"),
|
||||
],
|
||||
),
|
||||
branchPullRequest: () =>
|
||||
Effect.succeed({ state: "closed", updatedAt: NOW, closedAt: NOW }),
|
||||
branchPullRequest: () => Effect.succeed(makeBranchPullRequest("closed")),
|
||||
pullRequestSummary: (input) =>
|
||||
Effect.succeed(makePullRequestSummary({ ...input, state: "merged" })),
|
||||
});
|
||||
|
||||
@@ -17,6 +17,7 @@ import * as ServerSettings from "../serverSettings.ts";
|
||||
import { forkParked } from "../serverActivation.ts";
|
||||
import * as OrchestrationEngine from "./Services/OrchestrationEngine.ts";
|
||||
import * as ProjectionSnapshotQuery from "./Services/ProjectionSnapshotQuery.ts";
|
||||
import { pullRequestMatchesProject } from "./ThreadPullRequestReactor.ts";
|
||||
import {
|
||||
isAutoSettlementCandidate,
|
||||
resolveAutoSettlementAt,
|
||||
@@ -46,10 +47,8 @@ export const make = Effect.gen(function* () {
|
||||
const snapshot = yield* snapshots.getShellSnapshot();
|
||||
const now = DateTime.formatIso(yield* DateTime.now);
|
||||
const projects = new Map(snapshot.projects.map((project) => [project.id, project]));
|
||||
// A merge event re-sweeps every candidate, not just the threads linked to
|
||||
// the merged pull request: most threads carry no link and settle from
|
||||
// their branch lookup, which would otherwise wait for the next minute's
|
||||
// sweep on a possibly stale cached answer.
|
||||
// A merge rechecks all candidates, including branches that discovery has
|
||||
// not linked yet. Those lookups can still have cached the PR as open.
|
||||
const candidates = snapshot.threads.filter((thread) => isAutoSettlementCandidate(thread, now));
|
||||
|
||||
// Return the thread when it still needs a pull request decision. A rejected
|
||||
@@ -101,14 +100,14 @@ export const make = Effect.gen(function* () {
|
||||
},
|
||||
)).filter((thread) => thread !== null);
|
||||
|
||||
// Use the same cwd as the sidebar so both paths share GitManager's PR cache.
|
||||
// Use the same cwd as PR discovery so both paths share GitManager's cache.
|
||||
const lookupCwdByThreadId = new Map<string, string>();
|
||||
yield* Effect.forEach(
|
||||
lookupCandidates,
|
||||
(thread) =>
|
||||
Effect.gen(function* () {
|
||||
const project = projects.get(thread.projectId);
|
||||
if (project === undefined || thread.linkedPullRequest != null) return;
|
||||
if (project === undefined || thread.branch === null) return;
|
||||
const worktreeExists =
|
||||
thread.worktreePath !== null &&
|
||||
(yield* fileSystem.exists(thread.worktreePath).pipe(Effect.orElseSucceed(() => false)));
|
||||
@@ -122,12 +121,8 @@ export const make = Effect.gen(function* () {
|
||||
{ concurrency: 8, discard: true },
|
||||
);
|
||||
if (mergedPullRequest !== null) {
|
||||
// The merge just confirmed a terminal state the lookup caches can still
|
||||
// call open (branch answers live two minutes, the sweep runs every
|
||||
// minute). Drop the swept checkouts' cached answers so the merge settles
|
||||
// its branch threads now instead of on a later sweep. Threads linked to
|
||||
// the merged pull request settle from the event itself below and need no
|
||||
// lookup, so they are absent from this map by construction.
|
||||
// The merge confirmed a state the branch cache can still call open.
|
||||
// Recheck those branches now instead of waiting for cache expiry.
|
||||
const cwds = [...new Set(lookupCwdByThreadId.values())];
|
||||
yield* Effect.forEach(cwds, (cwd) => git.invalidateStatus(cwd), {
|
||||
concurrency: 8,
|
||||
@@ -135,12 +130,15 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
const lookupKey = (thread: (typeof candidates)[number]) => {
|
||||
if (thread.linkedPullRequest != null) {
|
||||
const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
|
||||
if (reference != null) {
|
||||
return JSON.stringify([
|
||||
"linked",
|
||||
thread.linkedPullRequest.projectId,
|
||||
thread.linkedPullRequest.repository,
|
||||
thread.linkedPullRequest.number,
|
||||
reference.projectId,
|
||||
reference.repository,
|
||||
reference.number,
|
||||
lookupCwdByThreadId.get(thread.id),
|
||||
thread.branch,
|
||||
]);
|
||||
}
|
||||
if (thread.branch === null) return JSON.stringify(["none", thread.id]);
|
||||
@@ -154,35 +152,47 @@ export const make = Effect.gen(function* () {
|
||||
const pullRequestFor = Effect.fn("ThreadSettlementReactor.pullRequestFor")(function* (
|
||||
thread: (typeof candidates)[number],
|
||||
) {
|
||||
if (thread.linkedPullRequest != null) {
|
||||
// The event carries the merged state, so only the threads linked to
|
||||
// that exact pull request settle from it. Every other linked thread
|
||||
// falls through to a fresh summary lookup below: the merge sweep
|
||||
// covers all candidates, and an unrelated merge must never settle
|
||||
// them.
|
||||
if (
|
||||
const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
|
||||
if (reference != null) {
|
||||
const matchesMerge =
|
||||
mergedPullRequest !== null &&
|
||||
thread.linkedPullRequest.projectId === mergedPullRequest.projectId &&
|
||||
thread.linkedPullRequest.repository.toLowerCase() ===
|
||||
mergedPullRequest.repository.toLowerCase() &&
|
||||
thread.linkedPullRequest.number === mergedPullRequest.number
|
||||
) {
|
||||
return {
|
||||
state: "merged",
|
||||
mergedAt: mergedPullRequest.mergedAt,
|
||||
} satisfies SettlementPullRequest;
|
||||
}
|
||||
if (!projects.has(thread.linkedPullRequest.projectId)) {
|
||||
reference.projectId === mergedPullRequest.projectId &&
|
||||
reference.repository.toLowerCase() === mergedPullRequest.repository.toLowerCase() &&
|
||||
reference.number === mergedPullRequest.number;
|
||||
if (!matchesMerge && !projects.has(reference.projectId)) {
|
||||
return yield* Effect.die(new Error("linked pull request project not found"));
|
||||
}
|
||||
const summary = yield* pullRequests.summary(
|
||||
{
|
||||
projectId: thread.linkedPullRequest.projectId,
|
||||
repository: thread.linkedPullRequest.repository,
|
||||
number: thread.linkedPullRequest.number,
|
||||
},
|
||||
{ recoverTransientFailure: false },
|
||||
);
|
||||
const summary = matchesMerge
|
||||
? ({
|
||||
state: "merged",
|
||||
closedAt: null,
|
||||
mergedAt: mergedPullRequest.mergedAt,
|
||||
} satisfies SettlementPullRequest)
|
||||
: yield* pullRequests.summary(
|
||||
{
|
||||
projectId: reference.projectId,
|
||||
repository: reference.repository,
|
||||
number: reference.number,
|
||||
},
|
||||
{ recoverTransientFailure: false },
|
||||
);
|
||||
const cwd = lookupCwdByThreadId.get(thread.id);
|
||||
if (summary.state !== "open" && thread.branch !== null && cwd !== undefined) {
|
||||
// A reused branch can already have a new open PR while discovery
|
||||
// is replacing its old link. Do not let settlement win that race.
|
||||
const current = yield* git.branchPullRequest(
|
||||
{ cwd, branch: thread.branch },
|
||||
{ refresh: true },
|
||||
);
|
||||
const project = projects.get(thread.projectId);
|
||||
if (
|
||||
current?.state === "open" &&
|
||||
project !== undefined &&
|
||||
pullRequestMatchesProject(current, project)
|
||||
) {
|
||||
return current;
|
||||
}
|
||||
}
|
||||
return {
|
||||
state: summary.state,
|
||||
closedAt: summary.closedAt ?? null,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
EventId,
|
||||
MessageId,
|
||||
ThreadLinkedPullRequest,
|
||||
UserInputRequestedPayload,
|
||||
isImportedAgentSessionMessageId,
|
||||
type OrchestrationCommand,
|
||||
@@ -38,6 +39,7 @@ import { threadHasQueuedTurnStart } from "./ThreadSettlementPolicy.ts";
|
||||
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
const decodeUserInputRequestedPayload = Schema.decodeUnknownOption(UserInputRequestedPayload);
|
||||
const threadPullRequestLinksEqual = Schema.toEquivalence(Schema.NullOr(ThreadLinkedPullRequest));
|
||||
|
||||
/**
|
||||
* Blocked-on-you work derived from the thread's retained activities: an
|
||||
@@ -836,6 +838,63 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.pull-request.sync": {
|
||||
const thread = yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
if (thread.deletedAt !== null) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} was deleted before pull request discovery`,
|
||||
});
|
||||
}
|
||||
if (
|
||||
thread.projectId !== command.projectId ||
|
||||
thread.branch !== command.expected.branch ||
|
||||
thread.worktreePath !== command.expected.worktreePath ||
|
||||
!threadPullRequestLinksEqual(
|
||||
thread.linkedPullRequest ?? null,
|
||||
command.expected.linkedPullRequest,
|
||||
) ||
|
||||
!threadPullRequestLinksEqual(
|
||||
thread.branchPullRequest ?? null,
|
||||
command.expected.branchPullRequest,
|
||||
)
|
||||
) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} changed before pull request discovery`,
|
||||
});
|
||||
}
|
||||
const project = yield* requireProject({ readModel, command, projectId: command.projectId });
|
||||
if (project.deletedAt !== null || project.workspaceRoot !== command.expected.workspaceRoot) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `project ${command.projectId} changed before pull request discovery`,
|
||||
});
|
||||
}
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.meta-updated",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
branchPullRequest: command.branchPullRequest,
|
||||
...(command.linkedPullRequest !== undefined
|
||||
? { linkedPullRequest: command.linkedPullRequest }
|
||||
: {}),
|
||||
updatedAt: thread.updatedAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.title.regeneration.complete": {
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
|
||||
@@ -86,6 +86,7 @@ describe("orchestration projector", () => {
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
branchPullRequest: null,
|
||||
latestTurn: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -105,6 +106,67 @@ describe("orchestration projector", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
effectIt.effect("sets and clears branch pull requests without changing manual links", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const eventFields = {
|
||||
aggregateKind: "thread" as const,
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: now,
|
||||
commandId: null,
|
||||
};
|
||||
let model = yield* projectEvent(
|
||||
createEmptyReadModel(now),
|
||||
makeEvent({
|
||||
...eventFields,
|
||||
sequence: 1,
|
||||
type: "thread.created",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "Pull request thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5-codex" },
|
||||
runtimeMode: "full-access",
|
||||
branch: "feature",
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const linkedPullRequest = {
|
||||
projectId: "project-1",
|
||||
repository: "pingdotgg/t3code",
|
||||
number: 42,
|
||||
url: "https://github.com/pingdotgg/t3code/pull/42",
|
||||
};
|
||||
const branchPullRequest = {
|
||||
...linkedPullRequest,
|
||||
number: 43,
|
||||
url: "https://github.com/pingdotgg/t3code/pull/43",
|
||||
};
|
||||
const updates = [
|
||||
{ payload: { linkedPullRequest, branchPullRequest }, expected: branchPullRequest },
|
||||
{ payload: { title: "Renamed thread" }, expected: branchPullRequest },
|
||||
{ payload: { branchPullRequest: null }, expected: null },
|
||||
];
|
||||
|
||||
for (const [index, update] of updates.entries()) {
|
||||
model = yield* projectEvent(
|
||||
model,
|
||||
makeEvent({
|
||||
...eventFields,
|
||||
sequence: index + 2,
|
||||
type: "thread.meta-updated",
|
||||
payload: { threadId: "thread-1", updatedAt: now, ...update.payload },
|
||||
}),
|
||||
);
|
||||
expect(model.threads[0]?.branchPullRequest).toEqual(update.expected);
|
||||
expect(model.threads[0]?.linkedPullRequest).toEqual(linkedPullRequest);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it("fails when event payload cannot be decoded by runtime schema", async () => {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const model = createEmptyReadModel(now);
|
||||
|
||||
@@ -336,6 +336,7 @@ export function projectEvent(
|
||||
interactionMode: payload.interactionMode,
|
||||
branch: payload.branch,
|
||||
worktreePath: payload.worktreePath,
|
||||
branchPullRequest: null,
|
||||
latestTurn: null,
|
||||
createdAt: payload.createdAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
@@ -510,6 +511,9 @@ export function projectEvent(
|
||||
...(payload.linkedPullRequest !== undefined
|
||||
? { linkedPullRequest: payload.linkedPullRequest }
|
||||
: {}),
|
||||
...(payload.branchPullRequest !== undefined
|
||||
? { branchPullRequest: payload.branchPullRequest }
|
||||
: {}),
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
|
||||
@@ -462,7 +462,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("round-trips a linked pull request through the thread row", () =>
|
||||
it.effect("round-trips manual and branch pull requests through the thread row", () =>
|
||||
Effect.gen(function* () {
|
||||
const threads = yield* ProjectionThreadRepository;
|
||||
const linkedPullRequest = {
|
||||
@@ -471,6 +471,11 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
number: 42,
|
||||
url: "https://github.com/pingdotgg/t3code/pull/42",
|
||||
};
|
||||
const branchPullRequest = {
|
||||
...linkedPullRequest,
|
||||
number: 43,
|
||||
url: "https://github.com/pingdotgg/t3code/pull/43",
|
||||
};
|
||||
|
||||
yield* threads.upsert({
|
||||
threadId: ThreadId.make("thread-linked-pr"),
|
||||
@@ -485,6 +490,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
linkedPullRequest,
|
||||
branchPullRequest,
|
||||
latestTurnId: null,
|
||||
createdAt: "2026-03-24T00:00:00.000Z",
|
||||
updatedAt: "2026-03-24T00:00:00.000Z",
|
||||
@@ -504,6 +510,10 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
|
||||
const persisted = yield* threads.getById({ threadId: ThreadId.make("thread-linked-pr") });
|
||||
assert.deepStrictEqual(Option.getOrNull(persisted)?.linkedPullRequest, linkedPullRequest);
|
||||
assert.deepStrictEqual(Option.getOrNull(persisted)?.branchPullRequest, branchPullRequest);
|
||||
|
||||
const listed = yield* threads.listByProjectId({ projectId: linkedPullRequest.projectId });
|
||||
assert.deepStrictEqual(listed[0]?.branchPullRequest, branchPullRequest);
|
||||
|
||||
const row = Option.getOrNull(persisted);
|
||||
if (row === null) return yield* Effect.die("Expected linked thread row to exist.");
|
||||
@@ -511,6 +521,12 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
|
||||
const cleared = yield* threads.getById({ threadId: ThreadId.make("thread-linked-pr") });
|
||||
assert.strictEqual(Option.getOrNull(cleared)?.linkedPullRequest, null);
|
||||
assert.deepStrictEqual(Option.getOrNull(cleared)?.branchPullRequest, branchPullRequest);
|
||||
|
||||
yield* threads.upsert({ ...row, branchPullRequest: null });
|
||||
const branchCleared = yield* threads.getById({ threadId: row.threadId });
|
||||
assert.strictEqual(Option.getOrNull(branchCleared)?.branchPullRequest, null);
|
||||
assert.deepStrictEqual(Option.getOrNull(branchCleared)?.linkedPullRequest, linkedPullRequest);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -20,6 +20,7 @@ const ProjectionThreadDbRow = ProjectionThread.mapFields(
|
||||
Struct.assign({
|
||||
modelSelection: Schema.fromJsonString(ModelSelection),
|
||||
linkedPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),
|
||||
branchPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),
|
||||
}),
|
||||
);
|
||||
type ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type;
|
||||
@@ -41,6 +42,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
branch,
|
||||
worktree_path,
|
||||
linked_pull_request_json,
|
||||
branch_pull_request_json,
|
||||
latest_turn_id,
|
||||
created_at,
|
||||
updated_at,
|
||||
@@ -70,6 +72,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.branch},
|
||||
${row.worktreePath},
|
||||
${row.linkedPullRequest === undefined || row.linkedPullRequest === null ? null : JSON.stringify(row.linkedPullRequest)},
|
||||
${row.branchPullRequest === undefined || row.branchPullRequest === null ? null : JSON.stringify(row.branchPullRequest)},
|
||||
${row.latestTurnId},
|
||||
${row.createdAt},
|
||||
${row.updatedAt},
|
||||
@@ -99,6 +102,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
branch = excluded.branch,
|
||||
worktree_path = excluded.worktree_path,
|
||||
linked_pull_request_json = excluded.linked_pull_request_json,
|
||||
branch_pull_request_json = excluded.branch_pull_request_json,
|
||||
latest_turn_id = excluded.latest_turn_id,
|
||||
created_at = excluded.created_at,
|
||||
updated_at = excluded.updated_at,
|
||||
@@ -135,6 +139,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
branch,
|
||||
worktree_path AS "worktreePath",
|
||||
linked_pull_request_json AS "linkedPullRequest",
|
||||
branch_pull_request_json AS "branchPullRequest",
|
||||
latest_turn_id AS "latestTurnId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -173,6 +178,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
branch,
|
||||
worktree_path AS "worktreePath",
|
||||
linked_pull_request_json AS "linkedPullRequest",
|
||||
branch_pull_request_json AS "branchPullRequest",
|
||||
latest_turn_id AS "latestTurnId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
|
||||
@@ -59,6 +59,7 @@ import Migration0044 from "./Migrations/044_ClearAutomaticProjectModelDefaults.t
|
||||
import Migration0045 from "./Migrations/045_ProjectionProjectsAutoPull.ts";
|
||||
import Migration0046 from "./Migrations/046_RepairAutomaticSettlementTimestamps.ts";
|
||||
import Migration0047 from "./Migrations/047_ProjectionProjectIcon.ts";
|
||||
import Migration0048 from "./Migrations/048_ProjectionThreadBranchPullRequest.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -118,6 +119,7 @@ export const migrationEntries = [
|
||||
[45, "ProjectionProjectsAutoPull", Migration0045],
|
||||
[46, "RepairAutomaticSettlementTimestamps", Migration0046],
|
||||
[47, "ProjectionProjectIcon", Migration0047],
|
||||
[48, "ProjectionThreadBranchPullRequest", Migration0048],
|
||||
] as const;
|
||||
|
||||
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const columns = yield* sql<{ readonly name: string }>`
|
||||
PRAGMA table_info(projection_threads)
|
||||
`;
|
||||
|
||||
if (!columns.some((column) => column.name === "branch_pull_request_json")) {
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN branch_pull_request_json TEXT
|
||||
`;
|
||||
}
|
||||
});
|
||||
@@ -35,6 +35,7 @@ export const ProjectionThread = Schema.Struct({
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
|
||||
branchPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
|
||||
latestTurnId: Schema.NullOr(TurnId),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
|
||||
@@ -38,15 +38,16 @@ const makeRepositoryIdentityResolverTestLayer = (options: {
|
||||
).pipe(Layer.provide(ProcessRunner.layer));
|
||||
|
||||
it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
|
||||
it.effect("reuses the cached Git root for repeated workspace lookups", () => {
|
||||
it.effect("refreshes the Git root only when requested", () => {
|
||||
const calls: Array<ReadonlyArray<string>> = [];
|
||||
let rootPath = "/repo";
|
||||
const processRunner = Layer.succeed(ProcessRunner.ProcessRunner, {
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
calls.push(input.args);
|
||||
return {
|
||||
stdout: input.args.includes("rev-parse")
|
||||
? "/repo\n"
|
||||
? `${rootPath}\n`
|
||||
: "origin\[email protected]:T3Tools/t3code.git (fetch)\n",
|
||||
stderr: "",
|
||||
code: ChildProcessSpawner.ExitCode(0),
|
||||
@@ -66,6 +67,7 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
|
||||
return Effect.gen(function* () {
|
||||
const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
|
||||
const first = yield* resolver.resolve("/repo/packages/web");
|
||||
rootPath = "/repo/packages/web";
|
||||
const second = yield* resolver.resolve("/repo/packages/web");
|
||||
|
||||
expect(first?.canonicalKey).toBe("github.com/t3tools/t3code");
|
||||
@@ -74,6 +76,14 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
|
||||
["-C", "/repo/packages/web", "rev-parse", "--show-toplevel"],
|
||||
["-C", "/repo", "remote", "-v"],
|
||||
]);
|
||||
|
||||
const refreshed = yield* resolver.resolve("/repo/packages/web", { refresh: true });
|
||||
expect(refreshed?.rootPath).toBe("/repo/packages/web");
|
||||
expect(yield* resolver.resolve("/repo/packages/web")).toEqual(refreshed);
|
||||
expect(calls.slice(2)).toEqual([
|
||||
["-C", "/repo/packages/web", "rev-parse", "--show-toplevel"],
|
||||
["-C", "/repo/packages/web", "remote", "-v"],
|
||||
]);
|
||||
}).pipe(Effect.provide(resolverLayer));
|
||||
});
|
||||
|
||||
@@ -197,25 +207,42 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
|
||||
}).pipe(Effect.provide(RepositoryIdentityResolver.layer)),
|
||||
);
|
||||
|
||||
it.effect("prefers upstream over origin when both remotes are configured", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const cwd = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-repository-identity-upstream-test-",
|
||||
});
|
||||
it.effect.each(["add", "replace"] as const)(
|
||||
"refreshes the primary upstream after %s before cache expiry",
|
||||
(change) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const cwd = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-repository-identity-upstream-test-",
|
||||
});
|
||||
|
||||
yield* git(cwd, ["init"]);
|
||||
yield* git(cwd, ["remote", "add", "origin", "[email protected]:julius/t3code.git"]);
|
||||
yield* git(cwd, ["remote", "add", "upstream", "[email protected]:T3Tools/t3code.git"]);
|
||||
yield* git(cwd, ["init"]);
|
||||
yield* git(cwd, ["remote", "add", "origin", "[email protected]:julius/t3code.git"]);
|
||||
if (change === "replace") {
|
||||
yield* git(cwd, ["remote", "add", "upstream", "[email protected]:T3Tools/previous.git"]);
|
||||
}
|
||||
|
||||
const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
|
||||
const identity = yield* resolver.resolve(cwd);
|
||||
const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
|
||||
const initialIdentity = yield* resolver.resolve(cwd);
|
||||
expect(initialIdentity?.canonicalKey).toBe(
|
||||
change === "add" ? "github.com/julius/t3code" : "github.com/t3tools/previous",
|
||||
);
|
||||
|
||||
expect(identity).not.toBeNull();
|
||||
expect(identity?.locator.remoteName).toBe("upstream");
|
||||
expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code");
|
||||
expect(identity?.displayName).toBe("t3tools/t3code");
|
||||
}).pipe(Effect.provide(RepositoryIdentityResolver.layer)),
|
||||
yield* git(cwd, [
|
||||
"remote",
|
||||
change === "add" ? "add" : "set-url",
|
||||
"upstream",
|
||||
"[email protected]:T3Tools/t3code.git",
|
||||
]);
|
||||
expect(yield* resolver.resolve(cwd)).toEqual(initialIdentity);
|
||||
const identity = yield* resolver.resolve(cwd, { refresh: true });
|
||||
|
||||
expect(identity).not.toBeNull();
|
||||
expect(identity?.locator.remoteName).toBe("upstream");
|
||||
expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code");
|
||||
expect(identity?.displayName).toBe("t3tools/t3code");
|
||||
expect(yield* resolver.resolve(cwd)).toEqual(identity);
|
||||
}).pipe(Effect.provide(RepositoryIdentityResolver.layer)),
|
||||
);
|
||||
|
||||
it.effect("uses the last remote path segment as the repository name for nested groups", () =>
|
||||
|
||||
@@ -25,7 +25,10 @@ export interface RepositoryIdentityResolverOptions {
|
||||
export class RepositoryIdentityResolver extends Context.Service<
|
||||
RepositoryIdentityResolver,
|
||||
{
|
||||
readonly resolve: (cwd: string) => Effect.Effect<RepositoryIdentity | null>;
|
||||
readonly resolve: (
|
||||
cwd: string,
|
||||
options?: { readonly refresh?: boolean },
|
||||
) => Effect.Effect<RepositoryIdentity | null>;
|
||||
}
|
||||
>()("t3/project/RepositoryIdentityResolver") {}
|
||||
|
||||
@@ -170,9 +173,11 @@ export const make = Effect.fn("RepositoryIdentityResolver.make")(function* (
|
||||
|
||||
const resolve: RepositoryIdentityResolver["Service"]["resolve"] = Effect.fn(
|
||||
"RepositoryIdentityResolver.resolve",
|
||||
)(function* (cwd) {
|
||||
)(function* (cwd, options) {
|
||||
if (options?.refresh) yield* Cache.invalidate(repositoryRootCache, cwd);
|
||||
const cacheKey = yield* Cache.get(repositoryRootCache, cwd);
|
||||
if (cacheKey === null) return null;
|
||||
if (options?.refresh) yield* Cache.invalidate(repositoryIdentityCache, cacheKey);
|
||||
return yield* Cache.get(repositoryIdentityCache, cacheKey);
|
||||
});
|
||||
|
||||
|
||||
@@ -71,6 +71,7 @@ import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderComma
|
||||
import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor.ts";
|
||||
import { ThreadDeletionReactorLive } from "./orchestration/Layers/ThreadDeletionReactor.ts";
|
||||
import * as ThreadSettlementReactor from "./orchestration/ThreadSettlementReactor.ts";
|
||||
import * as ThreadPullRequestReactor from "./orchestration/ThreadPullRequestReactor.ts";
|
||||
import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
|
||||
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
|
||||
import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts";
|
||||
@@ -279,6 +280,7 @@ const ReactorLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(CheckpointReactorLive),
|
||||
Layer.provideMerge(ThreadDeletionReactorLive),
|
||||
Layer.provideMerge(ThreadSettlementReactor.layer),
|
||||
Layer.provideMerge(ThreadPullRequestReactor.layer),
|
||||
Layer.provideMerge(AgentAwarenessRelay.layer.pipe(Layer.provide(ServerSecretStore.layer))),
|
||||
Layer.provideMerge(RuntimeReceiptBusLive),
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user