Skip to content

Commit cbaa176

Browse files
wSedlacekclaude
andcommitted
fix(git): queued commits wait for background work and stay on their branch
Review fixes for the commit confirmation and queue: - A queued commit waits while the agent is parked on background work, and drops if the thread moves to another checkout. - A second commit can no longer silently replace a queued one. - Actions that can commit always confirm during a run, instead of trusting a status that may have gone stale. - The branch guard accepts a mismatch only when the reflog shows the temporary branch was renamed to the current one. - A confirmed action stays pinned to the branch it was confirmed on, and the run prompt no longer repeats after the default branch prompt. - Cancelling the run prompt keeps the commit dialog's message and files on the new-branch path too. - Status refreshes that overlap a running read now run after it, and a PR lookup no longer skips the divergence refresh. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 82580b5 commit cbaa176

16 files changed

Lines changed: 213 additions & 68 deletions

‎apps/mobile/src/features/threads/ThreadGitControls.tsx‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,6 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) {
185185
const decision = await confirmCommitDuringRun({
186186
thread: threadRef,
187187
action: input.action,
188-
hasChanges: gitStatus?.hasWorkingTreeChanges === true,
189188
queuedRun: requiresDefaultBranchConfirmation(input.action, isDefaultRef)
190189
? null
191190
: () => void onRunAction(request),

‎apps/mobile/src/features/threads/git/GitCommitSheet.tsx‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,6 @@ export function GitCommitSheet(_props: GitCommitSheetProps) {
7272
? null
7373
: { environmentId: selectedThread.environmentId, threadId: selectedThread.id },
7474
action: "commit",
75-
hasChanges: true,
7675
queuedRun: () => void gitActions.onRunSelectedThreadGitAction(request),
7776
});
7877
if (decision === "cancelled") return;

‎apps/mobile/src/features/threads/git/GitOverviewSheet.tsx‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,6 @@ function GitOverviewSheetContent(props: GitOverviewSheetProps) {
150150
const decision = await confirmCommitDuringRun({
151151
thread: { environmentId, threadId },
152152
action: input.action,
153-
hasChanges: gitStatus.data?.hasWorkingTreeChanges === true,
154153
queuedRun: requiresDefaultBranchConfirmation(input.action, isDefaultRef)
155154
? null
156155
: () => void gitActions.onRunSelectedThreadGitAction(request),

‎apps/mobile/src/features/threads/git/confirmCommitDuringRun.ts‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
1+
import { threadWorkIsActive } from "@t3tools/client-runtime/state/shell";
22
import {
33
ACTIVE_RUN_COMMIT_COPY,
44
QUEUED_COMMIT_DROPPED_COPY,
@@ -14,20 +14,22 @@ import { gitActionQueue } from "../../../state/vcs";
1414
export function confirmCommitDuringRun(input: {
1515
readonly thread: ScopedThreadRef | null;
1616
readonly action: GitStackedAction;
17-
readonly hasChanges: boolean;
1817
readonly queuedRun: (() => void) | null;
1918
}): Promise<"proceed" | "queued" | "cancelled"> {
2019
const { thread, queuedRun } = input;
2120
// A native menu keeps the closure from when it opened, and a run can start while it is open.
2221
const shell =
2322
thread === null ? null : appAtomRegistry.get(environmentThreadShells.threadShellAtom(thread));
24-
const isThreadRunning = threadRuntimeIsActive(shell?.runtime);
25-
if (!requiresActiveRunConfirmation(input.action, isThreadRunning, input.hasChanges)) {
23+
if (!requiresActiveRunConfirmation(input.action, threadWorkIsActive(shell))) {
2624
return Promise.resolve("proceed");
2725
}
26+
const canQueue =
27+
thread !== null &&
28+
queuedRun !== null &&
29+
appAtomRegistry.get(gitActionQueue.queuedActionAtom(thread)) === null;
2830
return new Promise((resolve) => {
2931
Dialog.alert(ACTIVE_RUN_COMMIT_COPY.title, ACTIVE_RUN_COMMIT_COPY.description, [
30-
...(thread !== null && queuedRun !== null
32+
...(canQueue
3133
? [
3234
{
3335
text: ACTIVE_RUN_COMMIT_COPY.queueLabel,

‎apps/server/src/git/GitManager.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4431,6 +4431,19 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
44314431
});
44324432
expect(renamed.commit.status).toBe("created");
44334433

4434+
yield* runGit(repoDir, ["branch", "t3/deadbeef"]);
4435+
NodeFS.writeFileSync(NodePath.join(repoDir, "unrelated.txt"), "unrelated\n");
4436+
const unrelatedMessage = yield* runStackedAction(manager, {
4437+
cwd: repoDir,
4438+
action: "commit",
4439+
commitMessage: "Should not land on an unrelated branch",
4440+
expectedRefName: "t3/deadbeef",
4441+
}).pipe(
4442+
Effect.flip,
4443+
Effect.map((error) => error.message),
4444+
);
4445+
expect(unrelatedMessage).toContain('"feature/renamed" is checked out');
4446+
44344447
yield* runGit(repoDir, ["checkout", "main"]);
44354448
NodeFS.writeFileSync(NodePath.join(repoDir, "default.txt"), "default\n");
44364449
const defaultRefMessage = yield* runStackedAction(manager, {

‎apps/server/src/git/GitManager.ts‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2195,6 +2195,22 @@ export const make = Effect.gen(function* () {
21952195
});
21962196
});
21972197

2198+
const wasRenamedTo = Effect.fn("wasRenamedTo")(function* (
2199+
cwd: string,
2200+
oldBranch: string,
2201+
branch: string,
2202+
) {
2203+
const rename = `Branch: renamed refs/heads/${oldBranch} to refs/heads/${branch}`;
2204+
const reflog = yield* gitCore.execute({
2205+
operation: "GitManager.wasRenamedTo",
2206+
cwd,
2207+
args: ["log", "-g", "--format=%gs", "--fixed-strings", `--grep-reflog=${rename}`, "HEAD"],
2208+
allowNonZeroExit: true,
2209+
timeoutMs: 5_000,
2210+
});
2211+
return reflog.exitCode === 0 && reflog.stdout.split("\n").includes(rename);
2212+
});
2213+
21982214
const runCommitStep = Effect.fn("runCommitStep")(function* (
21992215
settings: SourceControlTextGenerationSettings,
22002216
cwd: string,
@@ -2455,7 +2471,11 @@ export const make = Effect.gen(function* () {
24552471
const remoteStatus: GitManager["Service"]["remoteStatus"] = Effect.fn("remoteStatus")(
24562472
function* (input, options) {
24572473
const cacheKey = yield* normalizeStatusCacheKey(input.cwd);
2458-
if (options?.refreshUpstream === false || options?.refreshMissingPullRequest) {
2474+
if (
2475+
options?.refreshUpstream === false ||
2476+
options?.refreshMissingPullRequest ||
2477+
options?.reuseKnownPullRequest
2478+
) {
24592479
return yield* readRemoteStatus(cacheKey, options);
24602480
}
24612481
return yield* Cache.get(remoteStatusResultCache, cacheKey);
@@ -3200,7 +3220,8 @@ export const make = Effect.gen(function* () {
32003220
input.expectedRefName !== undefined &&
32013221
isTemporaryWorktreeBranch(input.expectedRefName) &&
32023222
initialStatus.branch !== null &&
3203-
!initialStatus.isDefaultBranch;
3223+
!initialStatus.isDefaultBranch &&
3224+
(yield* wasRenamedTo(input.cwd, input.expectedRefName, initialStatus.branch));
32043225
if (
32053226
input.expectedRefName !== undefined &&
32063227
input.expectedRefName !== initialStatus.branch &&

‎apps/server/src/orchestration-v2/RunFinalizationService.test.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,8 @@ it.effect("a divergence-only refresh does not cancel another turn's PR lookup",
202202
const lookupStarted = Deferred.makeUnsafe<void>();
203203
const release = Deferred.makeUnsafe<void>();
204204
const finished = Deferred.makeUnsafe<void>();
205+
const divergedAgain = Deferred.makeUnsafe<void>();
206+
let divergenceRefreshes = 0;
205207
let checkedOutBranch = "feature";
206208
const layer = RunFinalization.layerObserver.pipe(
207209
Layer.provide(
@@ -220,7 +222,13 @@ it.effect("a divergence-only refresh does not cancel another turn's PR lookup",
220222
hasWorkingTreeChanges: false,
221223
workingTree: { files: [], insertions: 0, deletions: 0 },
222224
})),
223-
refreshDivergence: () => Effect.succeed(null),
225+
refreshDivergence: () =>
226+
Effect.suspend(() => {
227+
divergenceRefreshes += 1;
228+
return divergenceRefreshes === 2
229+
? Deferred.succeed(divergedAgain, undefined).pipe(Effect.as(null))
230+
: Effect.succeed(null);
231+
}),
224232
refreshPullRequestStatus: () =>
225233
Deferred.succeed(lookupStarted, undefined).pipe(
226234
Effect.andThen(Deferred.await(release)),
@@ -245,6 +253,7 @@ it.effect("a divergence-only refresh does not cancel another turn's PR lookup",
245253
yield* Deferred.await(lookupStarted);
246254
checkedOutBranch = "other";
247255
yield* observer.refresh({ cwd: "/repo", threadId, runId });
256+
yield* Deferred.await(divergedAgain);
248257
yield* Deferred.succeed(release, undefined);
249258
yield* Deferred.await(finished);
250259
}).pipe(Effect.provide(layer));

‎apps/server/src/orchestration-v2/RunFinalizationService.ts‎

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@ export const layerObserver = Layer.effect(
9898
const projections = yield* ProjectionStore.ProjectionStoreV2;
9999
const pullRequests = yield* PullRequestService.PullRequestService;
100100
const pullRequestLookups = yield* FiberMap.make<string>();
101+
const divergenceRefreshes = yield* FiberMap.make<string>();
101102
return {
102103
refreshAfterTurn: pullRequests.refreshAfterTurn,
103104
refresh: Effect.fn("RunFinalizationService.refresh")(
@@ -113,22 +114,25 @@ export const layerObserver = Layer.effect(
113114
(thread.activeRunId === null || thread.activeRunId === runId);
114115
// Divergence goes first so a clean tree never reads as up to date while the forge CLI
115116
// runs. That CLI can take minutes, so the next turn must not wait for it. A newer
116-
// turn's lookup replaces a running one, but divergence alone must not cancel a lookup.
117+
// turn's lookup replaces a running one, but divergence alone must neither cancel a
118+
// lookup nor be skipped for one.
117119
const divergence = vcsStatus.refreshDivergence(cwd);
118-
yield* (
119-
shouldLookUpPullRequest
120-
? divergence.pipe(Effect.andThen(vcsStatus.refreshPullRequestStatus(cwd)))
121-
: divergence
122-
).pipe(
123-
Effect.catch((error) =>
124-
Effect.logWarning("failed to refresh remote status after run completion", {
125-
threadId,
126-
cwd,
127-
detail: error.message,
128-
}),
129-
),
130-
FiberMap.run(pullRequestLookups, cwd, { onlyIfMissing: !shouldLookUpPullRequest }),
131-
);
120+
const logFailure = (error: { readonly message: string }) =>
121+
Effect.logWarning("failed to refresh remote status after run completion", {
122+
threadId,
123+
cwd,
124+
detail: error.message,
125+
});
126+
yield* shouldLookUpPullRequest
127+
? divergence.pipe(
128+
Effect.andThen(vcsStatus.refreshPullRequestStatus(cwd)),
129+
Effect.catch(logFailure),
130+
FiberMap.run(pullRequestLookups, cwd),
131+
)
132+
: divergence.pipe(
133+
Effect.catch(logFailure),
134+
FiberMap.run(divergenceRefreshes, cwd, { onlyIfMissing: true }),
135+
);
132136
},
133137
(effect, { cwd }) =>
134138
effect.pipe(Effect.mapError((cause) => new RunFinalizationRefreshError({ cwd, cause }))),

‎apps/server/src/vcs/VcsStatusBroadcaster.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -579,6 +579,40 @@ describe("VcsStatusBroadcaster", () => {
579579
}).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
580580
});
581581

582+
it.effect("a watched refresh that lands during a remote read runs after it", () => {
583+
const state: Parameters<typeof layerTestFor>[0] = {
584+
currentLocalStatus: baseLocalStatus,
585+
currentRemoteStatus: baseRemoteStatus,
586+
localStatusCalls: 0,
587+
remoteStatusCalls: 0,
588+
localInvalidationCalls: 0,
589+
remoteInvalidationCalls: 0,
590+
};
591+
592+
return Effect.gen(function* () {
593+
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
594+
const remoteUpdates = yield* watchRemoteUpdates(broadcaster);
595+
596+
const reading = yield* Deferred.make<void>();
597+
const release = yield* Deferred.make<void>();
598+
state.beforeRemoteStatus = Deferred.succeed(reading, undefined).pipe(
599+
Effect.andThen(Deferred.await(release)),
600+
);
601+
yield* broadcaster.refreshWatchedStatus("/repo", { includeDivergence: true });
602+
yield* Deferred.await(reading);
603+
604+
yield* broadcaster.refreshWatchedStatus("/repo", { includeDivergence: true });
605+
state.currentRemoteStatus = { ...baseRemoteStatus, aheadCount: 1 };
606+
state.beforeRemoteStatus = Effect.sync(() => {
607+
state.currentRemoteStatus = { ...baseRemoteStatus, aheadCount: 2 };
608+
});
609+
yield* Deferred.succeed(release, undefined);
610+
611+
assert.equal((yield* Queue.take(remoteUpdates))?.aheadCount, 1);
612+
assert.equal((yield* Queue.take(remoteUpdates))?.aheadCount, 2);
613+
}).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
614+
});
615+
582616
it.effect("a poll that started before the turn-end refresh cannot overwrite its PR", () => {
583617
const releaseFirstPoll = Deferred.makeUnsafe<void>();
584618
const firstPollStarted = Deferred.makeUnsafe<void>();

‎apps/server/src/vcs/VcsStatusBroadcaster.ts‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,7 @@ export const make = Effect.gen(function* () {
273273
remoteWriteLocks.withLock(cwd, effect);
274274
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
275275
const remoteRefreshes = yield* FiberMap.make<string>();
276+
const remoteRefreshesWanted = new Set<string>();
276277

277278
const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
278279
cwd: string,
@@ -578,6 +579,16 @@ export const make = Effect.gen(function* () {
578579
);
579580
});
580581

582+
const refreshWantedRemote = Effect.fn("VcsStatusBroadcaster.refreshWantedRemote")(function* (
583+
cwd: string,
584+
) {
585+
remoteRefreshesWanted.delete(cwd);
586+
const remoteMissing = !(yield* getCachedStatus(cwd))?.remote?.value;
587+
return yield* remoteMissing
588+
? refreshRemoteStatus(cwd, { refreshUpstream: false })
589+
: refreshDivergence(cwd);
590+
});
591+
581592
const refreshWatchedStatus: VcsStatusBroadcaster["Service"]["refreshWatchedStatus"] = Effect.fn(
582593
"VcsStatusBroadcaster.refreshWatchedStatus",
583594
)(function* (rawCwd, { includeDivergence }) {
@@ -589,11 +600,11 @@ export const make = Effect.gen(function* () {
589600
// A clean tree reads as up to date until divergence catches up, and a new ref reads as pending.
590601
if (!includeDivergence && !remoteMissing && !(wasDirty && !local.hasWorkingTreeChanges)) return;
591602
// A forge lookup can hold the remote lock for minutes, and local refreshes must not wait on it.
592-
const remoteRead = remoteMissing
593-
? refreshRemoteStatus(cwd, { refreshUpstream: false })
594-
: refreshDivergence(cwd);
595-
yield* remoteRead.pipe(
603+
// A read already running may discard its result for a ref that moved, so ask for another.
604+
remoteRefreshesWanted.add(cwd);
605+
yield* Effect.suspend(() => refreshWantedRemote(cwd)).pipe(
596606
Effect.ignore({ log: true }),
607+
Effect.repeat({ while: () => remoteRefreshesWanted.has(cwd) }),
597608
FiberMap.run(remoteRefreshes, cwd, { onlyIfMissing: true }),
598609
);
599610
});

0 commit comments

Comments
 (0)