Skip to content

Commit 604ecb6

Browse files
refactor(client): one VCS status refresh owner per checkout (#24975)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 6016969 commit 604ecb6

7 files changed

Lines changed: 212 additions & 149 deletions

‎apps/mobile/src/state/use-remote-environment-registry.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,14 @@ const remoteEnvironmentProjections = createRemoteEnvironmentProjectionAtoms({
3737
serverConfigAtom: serverEnvironment.configValueAtom,
3838
});
3939

40+
export const environmentConnectedAtom = Atom.family((environmentId: EnvironmentId) =>
41+
Atom.make(
42+
(get) =>
43+
get(remoteEnvironmentProjections.runtimeStateAtom(environmentId))?.connectionState ===
44+
"connected",
45+
).pipe(Atom.withLabel(`mobile:environment-connected:${environmentId}`)),
46+
);
47+
4048
const EMPTY_SAVED_CONNECTION_ATOM = Atom.make<SavedRemoteConnection | null>(null).pipe(
4149
Atom.withLabel("mobile:saved-connection:empty"),
4250
);

‎apps/mobile/src/state/use-selected-thread-git-actions.test.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,8 @@ const state = vi.hoisted(() => ({
2525
vi.mock("react", () => ({
2626
useCallback: (callback: unknown) => callback,
2727
useMemo: (factory: () => unknown) => factory(),
28-
useEffect: () => {},
29-
useEffectEvent: (callback: unknown) => callback,
3028
}));
29+
vi.mock("@effect/atom-react", () => ({ useAtomMount: () => {} }));
3130
vi.mock("./session", () => ({
3231
useEnvironmentScope: (environmentId: unknown, scope: string) =>
3332
(environmentId === state.thread.environmentId ? state.scopes : state.primaryScopes).has(scope),
@@ -51,7 +50,10 @@ vi.mock("./queries", () => ({
5150
}));
5251
vi.mock("./use-atom-command", () => ({ useAtomCommand: (command: unknown) => command }));
5352
vi.mock("./atom-registry", () => ({ appAtomRegistry: {} }));
54-
vi.mock("./use-remote-environment-registry", () => ({ setPendingConnectionError: () => {} }));
53+
vi.mock("./use-remote-environment-registry", () => ({
54+
environmentConnectedAtom: () => null,
55+
setPendingConnectionError: () => {},
56+
}));
5557
vi.mock("./use-vcs-action-state", () => ({
5658
showGitActionResult: (result: { type: string; description?: string }) =>
5759
state.results.push(result),

‎apps/mobile/src/state/use-selected-thread-git-actions.test.tsx‎

Lines changed: 0 additions & 113 deletions
This file was deleted.

‎apps/mobile/src/state/use-selected-thread-git-actions.ts‎

Lines changed: 32 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1-
import { useCallback, useEffect, useEffectEvent, useMemo } from "react";
1+
import { useAtomMount } from "@effect/atom-react";
2+
import { useCallback, useMemo } from "react";
23

34
import { EnvironmentProject, EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
45
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
56
import {
7+
createVcsStatusRevalidationAtomFamily,
68
type GitActionRequestInput,
79
type VcsActionOperation,
810
type VcsRef,
@@ -26,12 +28,31 @@ import { vcsActionManager, vcsEnvironment } from "../state/vcs";
2628
import { uuidv4 } from "../lib/uuid";
2729
import { appAtomRegistry } from "./atom-registry";
2830
import { readEnvironmentScope, useEnvironmentScope } from "./session";
29-
import { setPendingConnectionError } from "./use-remote-environment-registry";
31+
import {
32+
environmentConnectedAtom,
33+
setPendingConnectionError,
34+
} from "./use-remote-environment-registry";
3035
import { useAtomCommand } from "./use-atom-command";
3136
import { showGitActionResult } from "./use-vcs-action-state";
3237
import { useThreadSelection } from "./use-thread-selection";
3338
import { useSelectedThreadWorktree } from "./use-selected-thread-worktree";
3439

40+
function refreshFailureMessage(cause: Cause.Cause<unknown>): string {
41+
const error = Cause.squash(cause);
42+
return error instanceof Error ? error.message : "Failed to refresh git status.";
43+
}
44+
45+
// Selecting a thread or reconnecting its environment refreshes the checkout's
46+
// status once, shared by every sheet that shows it.
47+
const selectedThreadStatusRevalidation = createVcsStatusRevalidationAtomFamily({
48+
refreshStatus: vcsEnvironment.refreshStatus,
49+
connected: environmentConnectedAtom,
50+
onRefreshed: (result) =>
51+
setPendingConnectionError(
52+
AsyncResult.isFailure(result) ? refreshFailureMessage(result.cause) : null,
53+
),
54+
});
55+
3556
export function useSelectedThreadGitActions() {
3657
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
3758
reportFailure: false,
@@ -41,8 +62,7 @@ export function useSelectedThreadGitActions() {
4162
const createRef = useAtomCommand(vcsEnvironment.createRef, { reportFailure: false });
4263
const createWorktree = useAtomCommand(vcsEnvironment.createWorktree, { reportFailure: false });
4364
const pull = useAtomCommand(vcsEnvironment.pull, { reportFailure: false });
44-
const { selectedThread, selectedThreadProject, selectedEnvironmentRuntime } =
45-
useThreadSelection();
65+
const { selectedThread, selectedThreadProject } = useThreadSelection();
4666
const canWriteSourceControl = useEnvironmentScope(
4767
selectedThread?.environmentId ?? null,
4868
AuthSourceControlWriteScope,
@@ -130,9 +150,7 @@ export function useSelectedThreadGitActions() {
130150
execute,
131151
);
132152
if (AsyncResult.isFailure(result)) {
133-
const error = Cause.squash(result.cause);
134-
const message = error instanceof Error ? error.message : "Failed to refresh git status.";
135-
setPendingConnectionError(message);
153+
setPendingConnectionError(refreshFailureMessage(result.cause));
136154
return null;
137155
}
138156
setPendingConnectionError(null);
@@ -141,32 +159,13 @@ export function useSelectedThreadGitActions() {
141159
[refreshStatus, selectedThread, selectedThreadCwd, selectedThreadProject],
142160
);
143161

144-
// Key refreshes on primitives; streaming frequently replaces the selected thread object.
145-
const selectedEnvironmentId = selectedThread?.environmentId ?? null;
146-
const selectedThreadId = selectedThread?.id ?? null;
147-
const hasSelectedThreadProject = selectedThreadProject !== null;
148-
const isEnvironmentConnected = selectedEnvironmentRuntime?.connectionState === "connected";
149-
const refreshOnSelection = useEffectEvent(() => {
150-
void refreshSelectedThreadGitStatus({ quiet: true });
151-
});
152-
useEffect(() => {
153-
if (
154-
selectedEnvironmentId === null ||
155-
selectedThreadId === null ||
156-
!hasSelectedThreadProject ||
157-
selectedThreadCwd === null ||
158-
!isEnvironmentConnected
159-
) {
160-
return;
161-
}
162-
refreshOnSelection();
163-
}, [
164-
selectedEnvironmentId,
165-
selectedThreadId,
166-
hasSelectedThreadProject,
167-
selectedThreadCwd,
168-
isEnvironmentConnected,
169-
]);
162+
useAtomMount(
163+
selectedThreadStatusRevalidation(
164+
selectedThread && selectedThreadProject && selectedThreadCwd
165+
? { environmentId: selectedThread.environmentId, cwd: selectedThreadCwd }
166+
: null,
167+
),
168+
);
170169

171170
const runSelectedThreadGitMutation = useCallback(
172171
async <T, E>(

‎packages/client-runtime/src/state/vcs.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,3 +360,4 @@ export function createVcsEnvironmentAtoms<R, E>(
360360
export * from "./gitActions.ts";
361361
export * from "./vcsAction.ts";
362362
export * from "./vcsRef.ts";
363+
export * from "./vcsStatusRevalidation.ts";
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
import { EnvironmentId } from "@t3tools/contracts";
2+
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
3+
import { describe, expect, it, vi } from "vite-plus/test";
4+
5+
import { createVcsStatusRevalidationAtomFamily } from "./vcsStatusRevalidation.ts";
6+
7+
const environmentId = EnvironmentId.make("environment-1");
8+
9+
function setup(options: { readonly connected?: boolean; readonly wake?: boolean }) {
10+
const connectedAtom = Atom.make(options.connected ?? false);
11+
const wakes = new Set<() => void>();
12+
const run = vi.fn(async () => AsyncResult.success(null));
13+
const family = createVcsStatusRevalidationAtomFamily({
14+
refreshStatus: { label: "refresh-status", run },
15+
...(options.connected === undefined ? {} : { connected: () => connectedAtom }),
16+
...(options.wake
17+
? {
18+
subscribeWake: (wake: () => void) => {
19+
wakes.add(wake);
20+
return () => wakes.delete(wake);
21+
},
22+
wakeDebounceMs: 250,
23+
}
24+
: {}),
25+
});
26+
const registry = AtomRegistry.make();
27+
const wake = () => {
28+
for (const listener of wakes) listener();
29+
};
30+
return { registry, family, connectedAtom, run, wakes, wake };
31+
}
32+
33+
describe("createVcsStatusRevalidationAtomFamily", () => {
34+
it("refreshes once per connection, shared by every subscriber, and again on reconnect", () => {
35+
const { registry, family, connectedAtom, run } = setup({ connected: true });
36+
const target = { environmentId, cwd: "/repo" };
37+
const first = registry.mount(family(target));
38+
const second = registry.mount(family({ environmentId, cwd: "/repo" }));
39+
expect(run).toHaveBeenCalledTimes(1);
40+
expect(run).toHaveBeenCalledWith(expect.anything(), { environmentId, input: { cwd: "/repo" } });
41+
42+
registry.set(connectedAtom, false);
43+
expect(run).toHaveBeenCalledTimes(1);
44+
registry.set(connectedAtom, true);
45+
expect(run).toHaveBeenCalledTimes(2);
46+
47+
registry.mount(family({ environmentId, cwd: "/other" }))();
48+
expect(run).toHaveBeenCalledTimes(3);
49+
first();
50+
second();
51+
});
52+
53+
it("waits for the connection before the first refresh", () => {
54+
const { registry, family, connectedAtom, run } = setup({ connected: false });
55+
const unmount = registry.mount(family({ environmentId, cwd: "/repo" }));
56+
expect(run).not.toHaveBeenCalled();
57+
registry.set(connectedAtom, true);
58+
expect(run).toHaveBeenCalledTimes(1);
59+
unmount();
60+
});
61+
62+
it("debounces wake signals and stops listening with the last subscriber", () => {
63+
vi.useFakeTimers();
64+
try {
65+
const { registry, family, run, wakes, wake } = setup({ wake: true });
66+
const unmount = registry.mount(family({ environmentId, cwd: "/repo" }));
67+
expect(run).not.toHaveBeenCalled();
68+
69+
wake();
70+
vi.advanceTimersByTime(100);
71+
wake();
72+
vi.advanceTimersByTime(249);
73+
expect(run).not.toHaveBeenCalled();
74+
vi.advanceTimersByTime(1);
75+
expect(run).toHaveBeenCalledTimes(1);
76+
77+
wake();
78+
unmount();
79+
vi.runAllTimers();
80+
expect(run).toHaveBeenCalledTimes(1);
81+
expect(wakes.size).toBe(0);
82+
} finally {
83+
vi.useRealTimers();
84+
}
85+
});
86+
87+
it("does nothing for an idle target", () => {
88+
const { registry, family, run, wakes } = setup({ connected: true, wake: true });
89+
registry.mount(family(null))();
90+
expect(run).not.toHaveBeenCalled();
91+
expect(wakes.size).toBe(0);
92+
});
93+
});

0 commit comments

Comments
 (0)