Skip to content

Commit f2e4fed

Browse files
refactor(client): shared clocks, trackers and services replace effects
Adds the client-runtime pieces web and mobile build on: shared clock and deadline stores, a thread visit tracker, a workspace snapshot refresh atom, a cloud account service, a queued-run edit store and a per-answer hook on environment queries. Usage-limit, delayed-status and visit views on both clients move onto them in this layer. Effect categories removed: - timers moved to shared second/minute ticks and per-deadline stores (usage-limit resets, delayed status, debounce) - thread visit recording moved from chained view effects into a keyed tracker atom that records the open and throttles the watermark - workspace snapshot scans and retry cooldowns moved into one keyed atom family that stops with its last subscriber - suggested answers seeded into pending-request drafts at read time, and resolved-request drafts pruned when thread state reports resolution - cloud account transitions and teardown moved into one service with an explicit state machine; relay listing errors log once per fetch - query answers can be handled where they land, so derived records no longer need mirror effects in each consumer Bugs fixed: - Mobile usage-limit card never noticed a reset more than ~24.8 days out. - Mobile never pruned answer drafts for resolved requests. - Drafts for requests answered on another device, interrupted or ended with the turn were kept until the user next typed in that thread. - Mobile re-restored cloud composer drafts and re-activated the relay session on every render of the cloud auth bridge. - A failed cloud account activation left Connect dead until the account changed; it now retries on the next emission. - Switching threads could delay the first visit watermark by up to 10s. Temporary compat shims (removed in a later layer of this stack): - providerSkills.ts: keep hasCurrentProviderWorkspaceSnapshot exported for base mobile use-composer-command-menu.ts until the mobile-threads layer adopts the shared refresh atom (removed in layer 14) Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent a96cf08 commit f2e4fed

41 files changed

Lines changed: 2510 additions & 631 deletions

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/features/cloud/CloudAuthProvider.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
22
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
33

44
import { appAtomRegistry } from "../../state/atom-registry";
5-
import { activateCloudRelayAccount, deactivateCloudRelayAccount } from "./CloudAuthProvider";
5+
import { activateCloudRelayAccount, deactivateCloudRelayAccount } from "./cloudAccountService";
66
import { setAgentAwarenessRelayTokenProvider } from "../agent-awareness/remoteRegistration";
77

88
vi.mock("@clerk/expo", () => ({
@@ -27,6 +27,10 @@ vi.mock("../../connection/catalog", () => ({
2727
}));
2828

2929
vi.mock("./cloud-drafts", () => ({ removeCloudEnvironments: {} }));
30+
vi.mock("./connectOnboarding", () => ({
31+
clearConnectOnboardingRequest: vi.fn(),
32+
requestConnectOnboarding: vi.fn(),
33+
}));
3034
vi.mock("../../state/use-composer-drafts", () => ({
3135
getComposerCloudAccountId: vi.fn(async () => null),
3236
restoreCloudComposerDrafts: vi.fn(async () => undefined),
Lines changed: 20 additions & 196 deletions
Original file line numberDiff line numberDiff line change
@@ -1,208 +1,32 @@
1-
import { ClerkProvider, useAuth } from "@clerk/expo";
1+
import { ClerkProvider, getClerkInstance } from "@clerk/expo";
22
import { tokenCache } from "@clerk/expo/token-cache";
3-
import { ManagedRelay, setManagedRelaySession } from "@t3tools/client-runtime/relay";
4-
import {
5-
reportAtomCommandResult,
6-
settleAsyncResult,
7-
settlePromise,
8-
squashAtomCommandFailure,
9-
} from "@t3tools/client-runtime/state/runtime";
10-
import * as Effect from "effect/Effect";
11-
import { type ReactNode, useEffect, useRef } from "react";
12-
13-
import { runtime } from "../../lib/runtime";
14-
import { appAtomRegistry } from "../../state/atom-registry";
15-
import { useAtomCommand } from "../../state/use-atom-command";
16-
import {
17-
getComposerCloudAccountId,
18-
restoreCloudComposerDrafts,
19-
} from "../../state/use-composer-drafts";
20-
import {
21-
releaseAgentAwarenessRelayTokenProvider,
22-
setAgentAwarenessRelayTokenProvider,
23-
unregisterAgentAwarenessDeviceForCurrentUser,
24-
} from "../agent-awareness/remoteRegistration";
25-
import { clearConnectOnboardingRequest, requestConnectOnboarding } from "./connectOnboarding";
26-
import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig";
27-
import { removeCloudEnvironments } from "./cloud-drafts";
28-
29-
function resetManagedRelayTokenCache() {
30-
return settleAsyncResult(() =>
31-
runtime.runPromiseExit(
32-
ManagedRelay.ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)),
33-
),
34-
);
35-
}
36-
37-
export function deactivateCloudRelayAccount(): void {
38-
setAgentAwarenessRelayTokenProvider(null);
39-
setManagedRelaySession(appAtomRegistry, null);
40-
}
41-
42-
export function activateCloudRelayAccount(
43-
accountId: string,
44-
tokenProvider: () => Promise<string | null>,
45-
): void {
46-
setAgentAwarenessRelayTokenProvider(tokenProvider, accountId);
47-
setManagedRelaySession(appAtomRegistry, {
48-
accountId,
49-
readClerkToken: tokenProvider,
50-
});
51-
}
52-
53-
function CloudAuthBridge(props: { readonly children: ReactNode }) {
54-
const { getToken, isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
55-
const removeRelayEnvironments = useAtomCommand(removeCloudEnvironments, {
56-
reportFailure: false,
57-
reportDefect: false,
58-
});
59-
const previousTokenProviderRef = useRef<{
60-
readonly userId: string;
61-
readonly provider: () => Promise<string | null>;
62-
} | null>(null);
63-
const observedAccountRef = useRef<string | null | undefined>(undefined);
64-
const accountTransitionRef = useRef<Promise<void> | null>(null);
65-
66-
useEffect(() => {
67-
let cancelled = false;
68-
if (!isLoaded) {
69-
return;
70-
}
71-
72-
const previousObservedAccount = observedAccountRef.current;
73-
const nextAccount = isSignedIn && userId ? userId : null;
74-
observedAccountRef.current = nextAccount;
75-
76-
// Request after activateSession cleanup to avoid listing the previous account; sign-out drops pending requests.
77-
const isAccountTransition =
78-
previousObservedAccount !== undefined && previousObservedAccount !== nextAccount;
79-
if (isAccountTransition && nextAccount === null) {
80-
clearConnectOnboardingRequest();
81-
}
82-
83-
const cleanUpAccount = async (
84-
previous: {
85-
readonly userId: string;
86-
readonly provider: () => Promise<string | null>;
87-
} | null,
88-
accountId: string | null,
89-
) => {
90-
const removal = await removeRelayEnvironments(accountId);
91-
if (removal._tag !== "Success") throw squashAtomCommandFailure(removal);
92-
const cleanup = [
93-
resetManagedRelayTokenCache(),
94-
...(previous
95-
? [
96-
settleAsyncResult(() =>
97-
runtime.runPromiseExit(
98-
unregisterAgentAwarenessDeviceForCurrentUser(previous.provider),
99-
),
100-
),
101-
]
102-
: []),
103-
];
104-
const results = await Promise.all(cleanup);
105-
for (const result of results) {
106-
reportAtomCommandResult(result, { label: "cloud account cleanup" });
107-
}
108-
};
109-
const queueAccountCleanup = (previous: typeof previousTokenProviderRef.current) => {
110-
const previousTransition = accountTransitionRef.current ?? Promise.resolve();
111-
accountTransitionRef.current = previousTransition
112-
.catch(() => {})
113-
.then(() => cleanUpAccount(previous, previousObservedAccount ?? null));
114-
return accountTransitionRef.current;
115-
};
116-
117-
if (!isSignedIn || !userId) {
118-
const previous = previousTokenProviderRef.current;
119-
previousTokenProviderRef.current = null;
120-
deactivateCloudRelayAccount();
121-
if (previousObservedAccount !== null) {
122-
void settlePromise(() => queueAccountCleanup(previous)).then((result) => {
123-
reportAtomCommandResult(result, { label: "cloud account cleanup" });
124-
});
125-
}
126-
return;
127-
}
128-
129-
const previous = previousTokenProviderRef.current;
130-
const tokenProvider = () => getToken(resolveRelayClerkTokenOptions());
131-
const activateSession = () => {
132-
if (cancelled) {
133-
return;
134-
}
135-
previousTokenProviderRef.current = { userId, provider: tokenProvider };
136-
activateCloudRelayAccount(userId, tokenProvider);
137-
if (isAccountTransition) {
138-
requestConnectOnboarding(userId);
139-
}
140-
};
141-
const activateAfterTransition = (transition: Promise<void>) => {
142-
const activation = (async () => {
143-
await transition;
144-
if (cancelled) return;
145-
const storedAccount = await getComposerCloudAccountId();
146-
if (storedAccount !== null && storedAccount !== userId) {
147-
await cleanUpAccount(null, storedAccount);
148-
}
149-
if (cancelled) return;
150-
await restoreCloudComposerDrafts(userId);
151-
activateSession();
152-
})();
153-
accountTransitionRef.current = activation;
154-
void settlePromise(() => activation).then((result) => {
155-
reportAtomCommandResult(result, { label: "cloud account activation" });
156-
});
157-
};
158-
if (
159-
previousObservedAccount !== undefined &&
160-
previousObservedAccount !== null &&
161-
previousObservedAccount !== userId
162-
) {
163-
previousTokenProviderRef.current = null;
164-
deactivateCloudRelayAccount();
165-
activateAfterTransition(queueAccountCleanup(previous));
166-
} else {
167-
activateAfterTransition((accountTransitionRef.current ?? Promise.resolve()).catch(() => {}));
168-
}
169-
170-
return () => {
171-
cancelled = true;
172-
};
173-
}, [getToken, isLoaded, isSignedIn, removeRelayEnvironments, userId]);
174-
175-
useEffect(
176-
() => () => {
177-
previousTokenProviderRef.current = null;
178-
// Unmounting does not imply sign-out; preserve registration and lock-screen activities.
179-
releaseAgentAwarenessRelayTokenProvider();
180-
setManagedRelaySession(appAtomRegistry, null);
181-
},
182-
[],
183-
);
184-
185-
return props.children;
3+
import type { ReactNode } from "react";
4+
5+
import { cloudAccountService, deactivateCloudRelayAccount } from "./cloudAccountService";
6+
import { resolveCloudPublicConfig } from "./publicConfig";
7+
8+
const cloudConfig = resolveCloudPublicConfig();
9+
// Build-time constant: null when this build has no cloud config.
10+
const publishableKey = cloudConfig.relay.url ? cloudConfig.clerk.publishableKey : null;
11+
12+
if (publishableKey) {
13+
// The same native singleton ClerkProvider renders with, so the service
14+
// observes it for the app's lifetime without a React subscription.
15+
cloudAccountService.attach(getClerkInstance({ publishableKey }));
16+
} else {
17+
// Without cloud config no account can ever activate, so drop anything a
18+
// previous build with cloud enabled left registered.
19+
deactivateCloudRelayAccount();
18620
}
18721

18822
export function CloudAuthProvider(props: { readonly children: ReactNode }) {
189-
const config = resolveCloudPublicConfig();
190-
const publishableKey = config.clerk.publishableKey;
191-
const relayUrl = config.relay.url;
192-
193-
useEffect(() => {
194-
if (!publishableKey || !relayUrl) {
195-
deactivateCloudRelayAccount();
196-
}
197-
}, [publishableKey, relayUrl]);
198-
199-
if (!publishableKey || !relayUrl) {
23+
if (!publishableKey) {
20024
return props.children;
20125
}
20226

20327
return (
20428
<ClerkProvider publishableKey={publishableKey} tokenCache={tokenCache}>
205-
<CloudAuthBridge>{props.children}</CloudAuthBridge>
29+
{props.children}
20630
</ClerkProvider>
20731
);
20832
}
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
import type { getClerkInstance } from "@clerk/expo";
2+
import {
3+
createCloudAccountService,
4+
ManagedRelay,
5+
setManagedRelaySession,
6+
} from "@t3tools/client-runtime/relay";
7+
import {
8+
reportAtomCommandResult,
9+
runAtomCommand,
10+
settleAsyncResult,
11+
squashAtomCommandFailure,
12+
} from "@t3tools/client-runtime/state/runtime";
13+
import * as Effect from "effect/Effect";
14+
15+
import { runtime } from "../../lib/runtime";
16+
import { appAtomRegistry } from "../../state/atom-registry";
17+
import {
18+
getComposerCloudAccountId,
19+
restoreCloudComposerDrafts,
20+
} from "../../state/use-composer-drafts";
21+
import {
22+
releaseAgentAwarenessRelayTokenProvider,
23+
setAgentAwarenessRelayTokenProvider,
24+
unregisterAgentAwarenessDeviceForCurrentUser,
25+
} from "../agent-awareness/remoteRegistration";
26+
import { removeCloudEnvironments } from "./cloud-drafts";
27+
import { clearConnectOnboardingRequest, requestConnectOnboarding } from "./connectOnboarding";
28+
import { resolveRelayClerkTokenOptions } from "./publicConfig";
29+
30+
type ClerkInstance = ReturnType<typeof getClerkInstance>;
31+
32+
export function deactivateCloudRelayAccount(): void {
33+
setAgentAwarenessRelayTokenProvider(null);
34+
setManagedRelaySession(appAtomRegistry, null);
35+
}
36+
37+
export function activateCloudRelayAccount(
38+
accountId: string,
39+
tokenProvider: () => Promise<string | null>,
40+
): void {
41+
setAgentAwarenessRelayTokenProvider(tokenProvider, accountId);
42+
setManagedRelaySession(appAtomRegistry, {
43+
accountId,
44+
readClerkToken: tokenProvider,
45+
});
46+
}
47+
48+
function clerkTokenReader(clerk: ClerkInstance): () => Promise<string | null> {
49+
return async () =>
50+
clerk.session ? await clerk.session.getToken(resolveRelayClerkTokenOptions()) : null;
51+
}
52+
53+
const cleanUpCloudAccount = async (
54+
clerk: ClerkInstance,
55+
accountId: string | null,
56+
wasActive: boolean,
57+
) => {
58+
const removal = await runAtomCommand(appAtomRegistry, removeCloudEnvironments, accountId, {
59+
reportFailure: false,
60+
reportDefect: false,
61+
});
62+
if (removal._tag !== "Success") throw squashAtomCommandFailure(removal);
63+
const results = await Promise.all([
64+
settleAsyncResult(() =>
65+
runtime.runPromiseExit(
66+
ManagedRelay.ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)),
67+
),
68+
),
69+
...(wasActive
70+
? [
71+
settleAsyncResult(() =>
72+
runtime.runPromiseExit(
73+
unregisterAgentAwarenessDeviceForCurrentUser(clerkTokenReader(clerk)),
74+
),
75+
),
76+
]
77+
: []),
78+
]);
79+
for (const result of results) {
80+
reportAtomCommandResult(result, { label: "cloud account cleanup" });
81+
}
82+
};
83+
84+
export const cloudAccountService = createCloudAccountService<ClerkInstance>({
85+
deactivate: deactivateCloudRelayAccount,
86+
// Detaching is not a sign-out: the user is usually still signed in, so keep
87+
// lock-screen activities and the persisted registration for the next attach.
88+
detach: () => {
89+
releaseAgentAwarenessRelayTokenProvider();
90+
setManagedRelaySession(appAtomRegistry, null);
91+
},
92+
// A not-yet-presented onboarding request belongs to the account that left.
93+
onSignOutTransition: clearConnectOnboardingRequest,
94+
cleanUp: ({ source, accountId, wasActive }) => cleanUpCloudAccount(source, accountId, wasActive),
95+
prepare: async ({ source, accountId, isCurrent }) => {
96+
const storedAccount = await getComposerCloudAccountId();
97+
if (storedAccount !== null && storedAccount !== accountId) {
98+
await cleanUpCloudAccount(source, storedAccount, false);
99+
}
100+
if (!isCurrent()) return;
101+
await restoreCloudComposerDrafts(accountId);
102+
},
103+
activate: ({ source, accountId, isAccountTransition }) => {
104+
activateCloudRelayAccount(accountId, clerkTokenReader(source));
105+
// Issued after cleanup so the sheet never lists the previous account's environments.
106+
if (isAccountTransition) requestConnectOnboarding(accountId);
107+
},
108+
});

‎apps/mobile/src/features/cloud/connectOnboardingOptOut.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { loadPreferences, updatePreferences } from "../../persistence/imperative";
22

3-
// Keep persistence out of CloudAuthProvider's import graph; it breaks suite loading.
3+
// Lives apart from connectOnboarding.ts so cloudAccountService.ts (which
4+
// imports the request signal) never pulls the persistence adapter into its
5+
// module graph; that breaks CloudAuthProvider.test.ts suite loading.
46

57
export async function isConnectOnboardingOptedOut(accountId: string): Promise<boolean> {
68
const preferences = await loadPreferences();

‎apps/mobile/src/features/cloud/managedRelayState.ts‎

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
import type { EnvironmentId } from "@t3tools/contracts";
1313
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
1414
import { AsyncResult, Atom } from "effect/reactivity";
15-
import { useCallback, useEffect } from "react";
15+
import { useCallback } from "react";
1616

1717
import * as Runtime from "../../lib/runtime";
1818
import { appAtomRegistry } from "../../state/atom-registry";
@@ -53,14 +53,6 @@ export function useManagedRelayEnvironments() {
5353
: EMPTY_ENVIRONMENTS_ATOM;
5454
const result = useAtomValue(atom);
5555
const snapshot = readManagedRelaySnapshotState(result);
56-
useEffect(() => {
57-
if (snapshot.error) {
58-
console.error("[t3-cloud] Relay environment listing failed", {
59-
message: snapshot.error,
60-
traceId: snapshot.errorTraceId,
61-
});
62-
}
63-
}, [snapshot.error, snapshot.errorTraceId]);
6456
const refresh = useCallback(() => {
6557
if (accountId) {
6658
managedRelayQueryManager.refreshEnvironments(appAtomRegistry, accountId);

0 commit comments

Comments
 (0)