Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4517d7631b | ||
|
|
375ea9504a | ||
|
|
399b093bf6 |
No files matched your search
@@ -342,6 +342,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
refreshChangeRequestStatus: () => Effect.succeed(null),
|
||||
refreshStatus: () => Effect.die("refreshStatus should not be called in this test"),
|
||||
streamStatus: () => Stream.empty,
|
||||
}),
|
||||
|
||||
@@ -895,11 +895,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
statusRefName: null,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "pending" },
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -925,11 +927,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
statusRefName: null,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "pending" },
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1311,7 +1315,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status is resilient to gh lookup failures and returns pr null", () =>
|
||||
it.effect("status reports provider availability failures without leaking diagnostics", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -1333,6 +1337,39 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.refName).toBe("feature/status-no-gh");
|
||||
expect(status.pr).toBeNull();
|
||||
expect(status.changeRequestLookup).toEqual({
|
||||
_tag: "failed",
|
||||
provider: "github",
|
||||
reason: "provider_unavailable",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status reports source control authentication failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-auth"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-auth"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new GitHubCli.GitHubCliAuthenticationError({
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("private authentication output"),
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.changeRequestLookup).toEqual({
|
||||
_tag: "failed",
|
||||
provider: "github",
|
||||
reason: "authentication_required",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
GitStackedAction,
|
||||
VcsStatusInput,
|
||||
type VcsStatusLocalResult,
|
||||
type VcsStatusChangeRequestLookup,
|
||||
type VcsStatusRemoteResult,
|
||||
VcsStatusResult,
|
||||
ModelSelection,
|
||||
@@ -49,7 +50,7 @@ import * as ServerSettings from "../serverSettings.ts";
|
||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
|
||||
import type { ChangeRequest } from "@t3tools/contracts";
|
||||
import type { ChangeRequest, SourceControlProviderError } from "@t3tools/contracts";
|
||||
|
||||
export interface GitActionProgressReporter {
|
||||
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
|
||||
@@ -103,6 +104,32 @@ function isNotGitRepositoryError(error: GitCommandError): boolean {
|
||||
return error.message.toLowerCase().includes("not a git repository");
|
||||
}
|
||||
|
||||
function lookupFailureReason(error: SourceControlProviderError): VcsStatusChangeRequestLookup {
|
||||
const tags = new Set<string>();
|
||||
let current: unknown = error;
|
||||
for (let depth = 0; depth < 6 && current !== null && typeof current === "object"; depth += 1) {
|
||||
if ("_tag" in current && typeof current._tag === "string") {
|
||||
tags.add(current._tag);
|
||||
}
|
||||
if ("status" in current && (current.status === 401 || current.status === 403)) {
|
||||
return {
|
||||
_tag: "failed",
|
||||
provider: error.provider,
|
||||
reason: "authentication_required",
|
||||
};
|
||||
}
|
||||
current = "cause" in current ? current.cause : null;
|
||||
}
|
||||
|
||||
const hasTagSuffix = (suffix: string) => [...tags].some((tag) => tag.endsWith(suffix));
|
||||
const reason = hasTagSuffix("AuthenticationError")
|
||||
? "authentication_required"
|
||||
: hasTagSuffix("UnavailableError") || tags.has("VcsProcessSpawnError")
|
||||
? "provider_unavailable"
|
||||
: "lookup_failed";
|
||||
return { _tag: "failed", provider: error.provider, reason };
|
||||
}
|
||||
|
||||
interface OpenPrInfo {
|
||||
number: number;
|
||||
title: string;
|
||||
@@ -779,29 +806,36 @@ export const make = Effect.gen(function* () {
|
||||
return null;
|
||||
}
|
||||
|
||||
const pr =
|
||||
details.branch !== null
|
||||
? yield* findLatestPr(cwd, {
|
||||
branch: details.branch,
|
||||
upstreamRef: details.upstreamRef,
|
||||
}).pipe(
|
||||
Effect.map((latest) => {
|
||||
if (!latest) return null;
|
||||
// On the default branch, only surface open PRs.
|
||||
// Merged/closed matches are usually reverse-merge history, not the thread's PR context.
|
||||
if (details.isDefaultBranch && latest.state !== "open") return null;
|
||||
return toStatusPr(latest);
|
||||
}),
|
||||
Effect.orElseSucceed(() => null),
|
||||
)
|
||||
: null;
|
||||
let pr: VcsStatusRemoteResult["pr"] = null;
|
||||
let changeRequestLookup: VcsStatusChangeRequestLookup = { _tag: "succeeded" };
|
||||
if (details.branch !== null) {
|
||||
const lookup = yield* findLatestPr(cwd, {
|
||||
branch: details.branch,
|
||||
upstreamRef: details.upstreamRef,
|
||||
}).pipe(
|
||||
Effect.match({
|
||||
onFailure: (error) => ({ error }),
|
||||
onSuccess: (latest) => ({ latest }),
|
||||
}),
|
||||
);
|
||||
if ("error" in lookup) {
|
||||
changeRequestLookup = lookupFailureReason(lookup.error);
|
||||
} else {
|
||||
const latest = lookup.latest;
|
||||
if (latest && (!details.isDefaultBranch || latest.state === "open")) {
|
||||
pr = toStatusPr(latest);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
statusRefName: details.branch,
|
||||
hasUpstream: details.hasUpstream,
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
aheadOfDefaultCount: details.aheadOfDefaultCount,
|
||||
pr,
|
||||
changeRequestLookup,
|
||||
} satisfies VcsStatusRemoteResult;
|
||||
});
|
||||
const remoteStatusResultCache = yield* Cache.makeWith((cwd: string) => readRemoteStatus(cwd), {
|
||||
|
||||
@@ -66,11 +66,13 @@ describe("GitWorkflowService", () => {
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
statusRefName: null,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
|
||||
@@ -112,11 +112,13 @@ function nonRepositoryLocalStatus(): VcsStatusLocalResult {
|
||||
function nonRepositoryStatus(): VcsStatusResult {
|
||||
return {
|
||||
...nonRepositoryLocalStatus(),
|
||||
statusRefName: null,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
/* oxlint-disable t3code/no-manual-effect-runtime-in-tests */
|
||||
// This integration harness owns a ManagedRuntime and exercises its Promise boundary directly.
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
@@ -14,6 +16,7 @@ import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
EventId,
|
||||
GitManagerError,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
@@ -197,6 +200,16 @@ async function waitForEvent(
|
||||
return poll();
|
||||
}
|
||||
|
||||
async function waitForCondition(predicate: () => boolean, timeoutMs = 5_000): Promise<void> {
|
||||
const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
|
||||
while (!predicate()) {
|
||||
if ((await Effect.runPromise(Clock.currentTimeMillis)) >= deadline) {
|
||||
throw new Error("Timed out waiting for condition.");
|
||||
}
|
||||
await Effect.runPromise(Effect.sleep("10 millis"));
|
||||
}
|
||||
}
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
return NodeChildProcess.execFileSync("git", args, {
|
||||
cwd,
|
||||
@@ -280,6 +293,10 @@ describe("CheckpointReactor", () => {
|
||||
readonly providerSessionCwd?: string;
|
||||
readonly providerName?: ProviderDriverKind;
|
||||
readonly gitStatusRefreshCalls?: Array<string>;
|
||||
readonly changeRequestStatusRefreshCalls?: Array<string>;
|
||||
readonly failGitStatusRefresh?: boolean;
|
||||
readonly failChangeRequestStatusRefresh?: boolean;
|
||||
readonly gitStatusRefreshWait?: Promise<void>;
|
||||
}) {
|
||||
const cwd = createGitRepository();
|
||||
tempDirs.push(cwd);
|
||||
@@ -311,14 +328,45 @@ describe("CheckpointReactor", () => {
|
||||
Effect.sync(() => {
|
||||
options?.gitStatusRefreshCalls?.push(cwd);
|
||||
}).pipe(
|
||||
Effect.as({
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
Effect.andThen(
|
||||
options?.gitStatusRefreshWait
|
||||
? Effect.promise(() => options.gitStatusRefreshWait!)
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.andThen(
|
||||
options?.failGitStatusRefresh
|
||||
? Effect.fail(
|
||||
new GitManagerError({
|
||||
operation: "refreshLocalStatus",
|
||||
cwd,
|
||||
detail: "test failure",
|
||||
}),
|
||||
)
|
||||
: Effect.succeed({
|
||||
isRepo: true as const,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
),
|
||||
),
|
||||
refreshChangeRequestStatus: (cwd: string) =>
|
||||
Effect.sync(() => {
|
||||
options?.changeRequestStatusRefreshCalls?.push(cwd);
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
options?.failChangeRequestStatusRefresh
|
||||
? Effect.fail(
|
||||
new GitManagerError({
|
||||
operation: "refreshChangeRequestStatus",
|
||||
cwd,
|
||||
detail: "test failure",
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(null),
|
||||
),
|
||||
),
|
||||
refreshStatus: () => Effect.die("refreshStatus should not be called in this test"),
|
||||
streamStatus: () => Stream.empty,
|
||||
@@ -496,11 +544,13 @@ describe("CheckpointReactor", () => {
|
||||
).toBe("v2\n");
|
||||
});
|
||||
|
||||
it("refreshes local git status state on turn completion using the session cwd", async () => {
|
||||
it("refreshes local and change request status on turn completion using the session cwd", async () => {
|
||||
const gitStatusRefreshCalls: string[] = [];
|
||||
const changeRequestStatusRefreshCalls: string[] = [];
|
||||
const harness = await createHarness({
|
||||
seedFilesystemCheckpoints: false,
|
||||
gitStatusRefreshCalls,
|
||||
changeRequestStatusRefreshCalls,
|
||||
});
|
||||
|
||||
harness.provider.emit({
|
||||
@@ -516,10 +566,105 @@ describe("CheckpointReactor", () => {
|
||||
await harness.drain();
|
||||
|
||||
expect(gitStatusRefreshCalls).toEqual([harness.cwd]);
|
||||
expect(changeRequestStatusRefreshCalls).toEqual([harness.cwd]);
|
||||
});
|
||||
|
||||
it("falls back to the thread worktree when no provider session is available", async () => {
|
||||
const gitStatusRefreshCalls: string[] = [];
|
||||
const changeRequestStatusRefreshCalls: string[] = [];
|
||||
const harness = await createHarness({
|
||||
hasSession: false,
|
||||
seedFilesystemCheckpoints: false,
|
||||
gitStatusRefreshCalls,
|
||||
changeRequestStatusRefreshCalls,
|
||||
});
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make("evt-turn-completed-refresh-fallback"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-refresh-fallback"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
await harness.drain();
|
||||
|
||||
expect(gitStatusRefreshCalls).toEqual([harness.cwd]);
|
||||
expect(changeRequestStatusRefreshCalls).toEqual([harness.cwd]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ name: "local", failGitStatusRefresh: true, failChangeRequestStatusRefresh: false },
|
||||
{ name: "change request", failGitStatusRefresh: false, failChangeRequestStatusRefresh: true },
|
||||
])("runs both completion refreshes when the $name refresh fails", async (failure) => {
|
||||
const gitStatusRefreshCalls: string[] = [];
|
||||
const changeRequestStatusRefreshCalls: string[] = [];
|
||||
const harness = await createHarness({
|
||||
seedFilesystemCheckpoints: false,
|
||||
gitStatusRefreshCalls,
|
||||
changeRequestStatusRefreshCalls,
|
||||
failGitStatusRefresh: failure.failGitStatusRefresh,
|
||||
failChangeRequestStatusRefresh: failure.failChangeRequestStatusRefresh,
|
||||
});
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make(`evt-turn-completed-${failure.name}-refresh-failure`),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId(`turn-${failure.name}-refresh-failure`),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
await harness.drain();
|
||||
|
||||
expect(gitStatusRefreshCalls).toEqual([harness.cwd]);
|
||||
expect(changeRequestStatusRefreshCalls).toEqual([harness.cwd]);
|
||||
});
|
||||
|
||||
it("starts change request refresh without waiting for local refresh", async () => {
|
||||
const gitStatusRefreshCalls: string[] = [];
|
||||
const changeRequestStatusRefreshCalls: string[] = [];
|
||||
let releaseLocalRefresh: (() => void) | undefined;
|
||||
const gitStatusRefreshWait = new Promise<void>((resolve) => {
|
||||
releaseLocalRefresh = resolve;
|
||||
});
|
||||
const harness = await createHarness({
|
||||
seedFilesystemCheckpoints: false,
|
||||
gitStatusRefreshCalls,
|
||||
changeRequestStatusRefreshCalls,
|
||||
gitStatusRefreshWait,
|
||||
});
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make("evt-turn-completed-independent-refreshes"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-independent-refreshes"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
const draining = harness.drain();
|
||||
await waitForCondition(
|
||||
() => gitStatusRefreshCalls.length === 1 && changeRequestStatusRefreshCalls.length === 1,
|
||||
);
|
||||
|
||||
expect(gitStatusRefreshCalls).toEqual([harness.cwd]);
|
||||
expect(changeRequestStatusRefreshCalls).toEqual([harness.cwd]);
|
||||
releaseLocalRefresh?.();
|
||||
await draining;
|
||||
});
|
||||
|
||||
it("ignores auxiliary thread turn completion while primary turn is active", async () => {
|
||||
const harness = await createHarness({ seedFilesystemCheckpoints: false });
|
||||
const gitStatusRefreshCalls: string[] = [];
|
||||
const changeRequestStatusRefreshCalls: string[] = [];
|
||||
const harness = await createHarness({
|
||||
seedFilesystemCheckpoints: false,
|
||||
gitStatusRefreshCalls,
|
||||
changeRequestStatusRefreshCalls,
|
||||
});
|
||||
const createdAt = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
await Effect.runPromise(
|
||||
@@ -571,6 +716,20 @@ describe("CheckpointReactor", () => {
|
||||
const midReadModel = await harness.readModel();
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(midThread?.checkpoints).toHaveLength(0);
|
||||
expect(gitStatusRefreshCalls).toEqual([]);
|
||||
expect(changeRequestStatusRefreshCalls).toEqual([]);
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make("evt-turn-completed-missing-id"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
await harness.drain();
|
||||
expect(gitStatusRefreshCalls).toEqual([]);
|
||||
expect(changeRequestStatusRefreshCalls).toEqual([]);
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
|
||||
@@ -526,25 +526,73 @@ const make = Effect.gen(function* () {
|
||||
},
|
||||
);
|
||||
|
||||
const refreshLocalGitStatusFromTurnCompletion = Effect.fn(
|
||||
"refreshLocalGitStatusFromTurnCompletion",
|
||||
)(function* (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>) {
|
||||
const sessionRuntime = yield* resolveSessionRuntimeForThread(event.threadId);
|
||||
if (Option.isNone(sessionRuntime)) {
|
||||
return;
|
||||
}
|
||||
const refreshGitStatusFromTurnCompletion = Effect.fn("refreshGitStatusFromTurnCompletion")(
|
||||
function* (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>) {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
const thread = yield* resolveThreadDetail(event.threadId);
|
||||
if (
|
||||
thread?.session?.activeTurnId &&
|
||||
(!turnId || !sameId(thread.session.activeTurnId, turnId))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* vcsStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to refresh local git status after turn completion", {
|
||||
threadId: event.threadId,
|
||||
turnId: event.turnId ?? null,
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
detail: error.message,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
const sessionRuntime = yield* resolveSessionRuntimeForThread(event.threadId);
|
||||
let cwd = Option.getOrUndefined(sessionRuntime)?.cwd;
|
||||
if (!cwd) {
|
||||
if (thread) {
|
||||
cwd = yield* resolveCheckpointCwd({
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
projects: yield* resolveThreadProjects(thread.projectId),
|
||||
preferSessionRuntime: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (!cwd) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [local, remote] = yield* Effect.all(
|
||||
[
|
||||
vcsStatusBroadcaster.refreshLocalStatus(cwd).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to refresh local git status after turn completion", {
|
||||
threadId: event.threadId,
|
||||
turnId: event.turnId ?? null,
|
||||
cwd,
|
||||
detail: error.message,
|
||||
}).pipe(Effect.as(undefined)),
|
||||
),
|
||||
),
|
||||
vcsStatusBroadcaster.refreshChangeRequestStatus(cwd).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to refresh change request status after turn completion", {
|
||||
threadId: event.threadId,
|
||||
turnId: event.turnId ?? null,
|
||||
cwd,
|
||||
detail: error.message,
|
||||
}).pipe(Effect.as(undefined)),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
if (local && remote && remote.statusRefName !== local.refName) {
|
||||
yield* vcsStatusBroadcaster.refreshChangeRequestStatus(cwd).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to reconcile change request status after branch change", {
|
||||
threadId: event.threadId,
|
||||
turnId: event.turnId ?? null,
|
||||
cwd,
|
||||
detail: error.message,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const ensurePreTurnBaselineFromDomainTurnStart = Effect.fn(
|
||||
"ensurePreTurnBaselineFromDomainTurnStart",
|
||||
@@ -790,7 +838,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
if (event.type === "turn.completed") {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
yield* refreshLocalGitStatusFromTurnCompletion(event);
|
||||
yield* refreshGitStatusFromTurnCompletion(event);
|
||||
yield* captureCheckpointFromTurnCompletion(event).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.flatMap(nowIso, (createdAt) =>
|
||||
|
||||
@@ -262,10 +262,12 @@ describe("ProviderCommandReactor", () => {
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
statusRefName: "renamed-branch",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" as const },
|
||||
}),
|
||||
);
|
||||
const generateBranchName = vi.fn<TextGenerationShape["generateBranchName"]>((_) =>
|
||||
@@ -358,6 +360,8 @@ describe("ProviderCommandReactor", () => {
|
||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||
refreshLocalStatus: () =>
|
||||
Effect.die("refreshLocalStatus should not be called in this test"),
|
||||
refreshChangeRequestStatus: () =>
|
||||
Effect.die("refreshChangeRequestStatus should not be called in this test"),
|
||||
refreshStatus,
|
||||
streamStatus: () => Stream.die("streamStatus should not be called in this test"),
|
||||
}),
|
||||
|
||||
@@ -4823,10 +4823,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}),
|
||||
remoteStatus: () =>
|
||||
Effect.succeed({
|
||||
statusRefName: "main",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
}),
|
||||
status: () =>
|
||||
Effect.succeed({
|
||||
@@ -4836,10 +4838,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
refName: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
statusRefName: "main",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
}),
|
||||
runStackedAction: (input, options) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -4953,10 +4957,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
refName: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
statusRefName: "main",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
}),
|
||||
},
|
||||
reviewService: {
|
||||
@@ -5145,10 +5151,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.sync(() => {
|
||||
statusCalls += 1;
|
||||
return {
|
||||
statusRefName: "main",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" as const },
|
||||
};
|
||||
}),
|
||||
status: () =>
|
||||
@@ -5161,10 +5169,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
refName: "main",
|
||||
hasWorkingTreeChanges: true,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
statusRefName: "main",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" as const },
|
||||
};
|
||||
}),
|
||||
},
|
||||
@@ -5222,10 +5232,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.sync(() => {
|
||||
statusCalls += 1;
|
||||
return {
|
||||
statusRefName: "feature/demo",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" as const },
|
||||
};
|
||||
}),
|
||||
status: () =>
|
||||
@@ -5238,10 +5250,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
refName: "feature/demo",
|
||||
hasWorkingTreeChanges: true,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
statusRefName: "feature/demo",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" as const },
|
||||
};
|
||||
}),
|
||||
runStackedAction: () => Effect.fail(gitError),
|
||||
@@ -5293,10 +5307,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
remoteStatus: () =>
|
||||
Effect.sleep(Duration.seconds(2)).pipe(
|
||||
Effect.as({
|
||||
statusRefName: "main",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" as const },
|
||||
}),
|
||||
),
|
||||
},
|
||||
@@ -5339,10 +5355,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
remoteStatus: () =>
|
||||
Effect.sleep(Duration.seconds(2)).pipe(
|
||||
Effect.as({
|
||||
statusRefName: "feature/demo",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" as const },
|
||||
}),
|
||||
),
|
||||
runStackedAction: () =>
|
||||
@@ -5420,10 +5438,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
remoteStatus: () =>
|
||||
Effect.sleep(Duration.seconds(2)).pipe(
|
||||
Effect.as({
|
||||
statusRefName: "feature/demo",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" as const },
|
||||
}),
|
||||
),
|
||||
runStackedAction: () =>
|
||||
@@ -6744,10 +6764,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
statusRefName: "t3code/bootstrap-refName",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" as const },
|
||||
}),
|
||||
);
|
||||
const fetchRemote = vi.fn(
|
||||
|
||||
@@ -1521,11 +1521,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
refName: details.branch,
|
||||
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
|
||||
workingTree: details.workingTree,
|
||||
statusRefName: details.branch,
|
||||
hasUpstream: details.hasUpstream,
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
aheadOfDefaultCount: details.aheadOfDefaultCount,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "pending" as const },
|
||||
})),
|
||||
);
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
@@ -39,10 +40,12 @@ const baseLocalStatus: VcsStatusLocalResult = {
|
||||
};
|
||||
|
||||
const baseRemoteStatus: VcsStatusRemoteResult = {
|
||||
statusRefName: "feature/status-broadcast",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
};
|
||||
|
||||
const remoteStatusWithPr: VcsStatusRemoteResult = {
|
||||
@@ -145,6 +148,7 @@ describe("VcsStatusBroadcaster", () => {
|
||||
};
|
||||
state.currentRemoteStatus = {
|
||||
...baseRemoteStatus,
|
||||
statusRefName: "feature/updated-status",
|
||||
aheadCount: 2,
|
||||
};
|
||||
const refreshed = yield* broadcaster.refreshStatus("/repo");
|
||||
@@ -166,7 +170,44 @@ describe("VcsStatusBroadcaster", () => {
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it.effect("keeps the cached snapshot unchanged when a refresh branch fails", () => {
|
||||
it.effect(
|
||||
"retains a same-branch cached PR across lookup failure and clears it on recovery",
|
||||
() => {
|
||||
const state: Parameters<typeof makeTestLayer>[0] = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: remoteStatusWithPr,
|
||||
localStatusCalls: 0,
|
||||
remoteStatusCalls: 0,
|
||||
localInvalidationCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
state.currentRemoteStatus = {
|
||||
...baseRemoteStatus,
|
||||
changeRequestLookup: {
|
||||
_tag: "failed",
|
||||
provider: "github",
|
||||
reason: "lookup_failed",
|
||||
},
|
||||
};
|
||||
|
||||
const failed = yield* broadcaster.refreshChangeRequestStatus("/repo");
|
||||
assert.deepStrictEqual(failed, {
|
||||
...state.currentRemoteStatus,
|
||||
pr: remoteStatusWithPr.pr,
|
||||
});
|
||||
|
||||
state.currentRemoteStatus = baseRemoteStatus;
|
||||
const recovered = yield* broadcaster.refreshChangeRequestStatus("/repo");
|
||||
assert.deepStrictEqual(recovered, baseRemoteStatus);
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("keeps a successful local refresh when the remote refresh fails", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: baseRemoteStatus,
|
||||
@@ -228,7 +269,17 @@ describe("VcsStatusBroadcaster", () => {
|
||||
const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
|
||||
assert.isTrue(Exit.isFailure(refreshExit));
|
||||
assert.deepStrictEqual(cached, baseStatus);
|
||||
assert.deepStrictEqual(cached, {
|
||||
...baseStatus,
|
||||
...state.currentLocalStatus,
|
||||
statusRefName: null,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "pending" },
|
||||
});
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
|
||||
@@ -259,7 +310,13 @@ describe("VcsStatusBroadcaster", () => {
|
||||
assert.deepStrictEqual(refreshedLocal, state.currentLocalStatus);
|
||||
assert.deepStrictEqual(cached, {
|
||||
...state.currentLocalStatus,
|
||||
...baseRemoteStatus,
|
||||
statusRefName: null,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "pending" },
|
||||
});
|
||||
assert.equal(state.localStatusCalls, 2);
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
@@ -369,7 +426,7 @@ describe("VcsStatusBroadcaster", () => {
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it.effect("loads remote status once when periodic refreshes are disabled", () => {
|
||||
it.effect("keeps lightweight change request polling when Git fetches are disabled", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: remoteStatusWithPr,
|
||||
@@ -418,8 +475,15 @@ describe("VcsStatusBroadcaster", () => {
|
||||
assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false]);
|
||||
|
||||
yield* TestClock.adjust(Duration.minutes(2));
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
assert.equal(state.remoteStatusCalls, 5);
|
||||
assert.equal(state.remoteInvalidationCalls, 0);
|
||||
assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
]);
|
||||
|
||||
yield* Scope.close(scope, Exit.void);
|
||||
}).pipe(Effect.provide(Layer.merge(makeTestLayer(state), TestClock.layer())));
|
||||
@@ -576,17 +640,74 @@ describe("VcsStatusBroadcaster", () => {
|
||||
assert.equal(state.remoteInvalidationCalls, 0);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(59));
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
assert.equal(state.remoteStatusCalls, 2);
|
||||
assert.equal(state.remoteInvalidationCalls, 0);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(state.remoteStatusCalls, 2);
|
||||
assert.equal(state.remoteStatusCalls, 3);
|
||||
assert.equal(state.remoteInvalidationCalls, 1);
|
||||
|
||||
yield* Scope.close(scope, Exit.void);
|
||||
}).pipe(Effect.provide(Layer.merge(makeTestLayer(state), TestClock.layer())));
|
||||
});
|
||||
|
||||
it.effect("retries a failed upstream refresh after the failure backoff", () => {
|
||||
const refreshUpstreamValues: Array<boolean | undefined> = [];
|
||||
let failedUpstreamRefresh = false;
|
||||
const testLayer = VcsStatusBroadcaster.layer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
localStatus: () => Effect.succeed(baseLocalStatus),
|
||||
remoteStatus: (_input, options) => {
|
||||
refreshUpstreamValues.push(options?.refreshUpstream);
|
||||
if (options?.refreshUpstream && !failedUpstreamRefresh) {
|
||||
failedUpstreamRefresh = true;
|
||||
return Effect.fail(
|
||||
new GitManagerError({
|
||||
operation: "VcsStatusBroadcaster.test",
|
||||
cwd: "/repo",
|
||||
detail: "upstream refresh failure",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(baseRemoteStatus);
|
||||
},
|
||||
invalidateRemoteStatus: () => Effect.void,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
const scope = yield* Scope.make();
|
||||
const snapshotDeferred = yield* Deferred.make<void>();
|
||||
yield* Stream.runForEach(
|
||||
broadcaster.streamStatus(
|
||||
{ cwd: "/repo" },
|
||||
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.minutes(5)) },
|
||||
),
|
||||
(event) =>
|
||||
event._tag === "snapshot"
|
||||
? Deferred.succeed(snapshotDeferred, undefined).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
).pipe(Effect.forkIn(scope));
|
||||
yield* Deferred.await(snapshotDeferred);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* TestClock.adjust(Duration.minutes(5));
|
||||
assert.isTrue(failedUpstreamRefresh);
|
||||
assert.equal(refreshUpstreamValues.at(-1), true);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(30));
|
||||
assert.deepStrictEqual(refreshUpstreamValues.slice(-2), [true, true]);
|
||||
|
||||
yield* Scope.close(scope, Exit.void);
|
||||
}).pipe(Effect.provide(Layer.merge(testLayer, TestClock.layer())));
|
||||
});
|
||||
|
||||
it("backs off remote refresh failures exponentially and honors larger configured intervals", () => {
|
||||
assert.equal(
|
||||
Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(1, Duration.seconds(1))),
|
||||
@@ -631,6 +752,104 @@ describe("VcsStatusBroadcaster", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("coalesces concurrent lightweight refreshes for the same worktree", () => {
|
||||
let calls = 0;
|
||||
return Effect.gen(function* () {
|
||||
const started = yield* Deferred.make<void>();
|
||||
const release = yield* Deferred.make<void>();
|
||||
const testLayer = VcsStatusBroadcaster.layer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
remoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
calls += 1;
|
||||
return calls;
|
||||
}).pipe(
|
||||
Effect.flatMap((call) =>
|
||||
call === 1
|
||||
? Effect.succeed(baseRemoteStatus)
|
||||
: Deferred.succeed(started, undefined).pipe(
|
||||
Effect.ignore,
|
||||
Effect.andThen(Deferred.await(release)),
|
||||
Effect.as(baseRemoteStatus),
|
||||
),
|
||||
),
|
||||
),
|
||||
localStatus: () => Effect.succeed(baseLocalStatus),
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
const firstRefresh = yield* Effect.forkChild(
|
||||
broadcaster.refreshChangeRequestStatus("/repo"),
|
||||
);
|
||||
yield* Deferred.await(started);
|
||||
const secondRefresh = yield* Effect.forkChild(
|
||||
broadcaster.refreshChangeRequestStatus("/repo"),
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
yield* TestClock.adjust(Duration.millis(10));
|
||||
yield* Deferred.succeed(release, undefined);
|
||||
yield* Fiber.join(firstRefresh);
|
||||
yield* Fiber.join(secondRefresh);
|
||||
|
||||
assert.equal(calls, 2);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("does not let an old branch lookup satisfy a queued new branch lookup", () => {
|
||||
let calls = 0;
|
||||
let currentRefName = baseLocalStatus.refName;
|
||||
return Effect.gen(function* () {
|
||||
const started = yield* Deferred.make<void>();
|
||||
const release = yield* Deferred.make<void>();
|
||||
const testLayer = VcsStatusBroadcaster.layer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
localStatus: () => Effect.succeed({ ...baseLocalStatus, refName: currentRefName }),
|
||||
invalidateLocalStatus: () => Effect.void,
|
||||
remoteStatus: () => {
|
||||
calls += 1;
|
||||
const status = { ...baseRemoteStatus, statusRefName: currentRefName };
|
||||
return calls === 2
|
||||
? Deferred.succeed(started, undefined).pipe(
|
||||
Effect.ignore,
|
||||
Effect.andThen(Deferred.await(release)),
|
||||
Effect.as(status),
|
||||
)
|
||||
: Effect.succeed(status);
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
const oldBranchRefresh = yield* Effect.forkChild(
|
||||
broadcaster.refreshChangeRequestStatus("/repo"),
|
||||
);
|
||||
yield* Deferred.await(started);
|
||||
currentRefName = "feature/new-branch";
|
||||
yield* broadcaster.refreshLocalStatus("/repo");
|
||||
const newBranchRefresh = yield* Effect.forkChild(
|
||||
broadcaster.refreshChangeRequestStatus("/repo"),
|
||||
);
|
||||
yield* TestClock.adjust(Duration.millis(10));
|
||||
yield* Deferred.succeed(release, undefined);
|
||||
yield* Fiber.join(oldBranchRefresh);
|
||||
const refreshed = yield* Fiber.join(newBranchRefresh);
|
||||
|
||||
assert.equal(calls, 3);
|
||||
assert.equal(refreshed?.statusRefName, "feature/new-branch");
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("stops the remote poller after the last stream subscriber disconnects", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -8,7 +9,7 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
@@ -133,6 +134,11 @@ interface ActiveRemotePoller {
|
||||
readonly subscriberCount: number;
|
||||
}
|
||||
|
||||
interface RefreshLock {
|
||||
readonly semaphore: Semaphore.Semaphore;
|
||||
readonly users: number;
|
||||
}
|
||||
|
||||
interface StreamStatusOptions {
|
||||
readonly automaticRemoteRefreshInterval?: Effect.Effect<Duration.Duration, never>;
|
||||
}
|
||||
@@ -160,6 +166,9 @@ export class VcsStatusBroadcaster extends Context.Service<
|
||||
readonly refreshLocalStatus: (
|
||||
cwd: string,
|
||||
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
|
||||
readonly refreshChangeRequestStatus: (
|
||||
cwd: string,
|
||||
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
|
||||
readonly refreshStatus: (cwd: string) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
|
||||
readonly streamStatus: (
|
||||
input: VcsStatusInput,
|
||||
@@ -190,6 +199,51 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
|
||||
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
|
||||
const refreshLocksRef = yield* Ref.make(new Map<string, RefreshLock>());
|
||||
const refreshLocksGuard = yield* Semaphore.make(1);
|
||||
const backgroundRefreshSemaphore = yield* Semaphore.make(4);
|
||||
const lastRemoteRefreshRef = yield* Ref.make(
|
||||
new Map<string, { readonly completionId: number; readonly refreshUpstream: boolean }>(),
|
||||
);
|
||||
const refreshCompletionCounterRef = yield* Ref.make(0);
|
||||
|
||||
const withCwdRefreshLock = <A, E, R>(
|
||||
cwd: string,
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
): Effect.Effect<A, E, R> =>
|
||||
Effect.acquireUseRelease(
|
||||
refreshLocksGuard.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const locks = yield* Ref.get(refreshLocksRef);
|
||||
const existing = locks.get(cwd);
|
||||
if (existing) {
|
||||
yield* Ref.set(
|
||||
refreshLocksRef,
|
||||
new Map(locks).set(cwd, { ...existing, users: existing.users + 1 }),
|
||||
);
|
||||
return existing.semaphore;
|
||||
}
|
||||
const semaphore = yield* Semaphore.make(1);
|
||||
yield* Ref.set(refreshLocksRef, new Map(locks).set(cwd, { semaphore, users: 1 }));
|
||||
return semaphore;
|
||||
}),
|
||||
),
|
||||
(lock) => lock.withPermits(1)(effect),
|
||||
(lock) =>
|
||||
refreshLocksGuard.withPermits(1)(
|
||||
Ref.update(refreshLocksRef, (locks) => {
|
||||
const existing = locks.get(cwd);
|
||||
if (!existing || existing.semaphore !== lock) return locks;
|
||||
const next = new Map(locks);
|
||||
if (existing.users === 1) {
|
||||
next.delete(cwd);
|
||||
} else {
|
||||
next.set(cwd, { ...existing, users: existing.users - 1 });
|
||||
}
|
||||
return next;
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
|
||||
cwd: string,
|
||||
@@ -229,9 +283,18 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const updateCachedRemoteStatus = Effect.fn("VcsStatusBroadcaster.updateCachedRemoteStatus")(
|
||||
function* (cwd: string, remote: VcsStatusRemoteResult | null, options?: { publish?: boolean }) {
|
||||
const cached = yield* getCachedStatus(cwd);
|
||||
const previousRemote = cached?.remote?.value ?? null;
|
||||
const resolvedRemote =
|
||||
remote?.changeRequestLookup._tag === "failed" &&
|
||||
remote.pr === null &&
|
||||
previousRemote?.statusRefName === remote.statusRefName &&
|
||||
previousRemote.pr !== null
|
||||
? { ...remote, pr: previousRemote.pr }
|
||||
: remote;
|
||||
const nextRemote = {
|
||||
fingerprint: fingerprintStatusPart(remote),
|
||||
value: remote,
|
||||
fingerprint: fingerprintStatusPart(resolvedRemote),
|
||||
value: resolvedRemote,
|
||||
} satisfies CachedValue<VcsStatusRemoteResult | null>;
|
||||
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
|
||||
const previous = cache.get(cwd) ?? { local: null, remote: null };
|
||||
@@ -248,12 +311,12 @@ export const make = Effect.gen(function* () {
|
||||
cwd,
|
||||
event: {
|
||||
_tag: "remoteUpdated",
|
||||
remote,
|
||||
remote: resolvedRemote,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return remote;
|
||||
return resolvedRemote;
|
||||
},
|
||||
);
|
||||
|
||||
@@ -329,7 +392,9 @@ export const make = Effect.gen(function* () {
|
||||
const [local, remote] = yield* Effect.all(
|
||||
[
|
||||
cached?.local ? Effect.succeed(cached.local.value) : workflow.localStatus({ cwd }),
|
||||
cached?.remote ? Effect.succeed(cached.remote.value) : workflow.remoteStatus({ cwd }),
|
||||
cached?.remote
|
||||
? Effect.succeed(cached.remote.value)
|
||||
: refreshRemoteStatus(cwd, { refreshUpstream: false }),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
@@ -355,26 +420,57 @@ export const make = Effect.gen(function* () {
|
||||
cwd: string,
|
||||
options?: { readonly refreshUpstream?: boolean },
|
||||
) {
|
||||
if (options?.refreshUpstream !== false) {
|
||||
yield* workflow.invalidateRemoteStatus(cwd);
|
||||
}
|
||||
const remote = yield* workflow.remoteStatus({ cwd }, options);
|
||||
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
|
||||
const wantsUpstream = options?.refreshUpstream !== false;
|
||||
const observedCompletionId = (yield* Ref.get(lastRemoteRefreshRef)).get(cwd)?.completionId ?? 0;
|
||||
return yield* withCwdRefreshLock(
|
||||
cwd,
|
||||
backgroundRefreshSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const previousRefresh = (yield* Ref.get(lastRemoteRefreshRef)).get(cwd);
|
||||
const cached = yield* getCachedStatus(cwd);
|
||||
const cachedRemoteMatchesLocal =
|
||||
cached?.local?.value.refName === cached?.remote?.value?.statusRefName;
|
||||
if (
|
||||
previousRefresh &&
|
||||
previousRefresh.completionId > observedCompletionId &&
|
||||
(!wantsUpstream || previousRefresh.refreshUpstream) &&
|
||||
cachedRemoteMatchesLocal
|
||||
) {
|
||||
return cached?.remote?.value ?? null;
|
||||
}
|
||||
if (wantsUpstream) {
|
||||
yield* workflow.invalidateRemoteStatus(cwd);
|
||||
}
|
||||
const remote = yield* workflow.remoteStatus({ cwd }, options);
|
||||
const updated = yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
|
||||
const completionId = yield* Ref.updateAndGet(
|
||||
refreshCompletionCounterRef,
|
||||
(current) => current + 1,
|
||||
);
|
||||
yield* Ref.update(lastRemoteRefreshRef, (refreshes) =>
|
||||
new Map(refreshes).set(cwd, { completionId, refreshUpstream: wantsUpstream }),
|
||||
);
|
||||
return updated;
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const refreshChangeRequestStatus: VcsStatusBroadcaster["Service"]["refreshChangeRequestStatus"] =
|
||||
Effect.fn("VcsStatusBroadcaster.refreshChangeRequestStatus")(function* (rawCwd) {
|
||||
const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
|
||||
return yield* refreshRemoteStatus(cwd, { refreshUpstream: false });
|
||||
});
|
||||
|
||||
const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
|
||||
"VcsStatusBroadcaster.refreshStatus",
|
||||
)(function* (rawCwd) {
|
||||
const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
|
||||
yield* Effect.all([workflow.invalidateLocalStatus(cwd), workflow.invalidateRemoteStatus(cwd)], {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
});
|
||||
const [local, remote] = yield* Effect.all(
|
||||
[workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd })],
|
||||
[refreshLocalStatusCore(cwd), refreshRemoteStatus(cwd)],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
return yield* updateCachedStatus(cwd, local, remote, { publish: true });
|
||||
return mergeGitStatusParts(local, remote);
|
||||
});
|
||||
|
||||
const makeRemoteRefreshLoop = (
|
||||
@@ -385,23 +481,39 @@ export const make = Effect.gen(function* () {
|
||||
return Effect.gen(function* () {
|
||||
const consecutiveFailuresRef = yield* Ref.make(0);
|
||||
const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);
|
||||
const refreshRemoteStatusIfEnabled = Effect.gen(function* () {
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const lastLightweightRefreshRef = yield* Ref.make(now);
|
||||
const lastUpstreamRefreshRef = yield* Ref.make(now);
|
||||
const runOnce = Effect.fn("VcsStatusBroadcaster.remoteRefreshLoop.runOnce")(function* () {
|
||||
const configuredInterval = yield* automaticRemoteRefreshInterval;
|
||||
const activeInterval = Duration.isZero(configuredInterval)
|
||||
? DEFAULT_VCS_STATUS_REFRESH_INTERVAL
|
||||
: configuredInterval;
|
||||
const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);
|
||||
if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {
|
||||
return activeInterval;
|
||||
const currentTime = yield* Clock.currentTimeMillis;
|
||||
const nextLightweightAt =
|
||||
(yield* Ref.get(lastLightweightRefreshRef)) +
|
||||
Duration.toMillis(DEFAULT_VCS_STATUS_REFRESH_INTERVAL);
|
||||
const nextUpstreamAt = Duration.isZero(configuredInterval)
|
||||
? Number.POSITIVE_INFINITY
|
||||
: (yield* Ref.get(lastUpstreamRefreshRef)) + Duration.toMillis(configuredInterval);
|
||||
if (!needsInitialRefresh) {
|
||||
yield* Effect.sleep(
|
||||
Duration.millis(Math.max(0, Math.min(nextLightweightAt, nextUpstreamAt) - currentTime)),
|
||||
);
|
||||
}
|
||||
|
||||
const refreshTime = yield* Clock.currentTimeMillis;
|
||||
const refreshUpstream =
|
||||
!Duration.isZero(configuredInterval) &&
|
||||
(needsInitialRefresh || refreshTime >= nextUpstreamAt);
|
||||
|
||||
const exit = yield* refreshRemoteStatus(cwd, {
|
||||
refreshUpstream: !Duration.isZero(configuredInterval),
|
||||
refreshUpstream,
|
||||
}).pipe(Effect.exit);
|
||||
yield* Ref.set(lastLightweightRefreshRef, refreshTime);
|
||||
if (Exit.isSuccess(exit)) {
|
||||
if (refreshUpstream) yield* Ref.set(lastUpstreamRefreshRef, refreshTime);
|
||||
yield* Ref.set(needsInitialRefreshRef, false);
|
||||
yield* Ref.set(consecutiveFailuresRef, 0);
|
||||
return activeInterval;
|
||||
return;
|
||||
}
|
||||
|
||||
const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);
|
||||
@@ -413,33 +525,19 @@ export const make = Effect.gen(function* () {
|
||||
consecutiveFailuresRef,
|
||||
(count) => count + 1,
|
||||
);
|
||||
const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);
|
||||
const nextDelay = remoteRefreshFailureDelay(
|
||||
consecutiveFailures,
|
||||
DEFAULT_VCS_STATUS_REFRESH_INTERVAL,
|
||||
);
|
||||
yield* Effect.logWarning("VCS remote status refresh failed", {
|
||||
cwdLength: cwd.length,
|
||||
...remoteRefreshFailureDiagnostics(exit.cause),
|
||||
consecutiveFailures,
|
||||
nextDelayMs: Duration.toMillis(nextDelay),
|
||||
});
|
||||
return nextDelay;
|
||||
yield* Effect.sleep(nextDelay);
|
||||
});
|
||||
|
||||
if (!refreshImmediately) {
|
||||
const configuredInterval = yield* automaticRemoteRefreshInterval;
|
||||
yield* Effect.sleep(
|
||||
Duration.isZero(configuredInterval)
|
||||
? DEFAULT_VCS_STATUS_REFRESH_INTERVAL
|
||||
: configuredInterval,
|
||||
);
|
||||
}
|
||||
|
||||
return yield* refreshRemoteStatusIfEnabled.pipe(
|
||||
Effect.repeat(
|
||||
Schedule.identity<Duration.Duration>().pipe(
|
||||
Schedule.addDelay((delay) => Effect.succeed(delay)),
|
||||
),
|
||||
),
|
||||
Effect.asVoid,
|
||||
);
|
||||
return yield* runOnce().pipe(Effect.forever);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -535,6 +633,7 @@ export const make = Effect.gen(function* () {
|
||||
return VcsStatusBroadcaster.of({
|
||||
getStatus,
|
||||
refreshLocalStatus,
|
||||
refreshChangeRequestStatus,
|
||||
refreshStatus,
|
||||
streamStatus,
|
||||
});
|
||||
|
||||
@@ -24,14 +24,58 @@ function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
statusRefName: "feature/test",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("when: change request lookup is not confirmed", () => {
|
||||
it.each([
|
||||
{ _tag: "pending" as const },
|
||||
{
|
||||
_tag: "failed" as const,
|
||||
provider: "github" as const,
|
||||
reason: "authentication_required" as const,
|
||||
},
|
||||
])("never offers PR creation for $._tag lookup", (changeRequestLookup) => {
|
||||
const gitStatus = status({ aheadCount: 2, changeRequestLookup });
|
||||
|
||||
assert.equal(resolveQuickAction(gitStatus, false).action, "push");
|
||||
const prItem = buildMenuItems(gitStatus, false).find((item) => item.id === "pr");
|
||||
assert.equal(prItem?.disabled, true);
|
||||
assert.notEqual(prItem?.label, "Create PR");
|
||||
});
|
||||
|
||||
it("keeps an existing PR actionable when a refresh fails", () => {
|
||||
const gitStatus = status({
|
||||
pr: {
|
||||
number: 42,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/42",
|
||||
baseRef: "main",
|
||||
headRef: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
changeRequestLookup: {
|
||||
_tag: "failed",
|
||||
provider: "github",
|
||||
reason: "lookup_failed",
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(resolveQuickAction(gitStatus, false).kind, "open_pr");
|
||||
assert.equal(
|
||||
buildMenuItems(gitStatus, false).find((item) => item.id === "pr")?.label,
|
||||
"View PR",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when: ref is clean and has an open PR", () => {
|
||||
it("resolveQuickAction opens the existing PR", () => {
|
||||
const quick = resolveQuickAction(
|
||||
|
||||
@@ -3,7 +3,11 @@ import type {
|
||||
GitStackedAction,
|
||||
VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
|
||||
import {
|
||||
canCreateChangeRequest,
|
||||
getChangeRequestAvailability,
|
||||
isTemporaryWorktreeBranch,
|
||||
} from "@t3tools/shared/git";
|
||||
import {
|
||||
DEFAULT_CHANGE_REQUEST_TERMINOLOGY,
|
||||
getChangeRequestTerminology,
|
||||
@@ -101,7 +105,9 @@ export function buildMenuItems(
|
||||
|
||||
const hasBranch = gitStatus.refName !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const changeRequestAvailability = getChangeRequestAvailability(gitStatus);
|
||||
const hasOpenPr = changeRequestAvailability === "open";
|
||||
const lookupSucceeded = changeRequestAvailability === "available";
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
const hasDefaultBranchDelta = (gitStatus.aheadOfDefaultCount ?? gitStatus.aheadCount) > 0;
|
||||
const canPushWithoutUpstream = hasPrimaryRemote && !gitStatus.hasUpstream;
|
||||
@@ -116,7 +122,7 @@ export function buildMenuItems(
|
||||
!isBusy &&
|
||||
hasBranch &&
|
||||
!hasChanges &&
|
||||
!hasOpenPr &&
|
||||
canCreateChangeRequest(gitStatus) &&
|
||||
hasDefaultBranchDelta &&
|
||||
!isBehind &&
|
||||
(gitStatus.hasUpstream || canPushWithoutUpstream);
|
||||
@@ -155,7 +161,11 @@ export function buildMenuItems(
|
||||
}
|
||||
: {
|
||||
id: "pr",
|
||||
label: `Create ${terminology.shortLabel}`,
|
||||
label: lookupSucceeded
|
||||
? `Create ${terminology.shortLabel}`
|
||||
: changeRequestAvailability === "pending"
|
||||
? `Checking ${terminology.shortLabel} status`
|
||||
: `${terminology.shortLabel} status unavailable`,
|
||||
disabled: !canCreatePr,
|
||||
icon: "pr",
|
||||
kind: "open_dialog",
|
||||
@@ -185,7 +195,9 @@ export function resolveQuickAction(
|
||||
|
||||
const hasBranch = gitStatus.refName !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const changeRequestAvailability = getChangeRequestAvailability(gitStatus);
|
||||
const hasOpenPr = changeRequestAvailability === "open";
|
||||
const lookupSucceeded = changeRequestAvailability === "available";
|
||||
const isAhead = gitStatus.aheadCount > 0;
|
||||
const hasDefaultBranchDelta = (gitStatus.aheadOfDefaultCount ?? gitStatus.aheadCount) > 0;
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
@@ -205,7 +217,7 @@ export function resolveQuickAction(
|
||||
if (!gitStatus.hasUpstream && !hasPrimaryRemote) {
|
||||
return { label: "Commit", disabled: false, kind: "run_action", action: "commit" };
|
||||
}
|
||||
if (hasOpenPr || isDefaultRef) {
|
||||
if (hasOpenPr || isDefaultRef || !lookupSucceeded) {
|
||||
return { label: "Commit & push", disabled: false, kind: "run_action", action: "commit_push" };
|
||||
}
|
||||
return {
|
||||
@@ -238,7 +250,7 @@ export function resolveQuickAction(
|
||||
hint: "No local commits to push.",
|
||||
};
|
||||
}
|
||||
if (hasOpenPr || isDefaultRef) {
|
||||
if (hasOpenPr || isDefaultRef || !lookupSucceeded) {
|
||||
return {
|
||||
label: "Push",
|
||||
disabled: false,
|
||||
@@ -272,7 +284,7 @@ export function resolveQuickAction(
|
||||
}
|
||||
|
||||
if (isAhead) {
|
||||
if (hasOpenPr || isDefaultRef) {
|
||||
if (hasOpenPr || isDefaultRef || !lookupSucceeded) {
|
||||
return {
|
||||
label: "Push",
|
||||
disabled: false,
|
||||
@@ -292,6 +304,21 @@ export function resolveQuickAction(
|
||||
return { label: `View ${terminology.shortLabel}`, disabled: false, kind: "open_pr" };
|
||||
}
|
||||
|
||||
if (!lookupSucceeded) {
|
||||
return {
|
||||
label:
|
||||
changeRequestAvailability === "pending"
|
||||
? `Checking ${terminology.shortLabel} status`
|
||||
: `${terminology.shortLabel} status unavailable`,
|
||||
disabled: true,
|
||||
kind: "show_hint",
|
||||
hint:
|
||||
changeRequestAvailability === "pending"
|
||||
? `Checking for an existing ${terminology.singular}.`
|
||||
: `${terminology.shortLabel} status could not be checked.`,
|
||||
};
|
||||
}
|
||||
|
||||
if (hasDefaultBranchDelta && !isDefaultRef) {
|
||||
return {
|
||||
label: `Create ${terminology.shortLabel}`,
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
ThreadStatusLabel,
|
||||
ThreadWorktreeIndicator,
|
||||
} from "./ThreadStatusIndicators";
|
||||
import { changeRequestLookupWarning } from "./ThreadStatusIndicators.logic";
|
||||
import { ProjectFavicon } from "./ProjectFavicon";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { autoAnimate } from "@formkit/auto-animate";
|
||||
@@ -470,6 +471,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
|
||||
});
|
||||
const pr = resolveThreadPr(thread.branch, gitStatus.data);
|
||||
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
|
||||
const lookupWarning = changeRequestLookupWarning(thread.branch, gitStatus.data);
|
||||
const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
|
||||
const isConfirmingArchive = confirmingArchiveThreadKey === threadKey && !isThreadRunning;
|
||||
const threadMetaClassName = isConfirmingArchive
|
||||
@@ -711,6 +713,22 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
|
||||
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
{lookupWarning && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
role="img"
|
||||
aria-label={lookupWarning}
|
||||
className="inline-flex items-center justify-center text-amber-600/70 dark:text-amber-300/70"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<TriangleAlertIcon className="size-3" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{lookupWarning}</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
{threadStatus && <ThreadStatusLabel status={threadStatus} />}
|
||||
{renamingThreadKey === threadKey ? (
|
||||
<input
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { VcsStatusResult } from "@t3tools/contracts";
|
||||
|
||||
import { resolveChangeRequestPresentation } from "../sourceControlPresentation";
|
||||
|
||||
export function changeRequestLookupWarning(
|
||||
threadBranch: string | null,
|
||||
gitStatus: VcsStatusResult | null,
|
||||
): string | null {
|
||||
if (
|
||||
threadBranch === null ||
|
||||
gitStatus === null ||
|
||||
gitStatus.refName !== threadBranch ||
|
||||
gitStatus.changeRequestLookup._tag !== "failed"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const presentation = resolveChangeRequestPresentation(gitStatus.sourceControlProvider);
|
||||
switch (gitStatus.changeRequestLookup.reason) {
|
||||
case "authentication_required":
|
||||
return `${presentation.shortName} status unavailable: authentication required.`;
|
||||
case "provider_unavailable":
|
||||
return `${presentation.shortName} status unavailable: provider integration unavailable.`;
|
||||
case "lookup_failed":
|
||||
return `${presentation.shortName} status unavailable: lookup failed.`;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,58 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { ThreadId, type VcsStatusResult } from "@t3tools/contracts";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { changeRequestLookupWarning } from "./ThreadStatusIndicators.logic";
|
||||
import { ThreadWorktreeIndicator } from "./ThreadStatusIndicators";
|
||||
|
||||
const failedStatus: VcsStatusResult = {
|
||||
isRepo: true,
|
||||
sourceControlProvider: { kind: "github", name: "GitHub", baseUrl: "https://github.com" },
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/sidebar-indicator",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
statusRefName: "feature/sidebar-indicator",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: {
|
||||
_tag: "failed",
|
||||
provider: "github",
|
||||
reason: "authentication_required",
|
||||
},
|
||||
};
|
||||
|
||||
describe("changeRequestLookupWarning", () => {
|
||||
it("returns actionable provider copy for the matching thread branch", () => {
|
||||
expect(changeRequestLookupWarning("feature/sidebar-indicator", failedStatus)).toBe(
|
||||
"PR status unavailable: authentication required.",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not leak warnings across branches", () => {
|
||||
expect(changeRequestLookupWarning("feature/other", failedStatus)).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the refresh warning when a cached open PR remains actionable", () => {
|
||||
expect(
|
||||
changeRequestLookupWarning("feature/sidebar-indicator", {
|
||||
...failedStatus,
|
||||
pr: {
|
||||
number: 42,
|
||||
title: "Cached open PR",
|
||||
url: "https://example.com/pr/42",
|
||||
baseRef: "main",
|
||||
headRef: "feature/sidebar-indicator",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
).toBe("PR status unavailable: authentication required.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ThreadWorktreeIndicator", () => {
|
||||
it("renders the worktree folder and branch in an accessible label", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
|
||||
@@ -4,7 +4,13 @@ import {
|
||||
scopeThreadRef,
|
||||
} from "@t3tools/client-runtime/environment";
|
||||
import type { VcsStatusResult } from "@t3tools/contracts";
|
||||
import { CloudIcon, FolderGit2Icon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
|
||||
import {
|
||||
CloudIcon,
|
||||
FolderGit2Icon,
|
||||
GitPullRequestIcon,
|
||||
TerminalIcon,
|
||||
TriangleAlertIcon,
|
||||
} from "lucide-react";
|
||||
import { useMemo } from "react";
|
||||
import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments";
|
||||
import { useProject } from "../state/entities";
|
||||
@@ -14,6 +20,7 @@ import { vcsEnvironment } from "../state/vcs";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
import { resolveChangeRequestPresentation } from "../sourceControlPresentation";
|
||||
import { resolveThreadStatusPill, type ThreadStatusPill } from "./Sidebar.logic";
|
||||
import { changeRequestLookupWarning } from "./ThreadStatusIndicators.logic";
|
||||
import type { SidebarThreadSummary } from "../types";
|
||||
import { formatWorktreePathForDisplay } from "../worktreeCleanup";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
@@ -208,6 +215,7 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
|
||||
);
|
||||
const pr = resolveThreadPr(thread.branch, gitStatus.data);
|
||||
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
|
||||
const lookupWarning = changeRequestLookupWarning(thread.branch, gitStatus.data);
|
||||
const threadStatus = resolveThreadStatusPill({
|
||||
thread: {
|
||||
...thread,
|
||||
@@ -215,7 +223,7 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
|
||||
},
|
||||
});
|
||||
|
||||
if (!prStatus && !threadStatus) {
|
||||
if (!prStatus && !lookupWarning && !threadStatus) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -236,6 +244,21 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
|
||||
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
{lookupWarning ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
aria-label={lookupWarning}
|
||||
className="inline-flex items-center justify-center text-amber-600/70 dark:text-amber-300/70"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<TriangleAlertIcon className="size-3" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{lookupWarning}</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
{threadStatus ? <ThreadStatusLabel status={threadStatus} /> : null}
|
||||
</span>
|
||||
);
|
||||
|
||||
@@ -329,7 +329,8 @@ function GitFetchIntervalSettings() {
|
||||
</div>
|
||||
<p className="max-w-2xl text-xs leading-relaxed text-muted-foreground">
|
||||
Refresh remote branch status in the background. Set this to 0 seconds if Git credentials
|
||||
or security keys should only be prompted by explicit Git actions.
|
||||
or security keys should only be prompted by explicit Git actions. Lightweight pull or
|
||||
merge request status checks continue without fetching Git remotes.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { VcsStatusResult } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { buildMenuItems, resolveQuickAction } from "./gitActions.ts";
|
||||
|
||||
function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/test",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
statusRefName: "feature/test",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("change request certainty", () => {
|
||||
it.each([
|
||||
{ _tag: "pending" as const },
|
||||
{
|
||||
_tag: "failed" as const,
|
||||
provider: "github" as const,
|
||||
reason: "lookup_failed" as const,
|
||||
},
|
||||
])("never creates a PR while lookup is $._tag", (changeRequestLookup) => {
|
||||
const ahead = status({ aheadCount: 1, changeRequestLookup });
|
||||
const dirty = status({ hasWorkingTreeChanges: true, changeRequestLookup });
|
||||
|
||||
expect(resolveQuickAction(ahead, false).action).toBe("push");
|
||||
expect(resolveQuickAction(dirty, false).action).toBe("commit_push");
|
||||
expect(buildMenuItems(ahead, false).find((item) => item.id === "pr")?.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("allows creation after a successful lookup confirms absence", () => {
|
||||
expect(resolveQuickAction(status({ aheadCount: 1 }), false).action).toBe("create_pr");
|
||||
});
|
||||
|
||||
it("keeps a cached open PR actionable when lookup fails", () => {
|
||||
const gitStatus = status({
|
||||
pr: {
|
||||
number: 42,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/42",
|
||||
baseRef: "main",
|
||||
headRef: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
changeRequestLookup: {
|
||||
_tag: "failed",
|
||||
provider: "github",
|
||||
reason: "lookup_failed",
|
||||
},
|
||||
});
|
||||
|
||||
expect(resolveQuickAction(gitStatus, false).kind).toBe("open_pr");
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,11 @@ import type {
|
||||
GitStackedAction,
|
||||
VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
|
||||
import {
|
||||
canCreateChangeRequest,
|
||||
getChangeRequestAvailability,
|
||||
isTemporaryWorktreeBranch,
|
||||
} from "@t3tools/shared/git";
|
||||
|
||||
export type GitActionIconName = "commit" | "push" | "pr";
|
||||
|
||||
@@ -91,7 +95,9 @@ export function buildMenuItems(
|
||||
|
||||
const hasBranch = gitStatus.refName !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const changeRequestAvailability = getChangeRequestAvailability(gitStatus);
|
||||
const hasOpenPr = changeRequestAvailability === "open";
|
||||
const lookupSucceeded = changeRequestAvailability === "available";
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
const canPushWithoutUpstream = hasOriginRemote && !gitStatus.hasUpstream;
|
||||
const canCommit = !isBusy && hasChanges;
|
||||
@@ -106,7 +112,7 @@ export function buildMenuItems(
|
||||
!isBusy &&
|
||||
hasBranch &&
|
||||
!hasChanges &&
|
||||
!hasOpenPr &&
|
||||
canCreateChangeRequest(gitStatus) &&
|
||||
gitStatus.aheadCount > 0 &&
|
||||
!isBehind &&
|
||||
(gitStatus.hasUpstream || canPushWithoutUpstream);
|
||||
@@ -139,7 +145,11 @@ export function buildMenuItems(
|
||||
}
|
||||
: {
|
||||
id: "pr",
|
||||
label: "Create PR",
|
||||
label: lookupSucceeded
|
||||
? "Create PR"
|
||||
: changeRequestAvailability === "pending"
|
||||
? "Checking PR status"
|
||||
: "PR status unavailable",
|
||||
disabled: !canCreatePr,
|
||||
icon: "pr",
|
||||
kind: "open_dialog",
|
||||
@@ -169,7 +179,9 @@ export function resolveQuickAction(
|
||||
|
||||
const hasBranch = gitStatus.refName !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const changeRequestAvailability = getChangeRequestAvailability(gitStatus);
|
||||
const hasOpenPr = changeRequestAvailability === "open";
|
||||
const lookupSucceeded = changeRequestAvailability === "available";
|
||||
const isAhead = gitStatus.aheadCount > 0;
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
const isDiverged = isAhead && isBehind;
|
||||
@@ -187,7 +199,7 @@ export function resolveQuickAction(
|
||||
if (!gitStatus.hasUpstream && !hasOriginRemote) {
|
||||
return { label: "Commit", disabled: false, kind: "run_action", action: "commit" };
|
||||
}
|
||||
if (hasOpenPr || isDefaultBranch) {
|
||||
if (hasOpenPr || isDefaultBranch || !lookupSucceeded) {
|
||||
return { label: "Commit & push", disabled: false, kind: "run_action", action: "commit_push" };
|
||||
}
|
||||
return {
|
||||
@@ -221,7 +233,7 @@ export function resolveQuickAction(
|
||||
hint: "No local commits to push.",
|
||||
};
|
||||
}
|
||||
if (hasOpenPr || isDefaultBranch) {
|
||||
if (hasOpenPr || isDefaultBranch || !lookupSucceeded) {
|
||||
return {
|
||||
label: "Push",
|
||||
disabled: false,
|
||||
@@ -255,7 +267,7 @@ export function resolveQuickAction(
|
||||
}
|
||||
|
||||
if (isAhead) {
|
||||
if (hasOpenPr || isDefaultBranch) {
|
||||
if (hasOpenPr || isDefaultBranch || !lookupSucceeded) {
|
||||
return {
|
||||
label: "Push",
|
||||
disabled: false,
|
||||
@@ -275,6 +287,19 @@ export function resolveQuickAction(
|
||||
return { label: "View PR", disabled: false, kind: "open_pr" };
|
||||
}
|
||||
|
||||
if (!lookupSucceeded) {
|
||||
return {
|
||||
label:
|
||||
changeRequestAvailability === "pending" ? "Checking PR status" : "PR status unavailable",
|
||||
disabled: true,
|
||||
kind: "show_hint",
|
||||
hint:
|
||||
changeRequestAvailability === "pending"
|
||||
? "Checking for an existing PR."
|
||||
: "PR status could not be checked.",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
label: "Commit",
|
||||
disabled: true,
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
GitRunStackedActionResult,
|
||||
GitRunStackedActionInput,
|
||||
GitResolvePullRequestResult,
|
||||
VcsStatusChangeRequestLookup,
|
||||
} from "./git.ts";
|
||||
|
||||
const decodeCreateWorktreeInput = Schema.decodeUnknownSync(VcsCreateWorktreeInput);
|
||||
@@ -16,6 +17,19 @@ const decodePreparePullRequestThreadInput = Schema.decodeUnknownSync(
|
||||
const decodeRunStackedActionInput = Schema.decodeUnknownSync(GitRunStackedActionInput);
|
||||
const decodeRunStackedActionResult = Schema.decodeUnknownSync(GitRunStackedActionResult);
|
||||
const decodeResolvePullRequestResult = Schema.decodeUnknownSync(GitResolvePullRequestResult);
|
||||
const decodeChangeRequestLookup = Schema.decodeUnknownSync(VcsStatusChangeRequestLookup);
|
||||
|
||||
describe("VcsStatusChangeRequestLookup", () => {
|
||||
it.each([
|
||||
{ _tag: "pending" },
|
||||
{ _tag: "succeeded" },
|
||||
{ _tag: "failed", provider: "github", reason: "authentication_required" },
|
||||
{ _tag: "failed", provider: "gitlab", reason: "provider_unavailable" },
|
||||
{ _tag: "failed", provider: "bitbucket", reason: "lookup_failed" },
|
||||
])("decodes provider-neutral lookup state $._tag", (lookup) => {
|
||||
expect(decodeChangeRequestLookup(lookup)).toEqual(lookup);
|
||||
});
|
||||
});
|
||||
|
||||
describe("VcsCreateWorktreeInput", () => {
|
||||
it("accepts omitted newRefName for existing-refName worktrees", () => {
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import { NonNegativeInt, PositiveInt, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
import { SourceControlProviderError, SourceControlProviderInfo } from "./sourceControl.ts";
|
||||
import {
|
||||
SourceControlProviderError,
|
||||
SourceControlProviderInfo,
|
||||
SourceControlProviderKind,
|
||||
} from "./sourceControl.ts";
|
||||
import { VcsDriverKind } from "./vcs.ts";
|
||||
|
||||
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
|
||||
@@ -198,6 +202,16 @@ const VcsStatusChangeRequest = Schema.Struct({
|
||||
state: VcsStatusChangeRequestState,
|
||||
});
|
||||
|
||||
export const VcsStatusChangeRequestLookup = Schema.Union([
|
||||
Schema.TaggedStruct("pending", {}),
|
||||
Schema.TaggedStruct("succeeded", {}),
|
||||
Schema.TaggedStruct("failed", {
|
||||
provider: SourceControlProviderKind,
|
||||
reason: Schema.Literals(["authentication_required", "provider_unavailable", "lookup_failed"]),
|
||||
}),
|
||||
]);
|
||||
export type VcsStatusChangeRequestLookup = typeof VcsStatusChangeRequestLookup.Type;
|
||||
|
||||
const VcsStatusLocalShape = {
|
||||
isRepo: Schema.Boolean,
|
||||
sourceControlProvider: Schema.optional(SourceControlProviderInfo),
|
||||
@@ -219,11 +233,13 @@ const VcsStatusLocalShape = {
|
||||
};
|
||||
|
||||
const VcsStatusRemoteShape = {
|
||||
statusRefName: Schema.NullOr(TrimmedNonEmptyStringSchema),
|
||||
hasUpstream: Schema.Boolean,
|
||||
aheadCount: NonNegativeInt,
|
||||
behindCount: NonNegativeInt,
|
||||
aheadOfDefaultCount: Schema.optional(NonNegativeInt),
|
||||
pr: Schema.NullOr(VcsStatusChangeRequest),
|
||||
changeRequestLookup: VcsStatusChangeRequestLookup,
|
||||
};
|
||||
|
||||
export const VcsStatusLocalResult = Schema.Struct(VcsStatusLocalShape);
|
||||
|
||||
@@ -79,12 +79,38 @@ describe("isTemporaryWorktreeBranch", () => {
|
||||
});
|
||||
|
||||
describe("applyGitStatusStreamEvent", () => {
|
||||
const localStatus = {
|
||||
isRepo: true as const,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/demo",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
};
|
||||
|
||||
it("keeps an initial snapshot pending until remote lookup completes", () => {
|
||||
expect(
|
||||
applyGitStatusStreamEvent(null, {
|
||||
_tag: "snapshot",
|
||||
local: localStatus,
|
||||
remote: null,
|
||||
}),
|
||||
).toMatchObject({
|
||||
refName: "feature/demo",
|
||||
statusRefName: null,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "pending" },
|
||||
});
|
||||
});
|
||||
|
||||
it("treats a remote-only update as a repository when local state is missing", () => {
|
||||
const remote: VcsStatusRemoteResult = {
|
||||
statusRefName: null,
|
||||
hasUpstream: true,
|
||||
aheadCount: 2,
|
||||
behindCount: 1,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
};
|
||||
|
||||
expect(applyGitStatusStreamEvent(null, { _tag: "remoteUpdated", remote })).toEqual({
|
||||
@@ -94,10 +120,12 @@ describe("applyGitStatusStreamEvent", () => {
|
||||
refName: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
statusRefName: null,
|
||||
hasUpstream: true,
|
||||
aheadCount: 2,
|
||||
behindCount: 1,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -118,17 +146,21 @@ describe("applyGitStatusStreamEvent", () => {
|
||||
insertions: 1,
|
||||
deletions: 0,
|
||||
},
|
||||
statusRefName: "feature/demo",
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
};
|
||||
|
||||
const remote: VcsStatusRemoteResult = {
|
||||
statusRefName: "feature/demo",
|
||||
hasUpstream: true,
|
||||
aheadCount: 2,
|
||||
behindCount: 1,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
};
|
||||
|
||||
expect(applyGitStatusStreamEvent(current, { _tag: "remoteUpdated", remote })).toEqual({
|
||||
@@ -137,6 +169,77 @@ describe("applyGitStatusStreamEvent", () => {
|
||||
aheadCount: 2,
|
||||
behindCount: 1,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
});
|
||||
});
|
||||
|
||||
it("clears remote state when a local update switches branches", () => {
|
||||
const current: VcsStatusResult = {
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/old",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
statusRefName: "feature/old",
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: {
|
||||
number: 12,
|
||||
title: "Old branch PR",
|
||||
url: "https://example.com/pr/12",
|
||||
baseRef: "main",
|
||||
headRef: "feature/old",
|
||||
state: "open",
|
||||
},
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
};
|
||||
|
||||
expect(
|
||||
applyGitStatusStreamEvent(current, {
|
||||
_tag: "localUpdated",
|
||||
local: { ...current, refName: "feature/new" },
|
||||
}),
|
||||
).toMatchObject({
|
||||
refName: "feature/new",
|
||||
statusRefName: null,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "pending" },
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores a late remote update calculated for a previous branch", () => {
|
||||
const current: VcsStatusResult = {
|
||||
...localStatus,
|
||||
refName: "feature/new",
|
||||
statusRefName: null,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "pending" },
|
||||
};
|
||||
|
||||
expect(
|
||||
applyGitStatusStreamEvent(current, {
|
||||
_tag: "remoteUpdated",
|
||||
remote: {
|
||||
statusRefName: "feature/old",
|
||||
hasUpstream: true,
|
||||
aheadCount: 1,
|
||||
behindCount: 0,
|
||||
pr: {
|
||||
number: 12,
|
||||
title: "Old branch PR",
|
||||
url: "https://example.com/pr/12",
|
||||
baseRef: "main",
|
||||
headRef: "feature/old",
|
||||
state: "open",
|
||||
},
|
||||
changeRequestLookup: { _tag: "succeeded" },
|
||||
},
|
||||
}),
|
||||
).toEqual(current);
|
||||
});
|
||||
});
|
||||
@@ -203,25 +203,37 @@ export function detectSourceControlProviderFromGitRemoteUrl(
|
||||
}
|
||||
|
||||
const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
|
||||
statusRefName: null,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
changeRequestLookup: { _tag: "pending" },
|
||||
};
|
||||
|
||||
function remoteStatusForLocal(
|
||||
local: VcsStatusLocalResult,
|
||||
remote: VcsStatusRemoteResult | null,
|
||||
): VcsStatusRemoteResult {
|
||||
return remote !== null && remote.statusRefName === local.refName
|
||||
? remote
|
||||
: EMPTY_GIT_STATUS_REMOTE;
|
||||
}
|
||||
|
||||
export function mergeGitStatusParts(
|
||||
local: VcsStatusLocalResult,
|
||||
remote: VcsStatusRemoteResult | null,
|
||||
): VcsStatusResult {
|
||||
return {
|
||||
...local,
|
||||
...(remote ?? EMPTY_GIT_STATUS_REMOTE),
|
||||
...remoteStatusForLocal(local, remote),
|
||||
};
|
||||
}
|
||||
|
||||
function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
|
||||
return {
|
||||
statusRefName: status.statusRefName,
|
||||
hasUpstream: status.hasUpstream,
|
||||
aheadCount: status.aheadCount,
|
||||
behindCount: status.behindCount,
|
||||
@@ -229,6 +241,7 @@ function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
|
||||
? {}
|
||||
: { aheadOfDefaultCount: status.aheadOfDefaultCount }),
|
||||
pr: status.pr,
|
||||
changeRequestLookup: status.changeRequestLookup,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -269,6 +282,22 @@ export function applyGitStatusStreamEvent(
|
||||
event.remote,
|
||||
);
|
||||
}
|
||||
if (event.remote?.statusRefName !== current.refName) {
|
||||
return current;
|
||||
}
|
||||
return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
|
||||
}
|
||||
}
|
||||
|
||||
export type ChangeRequestAvailability = "pending" | "failed" | "open" | "available";
|
||||
|
||||
export function getChangeRequestAvailability(status: VcsStatusResult): ChangeRequestAvailability {
|
||||
if (status.pr?.state === "open") return "open";
|
||||
if (status.changeRequestLookup._tag === "pending") return "pending";
|
||||
if (status.changeRequestLookup._tag === "failed") return "failed";
|
||||
return "available";
|
||||
}
|
||||
|
||||
export function canCreateChangeRequest(status: VcsStatusResult): boolean {
|
||||
return getChangeRequestAvailability(status) === "available";
|
||||
}
|
||||
Reference in new issue
Block a user