Skip to content

Commit 38b57b5

Browse files
refactor(mobile): branch checkout keys are pure, registered at start
requestKey wrote each request into a module Map and was called from render, a render-time mutation of module state. The key is now a pure, fixed-order JSON tuple of the request's fields (branchCheckoutRequestKey), and start rebuilds the request from it, so a checkout is only registered when it starts. prune keeps abandoning checkouts whose route left. The route screen test keeps the mocks only main's screen used, with a comment, so it can still run against main and fail there on the second checkout. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 6107fcf commit 38b57b5

4 files changed

Lines changed: 58 additions & 25 deletions

File tree

‎apps/mobile/src/features/threads/NewTaskDraftRouteScreen.test.tsx‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ const harness = vi.hoisted(() => {
3434
route: { key: "thread-route", name: "Thread", params: {} as object },
3535
reset: () => undefined,
3636
checkout: vi.fn(),
37-
// Hook results stay stable across renders, as the real hooks' are.
37+
// Hook results stay stable across renders, as the real hooks' are. Only
38+
// main's screen reads these (see the main-comparison mocks below).
3839
layout: { deferThreadSelectionUntil: () => undefined },
3940
navigation: { goBack: () => undefined },
4041
preventContext: { preventedRoutes: {} },
@@ -68,18 +69,23 @@ vi.mock("./new-task-flow-provider", () => ({
6869
useNewTaskFlow: () => harness,
6970
}));
7071
vi.mock("./checkout-new-task-branch", () => ({ checkoutNewTaskBranch: harness.checkout }));
72+
// Main-comparison mocks: this screen no longer uses them, but main's screen
73+
// did (deferThreadSelectionUntil, useAtomCommand, useNavigation). They stay so
74+
// this test can run against main's screen and fail there for the right reason
75+
// (a second checkout) instead of on an unmockable import.
7176
vi.mock("../layout/AdaptiveWorkspaceLayout", () => ({
7277
useAdaptiveWorkspaceLayout: () => harness.layout,
7378
}));
79+
vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => harness.checkout }));
7480
vi.mock("../../state/entities", () => ({ useProjects: () => useSnapshot().projects }));
7581
vi.mock("../../state/workspace", () => ({
7682
useWorkspaceState: () => ({ state: useSnapshot().catalog }),
7783
}));
7884
vi.mock("../../state/vcs", () => ({ vcsEnvironment: { readRefs: {}, switchRef: {} } }));
79-
vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => harness.checkout }));
8085
vi.mock("@react-navigation/native", () => ({
8186
CommonActions: { goBack: () => ({ type: "GO_BACK" }) },
8287
createNavigationContainerRef: () => ({ current: null }),
88+
// Main-comparison only, like the mocks above.
8389
useNavigation: () => harness.navigation,
8490
useRoute: () => harness.route,
8591
usePreventRemove: () => undefined,

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

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,11 @@ import { useWorkspaceState } from "../../state/workspace";
2525
import { vcsEnvironment } from "../../state/vcs";
2626
import { checkoutNewTaskBranch } from "./checkout-new-task-branch";
2727
import { resolveNewTaskBranchWorktreePath } from "./new-task-context-presentation";
28-
import { type BranchCheckoutResult, makeNewTaskBranchCheckouts } from "./new-task-branch-checkout";
28+
import {
29+
type BranchCheckoutResult,
30+
branchCheckoutRequestKey,
31+
makeNewTaskBranchCheckouts,
32+
} from "./new-task-branch-checkout";
2933
import { liveNewTaskFlowKeys, newTaskFlowKey } from "./new-task-flow-state";
3034
import { NativeStackScreenOptions } from "../../native/StackHeader";
3135

@@ -127,7 +131,7 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
127131
const flowKey = newTaskFlowKey(currentRoute);
128132
const checkoutKey =
129133
needsPreparation && initialProjectRef.branch && !waitingForProject && flowKey !== undefined
130-
? branchCheckouts.requestKey({
134+
? branchCheckoutRequestKey({
131135
flowKey,
132136
routeKey: currentRoute.key,
133137
environmentId: project?.environmentId ?? null,

‎apps/mobile/src/features/threads/new-task-branch-checkout.test.ts‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { appAtomRegistry } from "../../state/atom-registry";
66
import {
77
type BranchCheckoutRequest,
88
type BranchCheckoutResult,
9+
branchCheckoutRequestKey,
910
makeNewTaskBranchCheckouts,
1011
} from "./new-task-branch-checkout";
1112

@@ -45,7 +46,7 @@ const failure: BranchCheckoutResult = AsyncResult.failure(Cause.fail(new Error("
4546
describe("new task branch checkouts", () => {
4647
it("runs once per request even when its atom node is removed and rebuilt", async () => {
4748
const { checkouts, runs } = setup();
48-
const key = checkouts.requestKey(request("flow-a", "feature"));
49+
const key = branchCheckoutRequestKey(request("flow-a", "feature"));
4950

5051
// A render read with no subscriber, then the node is dropped before the
5152
// subscription commits, then the subscription builds a fresh node.
@@ -75,10 +76,10 @@ describe("new task branch checkouts", () => {
7576
it("serializes checkouts across routes", async () => {
7677
const { checkouts, runs } = setup();
7778
const unmountA = appAtomRegistry.mount(
78-
checkouts.atom(checkouts.requestKey(request("flow-a", "a"))),
79+
checkouts.atom(branchCheckoutRequestKey(request("flow-a", "a"))),
7980
);
8081
const unmountB = appAtomRegistry.mount(
81-
checkouts.atom(checkouts.requestKey(request("flow-b", "b"))),
82+
checkouts.atom(branchCheckoutRequestKey(request("flow-b", "b"))),
8283
);
8384
await vi.waitFor(() => expect(runs).toHaveLength(1));
8485
expect(runs[0]!.request.branch).toBe("a");
@@ -93,8 +94,8 @@ describe("new task branch checkouts", () => {
9394

9495
it("handles a failure only after the route is released, and never once it left", async () => {
9596
const { checkouts, runs, holds, onFailure } = setup();
96-
const keyA = checkouts.requestKey(request("flow-a", "a"));
97-
const keyB = checkouts.requestKey(request("flow-b", "b"));
97+
const keyA = branchCheckoutRequestKey(request("flow-a", "a"));
98+
const keyB = branchCheckoutRequestKey(request("flow-b", "b"));
9899
const unmountA = appAtomRegistry.mount(checkouts.atom(keyA));
99100
const unmountB = appAtomRegistry.mount(checkouts.atom(keyB));
100101

@@ -119,7 +120,7 @@ describe("new task branch checkouts", () => {
119120
it("stops holding navigation when its route leaves the stack", async () => {
120121
const { checkouts, runs, holds } = setup();
121122
const unmount = appAtomRegistry.mount(
122-
checkouts.atom(checkouts.requestKey(request("flow-a", "a"))),
123+
checkouts.atom(branchCheckoutRequestKey(request("flow-a", "a"))),
123124
);
124125
await vi.waitFor(() => expect(runs).toHaveLength(1));
125126
runs[0]!.settle(success("a"));

‎apps/mobile/src/features/threads/new-task-branch-checkout.ts‎

Lines changed: 37 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
22
import type { VcsRef } from "@t3tools/client-runtime/state/vcs";
3-
import type { EnvironmentId } from "@t3tools/contracts";
3+
import { EnvironmentId } from "@t3tools/contracts";
44
import * as Effect from "effect/Effect";
5+
import * as Schema from "effect/Schema";
56
import { Atom } from "effect/reactivity";
67

78
export type BranchCheckoutResult = AtomCommandResult<VcsRef, unknown>;
@@ -17,6 +18,39 @@ export interface BranchCheckoutRequest {
1718
readonly worktreePath: string | null;
1819
}
1920

21+
// The family key lists the request's fields in a fixed order, so equal
22+
// requests share one key and start can rebuild the request from it.
23+
const RequestKey = Schema.fromJsonString(
24+
Schema.Tuple([
25+
Schema.String,
26+
Schema.String,
27+
Schema.NullOr(EnvironmentId),
28+
Schema.NullOr(Schema.String),
29+
Schema.String,
30+
Schema.NullOr(Schema.String),
31+
]),
32+
);
33+
const encodeRequestKey = Schema.encodeSync(RequestKey);
34+
const decodeRequestKey = Schema.decodeSync(RequestKey);
35+
36+
/** A pure, stable key for a request: the same fields always give the same key. */
37+
export function branchCheckoutRequestKey(request: BranchCheckoutRequest): string {
38+
return encodeRequestKey([
39+
request.flowKey,
40+
request.routeKey,
41+
request.environmentId,
42+
request.workspaceRoot,
43+
request.branch,
44+
request.worktreePath,
45+
]);
46+
}
47+
48+
function requestFromKey(key: string): BranchCheckoutRequest {
49+
const [flowKey, routeKey, environmentId, workspaceRoot, branch, worktreePath] =
50+
decodeRequestKey(key);
51+
return { flowKey, routeKey, environmentId, workspaceRoot, branch, worktreePath };
52+
}
53+
2054
interface CheckoutEntry {
2155
readonly request: BranchCheckoutRequest;
2256
readonly checkout: Promise<BranchCheckoutResult>;
@@ -39,23 +73,19 @@ export function makeNewTaskBranchCheckouts(deps: {
3973
// Ignoring a stale result cannot undo its Git mutation, so checkouts run one
4074
// at a time across routes.
4175
let tail: Promise<unknown> = Promise.resolve();
76+
// Registered when a checkout starts, never from render.
4277
const entries = new Map<string, CheckoutEntry>();
43-
// The family key is the request's serialized identity; the typed request is
44-
// registered alongside it so start never has to decode the key.
45-
const requests = new Map<string, BranchCheckoutRequest>();
4678

4779
function abandon(key: string, entry: CheckoutEntry): void {
4880
entry.abandoned = true;
4981
entry.release();
5082
entries.delete(key);
51-
requests.delete(key);
5283
}
5384

5485
function start(key: string): Promise<BranchCheckoutResult> {
5586
const existing = entries.get(key);
5687
if (existing) return existing.checkout;
57-
const request = requests.get(key);
58-
if (!request) return Promise.reject(new Error(`Unknown branch checkout request: ${key}`));
88+
const request = requestFromKey(key);
5989
// A route asks for one checkout at a time; a superseded request no longer
6090
// owns the route's failure handling or holds navigation.
6191
for (const [otherKey, other] of entries) {
@@ -77,11 +107,6 @@ export function makeNewTaskBranchCheckouts(deps: {
77107
}
78108

79109
return {
80-
requestKey(request: BranchCheckoutRequest): string {
81-
const key = JSON.stringify(request);
82-
requests.set(key, request);
83-
return key;
84-
},
85110
atom: Atom.family((key: string) =>
86111
Atom.make(Effect.promise(() => start(key))).pipe(
87112
Atom.withLabel("mobile:new-task-branch-checkout"),
@@ -96,9 +121,6 @@ export function makeNewTaskBranchCheckouts(deps: {
96121
for (const [key, entry] of entries) {
97122
if (!liveFlowKeys.has(entry.request.flowKey)) abandon(key, entry);
98123
}
99-
for (const [key, request] of requests) {
100-
if (!liveFlowKeys.has(request.flowKey)) requests.delete(key);
101-
}
102124
},
103125
};
104126
}

0 commit comments

Comments
 (0)