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 22, 17:00 UTC
refactor(client): one VCS status refresh owner per checkout (#24975)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 25, 2026 at 15:27 UTC
604ecb6d9a5c666928f9bbfdd8cb5b75bf462d88
7 files changed
+212
-149
apps/mobile/src/state/use-remote-environment-registry.ts
+8
@@ -37,6 +37,14 @@ const remoteEnvironmentProjections = createRemoteEnvironmentProjectionAtoms({
37
serverConfigAtom: serverEnvironment.configValueAtom,
38
});
39
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
+
48
const EMPTY_SAVED_CONNECTION_ATOM = Atom.make<SavedRemoteConnection | null>(null).pipe(
49
Atom.withLabel("mobile:saved-connection:empty"),
50
);
apps/mobile/src/state/use-selected-thread-git-actions.test.ts
+5
-3
@@ -25,9 +25,8 @@ const state = vi.hoisted(() => ({
25
vi.mock("react", () => ({
26
useCallback: (callback: unknown) => callback,
27
useMemo: (factory: () => unknown) => factory(),
28
- useEffect: () => {},
29
- useEffectEvent: (callback: unknown) => callback,
28
}));
29
+vi.mock("@effect/atom-react", () => ({ useAtomMount: () => {} }));
30
vi.mock("./session", () => ({
31
useEnvironmentScope: (environmentId: unknown, scope: string) =>
32
(environmentId === state.thread.environmentId ? state.scopes : state.primaryScopes).has(scope),
@@ -51,7 +50,10 @@ vi.mock("./queries", () => ({
50
}));
51
vi.mock("./use-atom-command", () => ({ useAtomCommand: (command: unknown) => command }));
52
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
+}));
57
vi.mock("./use-vcs-action-state", () => ({
58
showGitActionResult: (result: { type: string; description?: string }) =>
59
state.results.push(result),
apps/mobile/src/state/use-selected-thread-git-actions.test.tsx
deleted
-113
@@ -1,113 +0,0 @@
1
-import { act, useEffect, useReducer } from "react";
2
-import { createRoot, type Root } from "react-dom/client";
3
-import { AsyncResult } from "effect/reactivity";
4
-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5
-
6
-const harness = vi.hoisted(() => ({
7
- selection: {
8
- selectedThread: { environmentId: "environment-1", id: "thread-1" } as unknown,
9
- selectedThreadProject: { workspaceRoot: "/repo" } as unknown,
10
- selectedEnvironmentRuntime: { connectionState: "connected" } as unknown,
11
- },
12
- worktree: { selectedThreadCwd: "/repo" as string | null, selectedThreadWorktreePath: null },
13
- refreshStatusCalls: [] as Array<unknown>,
14
- renderCount: 0,
15
- onRefreshSettled: () => {},
16
-}));
17
-
18
-vi.mock("./use-atom-command", () => ({
19
- useAtomCommand: (command: unknown) =>
20
- command === "refreshStatus"
21
- ? async (input: unknown) => {
22
- harness.refreshStatusCalls.push(input);
23
- harness.onRefreshSettled();
24
- return AsyncResult.success({});
25
- }
26
- : async () => AsyncResult.success({}),
27
-}));
28
-vi.mock("./vcs", () => ({
29
- vcsEnvironment: { refreshStatus: "refreshStatus" },
30
- vcsActionManager: { runStackedAction: () => "runStackedAction", track: vi.fn() },
31
-}));
32
-vi.mock("./threads", () => ({ threadEnvironment: { updateMetadata: "updateMetadata" } }));
33
-vi.mock("./queries", () => ({ useBranches: () => ({ data: null, refresh: () => {} }) }));
34
-vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid" }));
35
-vi.mock("./atom-registry", () => ({ appAtomRegistry: {} }));
36
-vi.mock("./session", () => ({
37
- readEnvironmentScope: () => true,
38
- useEnvironmentScope: () => true,
39
-}));
40
-vi.mock("./use-remote-environment-registry", () => ({ setPendingConnectionError: () => {} }));
41
-vi.mock("./use-vcs-action-state", () => ({ showGitActionResult: () => {} }));
42
-vi.mock("./use-thread-selection", () => ({
43
- useThreadSelection: () => {
44
- harness.renderCount += 1;
45
- if (harness.renderCount > 50) {
46
- throw new Error("Consumer rerendered more than 50 times");
47
- }
48
- return harness.selection;
49
- },
50
-}));
51
-vi.mock("./use-selected-thread-worktree", () => ({
52
- useSelectedThreadWorktree: () => harness.worktree,
53
-}));
54
-
55
-import { useSelectedThreadGitActions } from "./use-selected-thread-git-actions";
56
-
57
-let root: Root | null = null;
58
-let rerender: () => void = () => {};
59
-
60
-function Consumer() {
61
- const [, bump] = useReducer((count: number) => count + 1, 0);
62
- useEffect(() => {
63
- rerender = bump;
64
- });
65
- useSelectedThreadGitActions();
66
- return null;
67
-}
68
-
69
-async function flush() {
70
- for (let index = 0; index < 5; index += 1) {
71
- await act(async () => {
72
- await Promise.resolve();
73
- });
74
- }
75
-}
76
-
77
-beforeEach(() => {
78
- (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
79
- harness.selection = {
80
- selectedThread: { environmentId: "environment-1", id: "thread-1" },
81
- selectedThreadProject: { workspaceRoot: "/repo" },
82
- selectedEnvironmentRuntime: { connectionState: "connected" },
83
- };
84
- harness.worktree = { selectedThreadCwd: "/repo", selectedThreadWorktreePath: null };
85
- harness.refreshStatusCalls = [];
86
- harness.renderCount = 0;
87
- harness.onRefreshSettled = () => rerender();
88
-});
89
-
90
-afterEach(() => {
91
- act(() => root?.unmount());
92
- root = null;
93
-});
94
-
95
-describe("useSelectedThreadGitActions", () => {
96
- it("refreshes once on mount and does not loop when refreshes rerender the consumer", async () => {
97
- root = createRoot(document.createElement("div"));
98
- act(() => root!.render(<Consumer />));
99
- await flush();
100
-
101
- harness.selection = {
102
- selectedThread: { environmentId: "environment-1", id: "thread-1" },
103
- selectedThreadProject: { workspaceRoot: "/repo" },
104
- selectedEnvironmentRuntime: { connectionState: "connected" },
105
- };
106
- act(() => rerender());
107
- await flush();
108
-
109
- expect(harness.refreshStatusCalls).toEqual([
110
- { environmentId: "environment-1", input: { cwd: "/repo" } },
111
- ]);
112
- });
113
-});
apps/mobile/src/state/use-selected-thread-git-actions.ts
+32
-33
@@ -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";
3
4
import { EnvironmentProject, EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
5
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
6
import {
7
+ createVcsStatusRevalidationAtomFamily,
8
type GitActionRequestInput,
9
type VcsActionOperation,
10
type VcsRef,
@@ -26,12 +28,31 @@ import { vcsActionManager, vcsEnvironment } from "../state/vcs";
28
import { uuidv4 } from "../lib/uuid";
29
import { appAtomRegistry } from "./atom-registry";
30
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";
35
import { useAtomCommand } from "./use-atom-command";
36
import { showGitActionResult } from "./use-vcs-action-state";
37
import { useThreadSelection } from "./use-thread-selection";
38
import { useSelectedThreadWorktree } from "./use-selected-thread-worktree";
39
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
+
56
export function useSelectedThreadGitActions() {
57
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
58
reportFailure: false,
@@ -41,8 +62,7 @@ export function useSelectedThreadGitActions() {
62
const createRef = useAtomCommand(vcsEnvironment.createRef, { reportFailure: false });
63
const createWorktree = useAtomCommand(vcsEnvironment.createWorktree, { reportFailure: false });
64
const pull = useAtomCommand(vcsEnvironment.pull, { reportFailure: false });
44
- const { selectedThread, selectedThreadProject, selectedEnvironmentRuntime } =
45
- useThreadSelection();
65
+ const { selectedThread, selectedThreadProject } = useThreadSelection();
66
const canWriteSourceControl = useEnvironmentScope(
67
selectedThread?.environmentId ?? null,
68
AuthSourceControlWriteScope,
@@ -130,9 +150,7 @@ export function useSelectedThreadGitActions() {
150
execute,
151
);
152
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));
154
return null;
155
}
156
setPendingConnectionError(null);
@@ -141,32 +159,13 @@ export function useSelectedThreadGitActions() {
159
[refreshStatus, selectedThread, selectedThreadCwd, selectedThreadProject],
160
);
161
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
+ );
169
170
const runSelectedThreadGitMutation = useCallback(
171
async <T, E>(
packages/client-runtime/src/state/vcs.ts
+1
@@ -360,3 +360,4 @@ export function createVcsEnvironmentAtoms<R, E>(
360
export * from "./gitActions.ts";
361
export * from "./vcsAction.ts";
362
export * from "./vcsRef.ts";
363
+export * from "./vcsStatusRevalidation.ts";
packages/client-runtime/src/state/vcsStatusRevalidation.test.ts
new
+93
@@ -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
+});
packages/client-runtime/src/state/vcsStatusRevalidation.ts
new
+73
@@ -0,0 +1,73 @@
1
+// @effect-diagnostics globalTimers:off - The wake debounce runs in an atom subscription, outside an Effect runtime.
2
+import type { EnvironmentId } from "@t3tools/contracts";
3
+import { Atom, type AtomRegistry } from "effect/reactivity";
4
+
5
+import { type AtomCommand, type AtomCommandResult, runAtomCommand } from "./runtime.ts";
6
+
7
+interface VcsStatusRevalidationTarget {
8
+ readonly environmentId: EnvironmentId;
9
+ readonly cwd: string;
10
+}
11
+
12
+/**
13
+ * One atom per environment and cwd that refreshes VCS status while mounted and
14
+ * shared by every subscriber. Refreshes only when `connected` is given and true
15
+ * (on mount and on each reconnect), and on `subscribeWake` (debounced); the wake
16
+ * subscription and timer end with the last subscriber.
17
+ */
18
+export function createVcsStatusRevalidationAtomFamily<R>(input: {
19
+ readonly refreshStatus: AtomCommand<
20
+ { readonly environmentId: EnvironmentId; readonly input: { readonly cwd: string } },
21
+ R,
22
+ unknown
23
+ >;
24
+ readonly connected?: (environmentId: EnvironmentId) => Atom.Atom<boolean>;
25
+ readonly subscribeWake?: (wake: () => void) => () => void;
26
+ readonly wakeDebounceMs?: number;
27
+ readonly onRefreshed?: (result: AtomCommandResult<R, unknown>) => void;
28
+}) {
29
+ const family = Atom.family((target: VcsStatusRevalidationTarget) => {
30
+ const { environmentId, cwd } = target;
31
+ const key = `${environmentId}:${cwd}`;
32
+
33
+ const refresh = async (registry: AtomRegistry.AtomRegistry) => {
34
+ const result = await runAtomCommand(
35
+ registry,
36
+ input.refreshStatus,
37
+ { environmentId, input: { cwd } },
38
+ { reportFailure: false },
39
+ );
40
+ input.onRefreshed?.(result);
41
+ };
42
+
43
+ const wakeAtom = Atom.make((get) => {
44
+ const subscribeWake = input.subscribeWake;
45
+ if (subscribeWake === undefined) return;
46
+ const registry = get.registry;
47
+ let timer: ReturnType<typeof setTimeout> | undefined;
48
+ const unsubscribe = subscribeWake(() => {
49
+ if (timer !== undefined) clearTimeout(timer);
50
+ timer = setTimeout(() => {
51
+ timer = undefined;
52
+ void refresh(registry);
53
+ }, input.wakeDebounceMs ?? 0);
54
+ });
55
+ get.addFinalizer(() => {
56
+ if (timer !== undefined) clearTimeout(timer);
57
+ unsubscribe();
58
+ });
59
+ }).pipe(Atom.withLabel(`vcs-status-revalidation:wake:${key}`));
60
+
61
+ return Atom.make((get) => {
62
+ get(wakeAtom);
63
+ const connected = input.connected;
64
+ // Rebuilds only when the connection flag flips, so each reconnect refreshes once.
65
+ if (connected !== undefined && get(connected(environmentId))) {
66
+ void refresh(get.registry);
67
+ }
68
+ }).pipe(Atom.withLabel(`vcs-status-revalidation:${key}`));
69
+ });
70
+ const idle = Atom.make<void>(undefined).pipe(Atom.withLabel("vcs-status-revalidation:idle"));
71
+ return (target: VcsStatusRevalidationTarget | null): Atom.Atom<void> =>
72
+ target === null ? idle : family({ environmentId: target.environmentId, cwd: target.cwd });
73
+}