@devries-cameron20 / t3code Mirror · read-only / commits / a575d45286
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 14:45 UTC

fix(web,server): the branch label no longer flips back after a switch (#28575)

Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Andrei committed Nov 14, 2026 at 20:56 UTC a575d45286f0c6496a47f823485b598167f52437
6 files changed +240 -28
apps/server/src/vcs/VcsStatusBroadcaster.test.ts
+43
@@ -1068,6 +1068,49 @@ describe("VcsStatusBroadcaster", () => {
1068 },
1069 );
1070
1071 + it.effect("publishes a checkout's branch before returning, ahead of the remote read", () => {
1072 + const state: Parameters<typeof layerTestFor>[0] = {
1073 + currentLocalStatus: baseLocalStatus,
1074 + currentRemoteStatus: baseRemoteStatus,
1075 + localStatusCalls: 0,
1076 + remoteStatusCalls: 0,
1077 + localInvalidationCalls: 0,
1078 + remoteInvalidationCalls: 0,
1079 + };
1080 +
1081 + return Effect.gen(function* () {
1082 + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
1083 + yield* broadcaster.getStatus({ cwd: "/repo" });
1084 + const subscribed = yield* Deferred.make<void>();
1085 + const localPublished = yield* Deferred.make<VcsStatusLocalResult>();
1086 + const remotePublished = yield* Deferred.make<VcsStatusRemoteResult | null>();
1087 + yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe(
1088 + Stream.runForEach((event) => {
1089 + if (event._tag === "snapshot") return Deferred.succeed(subscribed, undefined);
1090 + if (event._tag === "localUpdated") return Deferred.succeed(localPublished, event.local);
1091 + return event.remote === null
1092 + ? Effect.void
1093 + : Deferred.succeed(remotePublished, event.remote);
1094 + }),
1095 + Effect.forkScoped,
1096 + );
1097 + yield* Deferred.await(subscribed);
1098 +
1099 + const releaseRemote = yield* Deferred.make<void>();
1100 + state.beforeRemoteStatus = Deferred.await(releaseRemote);
1101 + state.currentLocalStatus = { ...baseLocalStatus, refName: "main" };
1102 + state.currentRemoteStatus = remoteStatusWithPr;
1103 + yield* broadcaster.refreshAfterCheckout("/repo");
1104 +
1105 + assert.equal((yield* Deferred.await(localPublished)).refName, "main");
1106 + assert.isFalse(yield* Deferred.isDone(remotePublished));
1107 +
1108 + yield* Deferred.succeed(releaseRemote, undefined);
1109 + assert.deepStrictEqual(yield* Deferred.await(remotePublished), remoteStatusWithPr);
1110 + assert.equal((yield* broadcaster.getStatus({ cwd: "/repo" })).pr?.number, 2978);
1111 + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1112 + });
1113 +
1114 it.effect("a remote poll refreshes Changes totals when divergence counts stay the same", () => {
1115 const state: Parameters<typeof layerTestFor>[0] = {
1116 currentLocalStatus: {
apps/server/src/vcs/VcsStatusBroadcaster.ts
+45 -16
@@ -236,6 +236,11 @@ export class VcsStatusBroadcaster extends Context.Service<
236 readonly refreshLocalStatus: (
237 cwd: string,
238 ) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
239 + /**
240 + * For a checkout someone is waiting on. Returns once the new branch is published, so the
241 + * caller's reply does not outrun it, and finishes the slower remote read in the background.
242 + */
243 + readonly refreshAfterCheckout: (cwd: string) => Effect.Effect<void>;
244 readonly refreshStatus: (
245 cwd: string,
246 options?: { readonly localOnly?: boolean },
@@ -603,6 +608,30 @@ export const make = Effect.gen(function* () {
608 );
609 });
610
611 + const refreshRemoteAndLocalTotals = Effect.fn("VcsStatusBroadcaster.refreshRemoteAndLocalTotals")(
612 + function* (cwd: string, policyCwd: string) {
613 + return yield* withRemoteWriteLock(
614 + cwd,
615 + Effect.gen(function* () {
616 + const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
617 + // Bump the PR lookup epoch after earlier remote writers have finished.
618 + yield* workflow.invalidateStatus(cwd);
619 + const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream });
620 + // Fetch can move the base used for local Changes totals.
621 + yield* refreshLocalStatusCore(cwd);
622 + // Without a fetch, the cached behind count cannot justify an automatic pull.
623 + const pulled = refreshUpstream
624 + ? yield* maybeAutoPull(cwd, remoteRead, [policyCwd])
625 + : null;
626 + if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote);
627 + yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
628 + const parts = yield* getStatusParts(cwd);
629 + return mergeGitStatusParts(parts.local, parts.remote);
630 + }),
631 + );
632 + },
633 + );
634 +
635 const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
636 "VcsStatusBroadcaster.refreshStatus",
637 )(function* (rawCwd, options) {
@@ -613,23 +642,22 @@ export const make = Effect.gen(function* () {
642 const parts = yield* getStatusParts(cwd);
643 return mergeGitStatusParts(parts.local, parts.remote);
644 }
616 - return yield* withRemoteWriteLock(
617 - cwd,
618 - Effect.gen(function* () {
619 - const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
620 - // Bump the PR lookup epoch after earlier remote writers have finished.
621 - yield* workflow.invalidateStatus(cwd);
622 - const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream });
623 - // Fetch can move the base used for local Changes totals.
624 - yield* refreshLocalStatusCore(cwd);
625 - // Without a fetch, the cached behind count cannot justify an automatic pull.
626 - const pulled = refreshUpstream ? yield* maybeAutoPull(cwd, remoteRead, [rawCwd]) : null;
627 - if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote);
628 - yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
629 - const parts = yield* getStatusParts(cwd);
630 - return mergeGitStatusParts(parts.local, parts.remote);
631 - }),
645 + return yield* refreshRemoteAndLocalTotals(cwd, rawCwd);
646 + });
647 +
648 + const refreshAfterCheckout: VcsStatusBroadcaster["Service"]["refreshAfterCheckout"] = Effect.fn(
649 + "VcsStatusBroadcaster.refreshAfterCheckout",
650 + )(function* (rawCwd) {
651 + const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
652 + const localDone = yield* Deferred.make<void>();
653 + // Owned by the broadcaster so a client disconnecting mid-switch still leaves status correct.
654 + yield* refreshLocalStatusCore(cwd).pipe(
655 + Effect.ensuring(Deferred.succeed(localDone, undefined)),
656 + Effect.andThen(refreshRemoteAndLocalTotals(cwd, rawCwd)),
657 + Effect.ignoreCause({ log: true }),
658 + Effect.forkIn(broadcasterScope),
659 );
660 + yield* Deferred.await(localDone);
661 });
662
663 const refreshPullRequestStatus: VcsStatusBroadcaster["Service"]["refreshPullRequestStatus"] =
@@ -1122,6 +1150,7 @@ export const make = Effect.gen(function* () {
1150 ),
1151 getStatus,
1152 refreshLocalStatus,
1153 + refreshAfterCheckout,
1154 refreshStatus: shareQueuedRefreshStatus,
1155 refreshPullRequestStatus,
1156 streamStatus,
apps/server/src/ws.ts
+12 -2
@@ -3172,9 +3172,19 @@ export const layerWsRpc = (
3172 ),
3173 ),
3174 [WS_METHODS.vcsCreateRef]: (input) =>
3175 - gitWorkflow.createRef(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
3175 + gitWorkflow
3176 + .createRef(input)
3177 + .pipe(
3178 + Effect.tap(() =>
3179 + input.switchRef
3180 + ? vcsStatusBroadcaster.refreshAfterCheckout(input.cwd)
3181 + : refreshGitStatus(input.cwd),
3182 + ),
3183 + ),
3184 [WS_METHODS.vcsSwitchRef]: (input) =>
3177 - gitWorkflow.switchRef(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
3185 + gitWorkflow
3186 + .switchRef(input)
3187 + .pipe(Effect.tap(() => vcsStatusBroadcaster.refreshAfterCheckout(input.cwd))),
3188 [WS_METHODS.vcsInit]: (input) =>
3189 vcsProvisioning.initRepository(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
3190 [WS_METHODS.reviewGetBranchCommits]: (input) => review.getBranchCommits(input),
apps/web/src/components/BranchToolbar.logic.test.ts
+56 -1
@@ -1,4 +1,4 @@
1 -import { ProviderInstanceId, RunId, type VcsRef } from "@t3tools/contracts";
1 +import { EnvironmentId, ProviderInstanceId, RunId, type VcsRef } from "@t3tools/contracts";
2 import { describe, expect, it } from "vite-plus/test";
3 import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
4 import {
@@ -13,6 +13,7 @@ import {
13 resolveLockedWorkspaceLabel,
14 sanitizeNewRefName,
15 shouldIncludeBranchPickerItem,
16 + isBranchHoldCurrent,
17 } from "./BranchToolbar.logic";
18
19 describe("resolveDraftEnvModeAfterBranchChange", () => {
@@ -332,6 +333,60 @@ describe("shouldIncludeBranchPickerItem", () => {
333 });
334 });
335
336 +describe("isBranchHoldCurrent", () => {
337 + const environmentId = EnvironmentId.make("env-a");
338 + const hold = {
339 + branch: "feature",
340 + environmentId,
341 + checkouts: [{ cwd: "/repo", replaces: "main" }],
342 + };
343 + const current = { canonicalBranch: "main", environmentId, cwd: "/repo" };
344 +
345 + it("keeps showing the checked-out branch while status still reports the old one", () => {
346 + expect(isBranchHoldCurrent(hold, current)).toBe(true);
347 + });
348 +
349 + it("lets go once status moves, even to a different branch than the checkout", () => {
350 + for (const canonicalBranch of ["feature", "other", null]) {
351 + expect(isBranchHoldCurrent(hold, { ...current, canonicalBranch })).toBe(false);
352 + }
353 + });
354 +
355 + it("does not apply to another checkout that happens to be on the old branch", () => {
356 + expect(isBranchHoldCurrent(hold, { ...current, cwd: "/other" })).toBe(false);
357 + });
358 +
359 + it("follows a thread moving from its worktree to the project root", () => {
360 + const moveHold = {
361 + branch: "main",
362 + environmentId,
363 + checkouts: [
364 + { cwd: "/repo-feature", replaces: "feature" },
365 + { cwd: "/repo", replaces: "dev" },
366 + ],
367 + };
368 + expect(
369 + isBranchHoldCurrent(moveHold, {
370 + environmentId,
371 + cwd: "/repo-feature",
372 + canonicalBranch: "feature",
373 + }),
374 + ).toBe(true);
375 + expect(
376 + isBranchHoldCurrent(moveHold, { environmentId, cwd: "/repo", canonicalBranch: "dev" }),
377 + ).toBe(true);
378 + expect(
379 + isBranchHoldCurrent(moveHold, { environmentId, cwd: "/repo", canonicalBranch: "main" }),
380 + ).toBe(false);
381 + });
382 +
383 + it("does not apply to the same path on another environment", () => {
384 + expect(
385 + isBranchHoldCurrent(hold, { ...current, environmentId: EnvironmentId.make("env-b") }),
386 + ).toBe(false);
387 + });
388 +});
389 +
390 describe("sanitizeNewRefName", () => {
391 it("collapses a run of whitespace into a single dash", () => {
392 expect(sanitizeNewRefName("new branch")).toBe("new-branch");
apps/web/src/components/BranchToolbar.logic.ts
+30
@@ -199,6 +199,36 @@ export function resolveBranchToolbarValue(input: {
199 return currentGitBranch ?? activeThreadBranch;
200 }
201
202 +export interface BranchHold {
203 + readonly branch: string | null;
204 + readonly environmentId: EnvironmentId;
205 + /**
206 + * Each checkout the thread can show before it catches up, with the branch its status reported
207 + * before the switch. A move from a worktree to the project root lists both.
208 + */
209 + readonly checkouts: ReadonlyArray<{ readonly cwd: string; readonly replaces: string | null }>;
210 +}
211 +
212 +/**
213 + * A finished checkout's branch stays on screen until status reports any change, because the status
214 + * stream and the RPC reply are not ordered and showing status first would flip back to the old branch.
215 + */
216 +export function isBranchHoldCurrent(
217 + hold: BranchHold,
218 + current: {
219 + readonly canonicalBranch: string | null;
220 + readonly environmentId: EnvironmentId;
221 + readonly cwd: string | null;
222 + },
223 +): boolean {
224 + return (
225 + hold.environmentId === current.environmentId &&
226 + hold.checkouts.some(
227 + (checkout) => checkout.cwd === current.cwd && checkout.replaces === current.canonicalBranch,
228 + )
229 + );
230 +}
231 +
232 /**
233 * The base a New worktree thread gets without the user picking one. Only a listed ref qualifies:
234 * during a clone the status names an unborn HEAD that no ref backs.
apps/web/src/components/BranchToolbarBranchSelector.tsx
+54 -9
@@ -45,7 +45,9 @@ import { parsePullRequestReference } from "@t3tools/client-runtime/pull-request-
45 import { getSourceControlPresentation } from "../sourceControlPresentation";
46 import { useComposerMenuProps } from "./chat/composerEventScope";
47 import {
48 + type BranchHold,
49 deriveLocalBranchNameFromRemoteRef,
50 + isBranchHoldCurrent,
51 isWorktreeChangeBlocked,
52 resolveBranchTriggerLabel,
53 resolveBranchToolbarPrBranch,
@@ -180,6 +182,7 @@ export function BranchToolbarBranchSelector({
182 branch: string | null,
183 worktreePath: string | null,
184 automatic = false,
185 + onMetadataFailure?: () => void,
186 ) => {
187 if (
188 !activeThreadId ||
@@ -216,6 +219,8 @@ export function BranchToolbarBranchSelector({
219 worktreePath,
220 ...(automatic ? { expectedEmpty: true } : {}),
221 },
222 + }).then((result) => {
223 + if (result._tag !== "Success") onMetadataFailure?.();
224 });
225 }
226 if (hasServerThread) {
@@ -326,8 +331,17 @@ export function BranchToolbarBranchSelector({
331 activeThreadBranch,
332 currentGitBranch,
333 });
334 + const [branchHold, setBranchHold] = useState<BranchHold | null>(null);
335 + const branchHoldCurrent =
336 + branchHold !== null &&
337 + isBranchHoldCurrent(branchHold, {
338 + canonicalBranch: canonicalActiveBranch,
339 + environmentId,
340 + cwd: branchCwd,
341 + });
342 + if (branchHold !== null && !branchHoldCurrent) setBranchHold(null);
343 const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
330 - canonicalActiveBranch,
344 + branchHoldCurrent ? branchHold.branch : canonicalActiveBranch,
345 (_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
346 );
347 const listedActiveBranch =
@@ -406,7 +420,6 @@ export function BranchToolbarBranchSelector({
420 startBranchActionTransition(async () => {
421 await action();
422 branchRefState.refresh();
409 - branchStatusQuery.refresh();
423 });
424 };
425
@@ -468,11 +481,37 @@ export function BranchToolbarBranchSelector({
481 const nextBranchName = refName.isRemote
482 ? (checkoutResult.value.refName ?? selectedBranchName)
483 : selectedBranchName;
471 - setOptimisticBranch(
472 - setThreadBranch(nextBranchName, selectionTarget.nextWorktreePath)
473 - ? nextBranchName
474 - : previousBranch,
484 + const movesCheckout = selectionTarget.checkoutCwd !== branchCwd;
485 + let hold: BranchHold | null = null;
486 + const applied = setThreadBranch(
487 + nextBranchName,
488 + selectionTarget.nextWorktreePath,
489 + false,
490 + // A failed move leaves the thread in its old checkout, which never had the new branch.
491 + movesCheckout
492 + ? () => setBranchHold((current) => (current === hold ? null : current))
493 + : undefined,
494 );
495 + if (applied) {
496 + hold = {
497 + branch: nextBranchName,
498 + environmentId,
499 + // The thread keeps its old checkout until the metadata update moves it to the new one.
500 + checkouts: [
501 + { cwd: branchCwd, replaces: canonicalActiveBranch },
502 + ...(movesCheckout
503 + ? [
504 + {
505 + cwd: selectionTarget.checkoutCwd,
506 + replaces: projectStatusQuery.data?.refName ?? null,
507 + },
508 + ]
509 + : []),
510 + ],
511 + };
512 + setBranchHold(hold);
513 + }
514 + setOptimisticBranch(applied ? nextBranchName : previousBranch);
515 return;
516 }
517 setOptimisticBranch(previousBranch);
@@ -509,9 +548,15 @@ export function BranchToolbarBranchSelector({
548 });
549 if (createBranchResult._tag === "Success") {
550 const nextBranchName = createBranchResult.value.refName;
512 - setOptimisticBranch(
513 - setThreadBranch(nextBranchName, activeWorktreePath) ? nextBranchName : previousBranch,
514 - );
551 + const applied = setThreadBranch(nextBranchName, activeWorktreePath);
552 + if (applied) {
553 + setBranchHold({
554 + branch: nextBranchName,
555 + environmentId,
556 + checkouts: [{ cwd: branchCwd, replaces: canonicalActiveBranch }],
557 + });
558 + }
559 + setOptimisticBranch(applied ? nextBranchName : previousBranch);
560 return;
561 }
562 setOptimisticBranch(previousBranch);