Skip to content

Commit 2d67e12

Browse files
Merge remote-tracking branch 'origin/main' into pr-22208
2 parents a63e5a5 + 5d91ab1 commit 2d67e12

80 files changed

Lines changed: 3380 additions & 1159 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/mobile/src/App.tsx‎

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,9 @@ import {
4040
type FoundationHotModule,
4141
} from "./lib/foundation-fast-refresh";
4242
import { useMobileNavigationTheme } from "./lib/useMobileNavigationTheme";
43-
import { useUiRuntimeMemoryWarningGc } from "./lib/useUiRuntimeMemoryWarningGc";
43+
import { installUiRuntimeMemoryWarningGc } from "./lib/useUiRuntimeMemoryWarningGc";
4444
import { SubscriptionUsageCoordinator } from "./widgets/SubscriptionUsageCoordinator";
45+
import { installSubscriptionUsageRefresh } from "./widgets/useSubscriptionUsage";
4546
import { GlobalVoiceInputControl } from "./features/voice-input/GlobalVoiceInputControl";
4647
import { restoreSettingsLinkState } from "./features/settings/settings-navigation";
4748
import {
@@ -99,6 +100,14 @@ function handleNavigationReady(): void {
99100
declare const module: { readonly hot?: FoundationHotModule } | undefined;
100101

101102
const appServiceDisposers = [
103+
installUiRuntimeMemoryWarningGc(),
104+
subscribeComposerDraftModelReconciliation({
105+
registry: appAtomRegistry,
106+
threadShellAtom: environmentThreadShells.threadShellAtom,
107+
threadRefsAtom: environmentThreadShells.threadRefsAtom,
108+
shellStateAtom: environmentShell.stateAtom,
109+
}),
110+
installSubscriptionUsageRefresh(),
102111
installPermissionUpdateNotice(),
103112
installThreadOutboxDelivery(),
104113
installComposerAttachmentUploads(),
@@ -118,18 +127,6 @@ function SplashScreenCoordinator() {
118127
}
119128

120129
export default function App() {
121-
useUiRuntimeMemoryWarningGc();
122-
useEffect(
123-
() =>
124-
subscribeComposerDraftModelReconciliation({
125-
registry: appAtomRegistry,
126-
threadShellAtom: environmentThreadShells.threadShellAtom,
127-
threadRefsAtom: environmentThreadShells.threadRefsAtom,
128-
shellStateAtom: environmentShell.stateAtom,
129-
}),
130-
[],
131-
);
132-
133130
return (
134131
<RegistryContext.Provider value={appAtomRegistry}>
135132
<CloudAuthProvider>

‎apps/mobile/src/features/files/useFileTreeEntries.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
1+
import { useAtomMount, useAtomSubscribe } from "@effect/atom-react";
12
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
23
import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
34
import * as Cause from "effect/Cause";
5+
import { Atom } from "effect/reactivity";
46
import { useEffect, useReducer, useRef, useState } from "react";
57

8+
import { environmentCatalog } from "../../connection/catalog";
69
import { appAtomRegistry } from "../../state/atom-registry";
710
import { projectEnvironment } from "../../state/projects";
811
import { useDebouncedValue } from "../../state/queries";
912
import { useEnvironmentQuery } from "../../state/query";
1013

14+
const noSessionGeneration = Atom.make(0);
15+
1116
export function useFileTreeEntries(input: {
1217
readonly cwd: string | null;
1318
readonly environmentId: EnvironmentId | null;
@@ -94,6 +99,17 @@ export function useFileTreeEntries(input: {
9499
render();
95100
});
96101
};
102+
// A folder read fails at once while its environment is unreachable; read it again once a new
103+
// session is up rather than leaving the error until someone refreshes.
104+
const sessionGeneration =
105+
environmentId === null
106+
? noSessionGeneration
107+
: environmentCatalog.sessionGenerationAtom(environmentId);
108+
// A listener alone does not compute the atom, so nothing would follow the connection.
109+
useAtomMount(sessionGeneration);
110+
useAtomSubscribe(sessionGeneration, () => {
111+
for (const path of directories.errors.keys()) void loadDirectory(path);
112+
});
97113
const { refresh: refreshRoot, data: rootData } = root;
98114
const { refresh: refreshSearch, data: searchData } = search;
99115
const snapshot = (() => {

‎apps/mobile/src/features/pull-requests/usePullRequestList.ts‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
import { RegistryContext, useAtomValue } from "@effect/atom-react";
1+
import { RegistryContext, useAtomMount, useAtomSubscribe, useAtomValue } from "@effect/atom-react";
22
import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
33
import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts";
44
import * as Cause from "effect/Cause";
55
import * as Effect from "effect/Effect";
66
import * as Option from "effect/Option";
77
import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
88
import { use, useCallback, useMemo, useState } from "react";
9+
import { environmentCatalog } from "../../connection/catalog";
910
import {
1011
composerPullRequests,
1112
pullRequestListPagesFamily,
@@ -142,6 +143,15 @@ const refreshLoadFamily = Atom.family((scopeKey: string) =>
142143
),
143144
);
144145

146+
// Changes when any of the scope's environments brings up a new session.
147+
const sessionsFamily = Atom.family((scopeKey: string) =>
148+
Atom.make((get) =>
149+
(JSON.parse(scopeKey) as readonly ListTarget[])
150+
.map(({ environmentId }) => get(environmentCatalog.sessionGenerationAtom(environmentId)))
151+
.join(),
152+
),
153+
);
154+
145155
const settledError = (result: AsyncResult.AsyncResult<string | null, never>) =>
146156
AsyncResult.isSuccess(result) && !result.waiting ? result.value : null;
147157

@@ -156,6 +166,19 @@ export function usePullRequestList(targets: readonly ListTarget[]) {
156166
// Starting one kind of load clears the other, so at most one holds an error.
157167
const loadError = settledError(refresh) ?? settledError(page);
158168

169+
// A page or refresh asked for while an environment was unreachable fails at once, and its
170+
// error stops loading on scroll. Once it is back, ask for the page again; a refresh's error is
171+
// stale by then because the list queries re-run on reconnect.
172+
// A listener alone does not compute the atom, so nothing would follow the connections.
173+
useAtomMount(sessionsFamily(scopeKey));
174+
useAtomSubscribe(sessionsFamily(scopeKey), () => {
175+
const pageResult = registry.get(pageAtom);
176+
const refreshResult = registry.get(refreshAtom);
177+
if (settledError(refreshResult) !== null) registry.set(refreshAtom, Atom.Reset);
178+
else if (settledError(pageResult) !== null && !refreshResult.waiting)
179+
registry.set(pageAtom, true);
180+
});
181+
159182
// Read from the registry, not the render: a second onEndReached before React re-renders must
160183
// see the load the first one started.
161184
const loadMore = (retry = false) => {

‎apps/mobile/src/lib/appState.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,12 @@ import { AccessibilityInfo, AppState } from "react-native";
33

44
type Listener = () => void;
55

6-
function subscribeAppState(onChange: Listener): () => void {
6+
export function subscribeAppState(onChange: Listener): () => void {
77
const subscription = AppState.addEventListener("change", () => onChange());
88
return () => subscription.remove();
99
}
1010

11-
function isAppActive(): boolean {
11+
export function isAppActive(): boolean {
1212
return AppState.currentState === "active";
1313
}
1414

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import { useEffect } from "react";
21
import { AppState } from "react-native";
32
import { scheduleOnUI } from "react-native-worklets";
43

@@ -9,11 +8,9 @@ function collectUiRuntimeGarbage() {
98
}
109

1110
/** iOS memory warnings collect only RN's heap; collect worklets too to release shadow nodes and serializables. */
12-
export function useUiRuntimeMemoryWarningGc() {
13-
useEffect(() => {
14-
const subscription = AppState.addEventListener("memoryWarning", () => {
15-
scheduleOnUI(collectUiRuntimeGarbage);
16-
});
17-
return () => subscription.remove();
18-
}, []);
11+
export function installUiRuntimeMemoryWarningGc(): () => void {
12+
const subscription = AppState.addEventListener("memoryWarning", () => {
13+
scheduleOnUI(collectUiRuntimeGarbage);
14+
});
15+
return () => subscription.remove();
1916
}

‎apps/mobile/src/state/assets.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ const state = vi.hoisted(() => ({
1919

2020
vi.mock("react", () => ({ useCallback: <A>(callback: A) => callback }));
2121
vi.mock("@effect/atom-react", () => ({
22+
useAtomMount: () => undefined,
23+
useAtomSubscribe: () => undefined,
2224
useAtomValue: (atom: unknown) =>
2325
atom === state.assetAtom
2426
? AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 })
@@ -39,6 +41,9 @@ vi.mock("./query", () => ({
3941
}));
4042
vi.mock("./projectClones", () => ({ environmentProjectCloneListAtom: () => null }));
4143
vi.mock("../connection/runtime", () => ({ connectionAtomRuntime: {} }));
44+
vi.mock("../connection/catalog", () => ({
45+
environmentCatalog: { sessionGenerationAtom: () => null },
46+
}));
4247
vi.mock("@t3tools/client-runtime/state/assets", async (importOriginal) => ({
4348
...(await importOriginal<typeof import("@t3tools/client-runtime/state/assets")>()),
4449
createAssetEnvironmentAtoms: () => ({ createUrl: state.assetQuery }),

‎apps/mobile/src/state/assets.ts‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useAtomValue } from "@effect/atom-react";
1+
import { useAtomMount, useAtomSubscribe, useAtomValue } from "@effect/atom-react";
22
import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
33
import {
44
assetUrlStateFromResult,
@@ -13,6 +13,7 @@ import * as Effect from "effect/Effect";
1313
import { Atom, AsyncResult } from "effect/reactivity";
1414
import { useCallback } from "react";
1515

16+
import { environmentCatalog } from "../connection/catalog";
1617
import { connectionAtomRuntime } from "../connection/runtime";
1718
import { projectFaviconDatabaseCache } from "../lib/projectFaviconDatabaseCache";
1819
import { type AssetUrlState, deriveAssetUrlState } from "./asset-url-state";
@@ -112,7 +113,7 @@ export async function refreshAssetUrl(
112113
reportFailure: false,
113114
...(signal ? { signal } : {}),
114115
});
115-
// The query can wait through a reconnect; resolve against the connection that answered it.
116+
// A route can change while the query runs; resolve against the connection now current.
116117
const connection = appAtomRegistry.get(connectionAtom);
117118
if (connection._tag === "None") return null;
118119
const state = assetUrlStateFromResult(result, connection.value.httpBaseUrl);
@@ -154,6 +155,7 @@ const freshAssetUrlFamily = Atom.family((key: FreshAssetUrlKey) =>
154155
const noFreshAssetUrl = Atom.make(AsyncResult.initial<AuthorizedAssetUrl, Error>()).pipe(
155156
Atom.withLabel("fresh-asset-url:none"),
156157
);
158+
const noSessionGeneration = Atom.make(0);
157159

158160
/**
159161
* A signed URL minted when the reader mounts, not a cached one: cached links can
@@ -166,9 +168,20 @@ export function useFreshAssetUrl(
166168
): AsyncResult.AsyncResult<AuthorizedAssetUrl, Error> {
167169
const connection = usePreparedConnection(environmentId);
168170
const httpBaseUrl = connection._tag === "Some" ? connection.value.httpBaseUrl : null;
169-
return useAtomValue(
171+
const atom =
170172
resource === null
171173
? noFreshAssetUrl
172-
: freshAssetUrlFamily({ environmentId, resource, httpBaseUrl, revision }),
173-
);
174+
: freshAssetUrlFamily({ environmentId, resource, httpBaseUrl, revision });
175+
// Minting fails at once while the environment is unreachable; mint again once a new session is
176+
// up instead of keeping the error until Retry.
177+
const sessionGeneration =
178+
environmentId === null
179+
? noSessionGeneration
180+
: environmentCatalog.sessionGenerationAtom(environmentId);
181+
// A listener alone does not compute the atom, so nothing would follow the connection.
182+
useAtomMount(sessionGeneration);
183+
useAtomSubscribe(sessionGeneration, () => {
184+
if (AsyncResult.isFailure(appAtomRegistry.get(atom))) appAtomRegistry.refresh(atom);
185+
});
186+
return useAtomValue(atom);
174187
}

‎apps/mobile/src/widgets/SubscriptionUsageCoordinator.tsx‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import { useAppearancePreferences } from "../features/settings/appearance/Appear
77
import { environmentCatalog } from "../connection/catalog";
88
import { environmentPresentations } from "../state/presentation";
99
import { publishSubscriptionUsage } from "./publishSubscriptionUsage";
10-
import { useSubscriptionUsage } from "./useSubscriptionUsage";
1110
import { buildSubscriptionUsageSnapshot } from "./subscriptionUsageSnapshot";
1211
import { createWidgetTheme } from "./widgetTheme";
1312

@@ -29,7 +28,6 @@ export function SubscriptionUsageCoordinator() {
2928
} = useAppearancePreferences();
3029
const catalog = useAtomValue(environmentCatalog.catalogValueAtom);
3130
const snapshot = useAtomValue(snapshotAtom);
32-
useSubscriptionUsage(catalog.isReady);
3331
const androidAppearance = Platform.OS === "android" ? themeAppearance : null;
3432
useEffect(() => {
3533
if (!catalog.isReady || !appearanceReady) return;
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
import { EnvironmentId } from "@t3tools/contracts";
2+
import { Atom, AtomRegistry } from "effect/reactivity";
3+
import { describe, expect, it, vi } from "vite-plus/test";
4+
5+
const fixture = vi.hoisted(() => ({
6+
appState: "active",
7+
appStateListeners: new Set<() => void>(),
8+
refreshed: [] as string[],
9+
}));
10+
11+
vi.mock("react-native", () => ({
12+
AppState: {
13+
get currentState() {
14+
return fixture.appState;
15+
},
16+
addEventListener: (_event: string, listener: () => void) => {
17+
fixture.appStateListeners.add(listener);
18+
return { remove: () => fixture.appStateListeners.delete(listener) };
19+
},
20+
},
21+
AccessibilityInfo: { addEventListener: vi.fn(), isReduceMotionEnabled: vi.fn() },
22+
}));
23+
24+
vi.mock("../state/atom-registry", async () => {
25+
const { AtomRegistry } = await import("effect/reactivity");
26+
return { appAtomRegistry: AtomRegistry.make() };
27+
});
28+
29+
vi.mock("../connection/catalog", async () => {
30+
const { Atom } = await import("effect/reactivity");
31+
return { environmentCatalog: { catalogValueAtom: Atom.make({ isReady: false }) } };
32+
});
33+
34+
vi.mock("../state/presentation", async () => {
35+
const { Atom } = await import("effect/reactivity");
36+
return {
37+
environmentPresentations: { presentationsAtom: Atom.make(new Map<string, unknown>()) },
38+
};
39+
});
40+
41+
vi.mock("../state/server", () => ({
42+
serverEnvironment: { refreshProviders: { label: "Refresh providers" } },
43+
}));
44+
45+
vi.mock("@t3tools/client-runtime/state/runtime", () => ({
46+
runAtomCommand: (
47+
_registry: unknown,
48+
_command: unknown,
49+
input: { readonly environmentId: string },
50+
) => {
51+
fixture.refreshed.push(input.environmentId);
52+
return Promise.resolve();
53+
},
54+
}));
55+
56+
import { environmentCatalog } from "../connection/catalog";
57+
import { appAtomRegistry } from "../state/atom-registry";
58+
import { environmentPresentations } from "../state/presentation";
59+
import { installSubscriptionUsageRefresh } from "./useSubscriptionUsage";
60+
61+
const registry = appAtomRegistry as AtomRegistry.AtomRegistry;
62+
const catalogAtom = environmentCatalog.catalogValueAtom as unknown as Atom.Writable<{
63+
isReady: boolean;
64+
}>;
65+
const presentationsAtom = environmentPresentations.presentationsAtom as unknown as Atom.Writable<
66+
Map<string, { connection: { phase: string } }>
67+
>;
68+
69+
const connected = EnvironmentId.make("env-connected");
70+
const connecting = EnvironmentId.make("env-connecting");
71+
72+
describe("installSubscriptionUsageRefresh", () => {
73+
it("refreshes connected environments once the catalog is ready and the app is active", () => {
74+
fixture.appState = "background";
75+
fixture.refreshed = [];
76+
registry.set(catalogAtom, { isReady: false });
77+
registry.set(
78+
presentationsAtom,
79+
new Map([
80+
[connected, { connection: { phase: "connected" } }],
81+
[connecting, { connection: { phase: "connecting" } }],
82+
]),
83+
);
84+
85+
const dispose = installSubscriptionUsageRefresh();
86+
registry.set(catalogAtom, { isReady: true });
87+
// Backgrounded: nothing refreshes yet.
88+
expect(fixture.refreshed).toEqual([]);
89+
90+
fixture.appState = "active";
91+
for (const listener of fixture.appStateListeners) listener();
92+
expect(fixture.refreshed).toEqual([connected]);
93+
94+
dispose();
95+
expect(fixture.appStateListeners.size).toBe(0);
96+
});
97+
});

0 commit comments

Comments
 (0)