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,mobile): Linked environments shows links made outside the app (#28907)
Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>
Nabil Belahouane committed
Nov 14, 2026 at 08:53 UTC
12102c74a323c67bcbec189ae23dc50c62740895
5 files changed
+333
-3
apps/mobile/src/features/connection/LinkedEnvironmentsSection.test.tsx
new
+169
@@ -0,0 +1,169 @@
1
+import { RegistryContext } from "@effect/atom-react";
2
+import {
3
+ NavigationContext,
4
+ type NavigationProp,
5
+ type ParamListBase,
6
+} from "@react-navigation/native";
7
+import { EnvironmentId } from "@t3tools/contracts";
8
+import { AtomRegistry } from "effect/reactivity";
9
+import { act, type ReactNode } from "react";
10
+import { createRoot } from "react-dom/client";
11
+import { expect, it, vi } from "vite-plus/test";
12
+
13
+// Each listing probes every linked machine, so the test counts the fetches it starts and cuts.
14
+const fetches = vi.hoisted(() => ({
15
+ started: 0,
16
+ interrupted: 0,
17
+ gate: Promise.resolve(),
18
+ open: () => {},
19
+}));
20
+
21
+vi.mock("@react-navigation/native", async () => {
22
+ const { createRequire } = await import("node:module");
23
+ const { realpathSync } = await import("node:fs");
24
+ const require = createRequire(import.meta.url);
25
+ const nativeRequire = createRequire(
26
+ realpathSync(require.resolve("@react-navigation/native/package.json")),
27
+ );
28
+ // Use the shipped focus hook without importing the React Native view layer.
29
+ const { NavigationContext, useFocusEffect }: typeof import("@react-navigation/native") =
30
+ nativeRequire("@react-navigation/core");
31
+ return { NavigationContext, useFocusEffect };
32
+});
33
+const appState = vi.hoisted(() => ({ listeners: new Set<(state: string) => void>() }));
34
+
35
+vi.mock("react-native", () => ({
36
+ AppState: {
37
+ addEventListener: (_event: "change", listener: (state: string) => void) => {
38
+ appState.listeners.add(listener);
39
+ return { remove: () => appState.listeners.delete(listener) };
40
+ },
41
+ },
42
+ View: ({ children }: { children?: ReactNode }) => children,
43
+}));
44
+vi.mock("../../components/ui/AppText", () => ({
45
+ AppText: ({ children }: { children?: ReactNode }) => children,
46
+}));
47
+vi.mock("../settings/components/SettingsSection", () => ({
48
+ SettingsSection: ({ children }: { children?: ReactNode }) => children,
49
+}));
50
+vi.mock("../../state/entities", () => ({
51
+ useEnvironmentServerConfig: () => ({
52
+ environment: { capabilities: { peerLinks: true } },
53
+ settings: { linkedEnvironmentsEnabled: true },
54
+ }),
55
+}));
56
+vi.mock("../../state/session", () => ({ useEnvironmentScope: () => true }));
57
+vi.mock("../../state/peerLinks", async () => {
58
+ const { Atom } = await import("effect/reactivity");
59
+ const EffectModule = await import("effect/Effect");
60
+ // Waits for the gate, as a list waits on its slowest linked machine.
61
+ const list = Atom.make(
62
+ EffectModule.gen(function* () {
63
+ fetches.started += 1;
64
+ yield* EffectModule.promise(() => fetches.gate);
65
+ return { links: [] };
66
+ }).pipe(
67
+ EffectModule.onInterrupt(() =>
68
+ EffectModule.sync(() => {
69
+ fetches.interrupted += 1;
70
+ }),
71
+ ),
72
+ ),
73
+ );
74
+ return { peerLinkEnvironment: { list: () => list } };
75
+});
76
+
77
+import { LinkedEnvironmentsSection } from "./LinkedEnvironmentsSection";
78
+
79
+function createNavigation() {
80
+ const listeners = { focus: new Set<() => void>(), blur: new Set<() => void>() };
81
+ let focused = true;
82
+ return {
83
+ value: {
84
+ isFocused: () => focused,
85
+ addListener: (event: keyof typeof listeners, listener: () => void) => {
86
+ listeners[event].add(listener);
87
+ return () => listeners[event].delete(listener);
88
+ },
89
+ } as unknown as NavigationProp<ParamListBase>,
90
+ focus(next: boolean) {
91
+ focused = next;
92
+ act(() => {
93
+ for (const listener of listeners[next ? "focus" : "blur"]) listener();
94
+ });
95
+ },
96
+ };
97
+}
98
+
99
+function setup() {
100
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
101
+ fetches.started = 0;
102
+ fetches.interrupted = 0;
103
+ fetches.gate = new Promise((resolve) => {
104
+ fetches.open = resolve;
105
+ });
106
+ const registry = AtomRegistry.make();
107
+ const root = createRoot(document.createElement("div"));
108
+ const navigation = createNavigation();
109
+ act(() =>
110
+ root.render(
111
+ <RegistryContext.Provider value={registry}>
112
+ <NavigationContext.Provider value={navigation.value}>
113
+ <LinkedEnvironmentsSection
114
+ environmentId={EnvironmentId.make("mac")}
115
+ environmentLabel="Mac"
116
+ />
117
+ </NavigationContext.Provider>
118
+ </RegistryContext.Provider>,
119
+ ),
120
+ );
121
+ return {
122
+ focus: navigation.focus,
123
+ moveApp: (state: "active" | "background") =>
124
+ act(() => {
125
+ for (const listener of appState.listeners) listener(state);
126
+ }),
127
+ settle: () =>
128
+ act(async () => {
129
+ fetches.open();
130
+ await fetches.gate;
131
+ }),
132
+ [Symbol.dispose]() {
133
+ act(() => root.unmount());
134
+ registry.dispose();
135
+ },
136
+ };
137
+}
138
+
139
+it("asks again on focus only once the list it is waiting for has answered", async () => {
140
+ using screen = setup();
141
+ // The first focus comes while the first fetch runs, which must not be cut and restarted.
142
+ expect(fetches).toMatchObject({ started: 1, interrupted: 0 });
143
+ screen.focus(false);
144
+ screen.focus(true);
145
+ expect(fetches).toMatchObject({ started: 1, interrupted: 0 });
146
+
147
+ await screen.settle();
148
+ screen.focus(false);
149
+ screen.focus(true);
150
+ expect(fetches).toMatchObject({ started: 2, interrupted: 0 });
151
+});
152
+
153
+it("asks again when the app comes back to the front on this screen", async () => {
154
+ using screen = setup();
155
+ await screen.settle();
156
+ expect(fetches).toMatchObject({ started: 1, interrupted: 0 });
157
+ fetches.gate = new Promise((resolve) => {
158
+ fetches.open = resolve;
159
+ });
160
+
161
+ screen.moveApp("background");
162
+ screen.moveApp("active");
163
+ expect(fetches).toMatchObject({ started: 2, interrupted: 0 });
164
+
165
+ // Coming back while that answer is still out must not cut it and start again.
166
+ screen.moveApp("background");
167
+ screen.moveApp("active");
168
+ expect(fetches).toMatchObject({ started: 2, interrupted: 0 });
169
+});
apps/mobile/src/features/connection/LinkedEnvironmentsSection.tsx
+21
-3
@@ -1,9 +1,10 @@
1
+import { RegistryContext } from "@effect/atom-react";
2
import { offersLinkedEnvironments } from "@t3tools/client-runtime/link-request";
3
import { peerLinkHealth } from "@t3tools/client-runtime/state/peerLinks";
4
import { useFocusEffect } from "@react-navigation/native";
5
import { AuthAccessReadScope, type EnvironmentId } from "@t3tools/contracts";
6
import * as DateTime from "effect/DateTime";
6
-import { useCallback, useState } from "react";
7
+import { useCallback, useContext, useState } from "react";
8
import { AppState, View } from "react-native";
9
10
import { AppText as Text } from "../../components/ui/AppText";
@@ -20,8 +21,25 @@ export function LinkedEnvironmentsSection(props: {
21
const config = useEnvironmentServerConfig(props.environmentId);
22
const canRead = useEnvironmentScope(props.environmentId, AuthAccessReadScope);
23
const supported = canRead && offersLinkedEnvironments(config);
23
- const links = useEnvironmentQuery(
24
- supported ? peerLinkEnvironment.list({ environmentId: props.environmentId, input: {} }) : null,
24
+ const listAtom = supported
25
+ ? peerLinkEnvironment.list({ environmentId: props.environmentId, input: {} })
26
+ : null;
27
+ const links = useEnvironmentQuery(listAtom);
28
+ const registry = useContext(RegistryContext);
29
+ // Links change outside this client, and the shared list only revalidates when built, so
30
+ // showing the screen and bringing the app back ask again.
31
+ useFocusEffect(
32
+ useCallback(() => {
33
+ if (listAtom === null) return;
34
+ const askAgain = () => {
35
+ if (!registry.get(listAtom).waiting) registry.refresh(listAtom);
36
+ };
37
+ askAgain();
38
+ const subscription = AppState.addEventListener("change", (state) => {
39
+ if (state === "active") askAgain();
40
+ });
41
+ return () => subscription.remove();
42
+ }, [listAtom, registry]),
43
);
44
const [nowMs, setNowMs] = useState(Date.now);
45
const hasLinks = supported && (links.data?.links.length ?? 0) > 0;
apps/mobile/vite.config.ts
+1
@@ -47,6 +47,7 @@ const reactTests = [
47
"src/features/home/home-route-visibility.test.tsx",
48
"src/features/layout/workspace/useSearchScrollRestoration.test.tsx",
49
"src/features/connection/ConnectionsNewRouteScreen.test.tsx",
50
+ "src/features/connection/LinkedEnvironmentsSection.test.tsx",
51
"src/features/devices/device-stream.browser.test.ts",
52
"src/features/keyboard/keyboardControllerState.test.tsx",
53
];
apps/web/src/components/settings/LinkedEnvironmentsSettings.browser.test.tsx
new
+128
@@ -0,0 +1,128 @@
1
+import { RegistryContext, useAtomValue } from "@effect/atom-react";
2
+import { EnvironmentId, type PeerLinkSummary } from "@t3tools/contracts";
3
+import * as DateTime from "effect/DateTime";
4
+import { AsyncResult, AtomRegistry } from "effect/reactivity";
5
+import { describe, expect, it, vi } from "vite-plus/test";
6
+
7
+import "~/index.css";
8
+import { peerLinkEnvironment } from "~/state/peerLinks";
9
+import { render } from "../../../test/render";
10
+import { LinkedEnvironmentsSettings } from "./LinkedEnvironmentsSettings";
11
+
12
+const hostId = EnvironmentId.make("mac");
13
+const vmLink: PeerLinkSummary = {
14
+ environmentId: EnvironmentId.make("vm"),
15
+ label: "boat-task",
16
+ urls: ["http://boat-task.example.ts.net:3773"],
17
+ access: "full-access",
18
+ linkedAt: DateTime.makeUnsafe("2026-11-01T00:00:00.000Z"),
19
+ expiresAt: DateTime.makeUnsafe("2099-01-01T00:00:00.000Z"),
20
+ lastReachedAt: null,
21
+ lastError: null,
22
+ status: "reachable",
23
+};
24
+
25
+// What the host's `peerLinks.list` answers. The CLI and agents link machines without this client.
26
+const server = vi.hoisted(() => ({
27
+ links: [] as Array<PeerLinkSummary>,
28
+ started: 0,
29
+ interrupted: 0,
30
+ answer: Promise.resolve(),
31
+}));
32
+
33
+function setup() {
34
+ server.links = [];
35
+ server.started = 0;
36
+ server.interrupted = 0;
37
+ server.answer = Promise.resolve();
38
+}
39
+
40
+vi.mock(import("~/state/peerLinks"), async (original) => {
41
+ const actual = await original();
42
+ const { Atom: AtomModule } = await import("effect/reactivity");
43
+ const EffectModule = await import("effect/Effect");
44
+ // The real list query's options: stale-while-revalidate, revalidating only when it is built.
45
+ const list = AtomModule.make(
46
+ EffectModule.gen(function* () {
47
+ server.started += 1;
48
+ yield* EffectModule.promise(() => server.answer);
49
+ return { links: [...server.links] };
50
+ }).pipe(
51
+ EffectModule.onInterrupt(() =>
52
+ EffectModule.sync(() => {
53
+ server.interrupted += 1;
54
+ }),
55
+ ),
56
+ ),
57
+ ).pipe(AtomModule.swr({ staleTime: 10_000, revalidateOnMount: true }));
58
+ const denied = AtomModule.make(false);
59
+ return {
60
+ ...actual,
61
+ peerLinkEnvironment: {
62
+ ...actual.peerLinkEnvironment,
63
+ list: (() => list) as never,
64
+ link: { ...actual.peerLinkEnvironment.link, permissionAtom: () => denied },
65
+ unlink: { ...actual.peerLinkEnvironment.unlink, permissionAtom: () => denied },
66
+ },
67
+ };
68
+});
69
+
70
+/** Stands in for the chat composer, which reads the same list while a thread is open. */
71
+function ComposerReader() {
72
+ const result = useAtomValue(peerLinkEnvironment.list({ environmentId: hostId, input: {} }));
73
+ return AsyncResult.isSuccess(result) ? <p>Composer loaded</p> : null;
74
+}
75
+
76
+describe("LinkedEnvironmentsSettings", () => {
77
+ it("shows a link made elsewhere while the composer keeps the list loaded", async () => {
78
+ setup();
79
+ const registry = AtomRegistry.make();
80
+ using _registry = { [Symbol.dispose]: () => registry.dispose() };
81
+ await using composer = await render(
82
+ <RegistryContext.Provider value={registry}>
83
+ <ComposerReader />
84
+ </RegistryContext.Provider>,
85
+ );
86
+ await expect.element(composer.getByText("Composer loaded")).toBeVisible();
87
+
88
+ server.links = [vmLink];
89
+ await using screen = await render(
90
+ <RegistryContext.Provider value={registry}>
91
+ <LinkedEnvironmentsSettings
92
+ environmentId={hostId}
93
+ environmentLabel={null}
94
+ isSearchTarget={false}
95
+ />
96
+ </RegistryContext.Provider>,
97
+ );
98
+
99
+ await expect.element(screen.getByRole("heading", { name: "boat-task" })).toBeVisible();
100
+ });
101
+
102
+ it("leaves a list that is still loading to answer", async () => {
103
+ setup();
104
+ // useLiveRefresh remembers each view's last read across mounts, so this view gets its own host.
105
+ const loadingHostId = EnvironmentId.make("mac-loading");
106
+ let answer = () => {};
107
+ server.answer = new Promise((resolve) => {
108
+ answer = resolve;
109
+ });
110
+ server.links = [vmLink];
111
+ const registry = AtomRegistry.make();
112
+ using _registry = { [Symbol.dispose]: () => registry.dispose() };
113
+ await using screen = await render(
114
+ <RegistryContext.Provider value={registry}>
115
+ <LinkedEnvironmentsSettings
116
+ environmentId={loadingHostId}
117
+ environmentLabel={null}
118
+ isSearchTarget={false}
119
+ />
120
+ </RegistryContext.Provider>,
121
+ );
122
+ await expect.element(screen.getByRole("status")).toBeVisible();
123
+
124
+ answer();
125
+ await expect.element(screen.getByRole("heading", { name: "boat-task" })).toBeVisible();
126
+ expect(server).toMatchObject({ started: 1, interrupted: 0 });
127
+ });
128
+});
apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx
+14
@@ -43,6 +43,7 @@ import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
43
import { LinkAccessPicker } from "./LinkAccessPicker";
44
import { LinkAddressWarning, LinkMachineSelect } from "./LinkMachineSelect";
45
import { SettingsRow, SettingsSection } from "./settingsLayout";
46
+import { useLiveRefresh } from "../../hooks/useLiveRefresh";
47
import { useNowMinute } from "../../hooks/useNowMinute";
48
import { searchableSetting } from "./settingsSearch";
49
@@ -59,6 +60,19 @@ export function LinkedEnvironmentsSettings({
60
readonly isSearchTarget: boolean;
61
}) {
62
const links = useEnvironmentQuery(peerLinkEnvironment.list({ environmentId, input: {} }));
63
+ // Links made outside this client bump nothing the shared list reads, so showing the panel
64
+ // asks again. Listing probes every linked environment, too costly for a timer nobody asked for.
65
+ // A list still loading counts as read now, so the next return to the window asks again.
66
+ useLiveRefresh(
67
+ () => {
68
+ if (!links.isPending) links.refresh();
69
+ },
70
+ {
71
+ key: `linked-environments:${environmentId}`,
72
+ intervalMs: null,
73
+ refreshOnShow: true,
74
+ },
75
+ );
76
const canLink = useAtomValue(peerLinkEnvironment.link.permissionAtom(environmentId));
77
const search = searchableSetting("linked-environments");
78
return (