Skip to content

Commit e48e4c7

Browse files
refactor(web): app shell, auth routes and sidebar widgets stop syncing
Route-entry work for pairing, connect and thread links runs from route loaders and navigation listeners, and the app shell, desktop hosts, sidebar widgets, usage page and animated layout helpers act in handlers, ref callbacks and shared stores. Effect categories removed: - route-entry work (pairing token submit, connect-agent lookup, CLI auth watch, thread link prompts) moved to route loaders and route hooks - sidebar toggle, back/forward, undo and usage shortcuts moved to dispatcher scopes - timers moved to shared deadlines and stores (SSH countdown, toast dismissal, update pill exit, panel exit, quit-hold hint) - measurement and tooltip tracking moved to ref callbacks - resize drag state captured at pointer-down and released by the handle's ref callback - relay discovery polling and computer selection moved to an onboarding store; usage limits refresh from per-environment atoms Bugs fixed: - SSH password prompts that arrived while the dialog was closed were lost. - The sidebar toggle shortcut could not yield to terminal- or preview-scoped bindings on the same chord. - Undo notices re-announced an unchanged summary. - Successful pairing re-enabled the form for a frame before reloading. - /connect-agent fetched the approval twice. - A thread link's prompt was placed while the hosted landing page was still asking where to open it, and "Continue here" did not survive a remount. - Reopening the wizard's connect step flashed the empty computer list. Kept effects: - Resizable width layout effect: re-applies a live drag after a render. - Panel navigation suppression: "after paint" needs requestAnimationFrame. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent c0dccbe commit e48e4c7

58 files changed

Lines changed: 2791 additions & 1232 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import { describe, expect, it, vi } from "vite-plus/test";
2+
3+
vi.mock("../env", () => ({ isElectron: false }));
4+
vi.mock("./connectCliAuth", () => ({
5+
buildConnectCliClerkAuthorizeUrl: (request: { state: string }) =>
6+
`https://clerk.test/oauth/authorize?state=${request.state}`,
7+
connectCliSignInRedirectUrl: (_request: unknown, href: string) => href,
8+
}));
9+
10+
import {
11+
stopConnectCliAuthorization,
12+
watchConnectCliAuthorization,
13+
} from "./connectCliAuthorization";
14+
import { type ManagedClerk, publishManagedClerk } from "./managedClerk";
15+
16+
type Resources = { user: { id: string } | null | undefined };
17+
18+
const clerk = {
19+
isSignedIn: false,
20+
listeners: new Set<(resources: Resources) => void>(),
21+
openSignIn: vi.fn(),
22+
addListener(listener: (resources: Resources) => void) {
23+
this.listeners.add(listener);
24+
return () => this.listeners.delete(listener);
25+
},
26+
emit(resources: Resources) {
27+
for (const listener of this.listeners) listener(resources);
28+
},
29+
};
30+
publishManagedClerk(clerk as unknown as ManagedClerk);
31+
32+
const assign = vi.fn();
33+
vi.stubGlobal("window", { location: { href: "https://app.test/connect", assign } });
34+
35+
function setup() {
36+
stopConnectCliAuthorization();
37+
clerk.isSignedIn = false;
38+
clerk.openSignIn.mockClear();
39+
assign.mockClear();
40+
}
41+
42+
const request = (state: string) => ({ state, challenge: "c", loopbackPort: 4321 });
43+
44+
describe("watchConnectCliAuthorization", () => {
45+
it("opens sign-in once per request, across emissions and route reloads", async () => {
46+
setup();
47+
watchConnectCliAuthorization(request("a"));
48+
await Promise.resolve();
49+
clerk.emit({ user: undefined });
50+
expect(clerk.openSignIn).not.toHaveBeenCalled();
51+
52+
clerk.emit({ user: null });
53+
clerk.emit({ user: null });
54+
watchConnectCliAuthorization(request("a"));
55+
clerk.emit({ user: null });
56+
expect(clerk.openSignIn).toHaveBeenCalledTimes(1);
57+
expect(clerk.listeners.size).toBe(1);
58+
});
59+
60+
it("redirects to the authorize URL once signed in, and only once", async () => {
61+
setup();
62+
watchConnectCliAuthorization(request("b"));
63+
await Promise.resolve();
64+
clerk.isSignedIn = true;
65+
clerk.emit({ user: { id: "u" } });
66+
clerk.emit({ user: { id: "u" } });
67+
expect(assign).toHaveBeenCalledTimes(1);
68+
expect(assign).toHaveBeenCalledWith("https://clerk.test/oauth/authorize?state=b");
69+
});
70+
71+
it("stops listening when the route is left, even before Clerk is available", async () => {
72+
setup();
73+
watchConnectCliAuthorization(request("c"));
74+
stopConnectCliAuthorization();
75+
await Promise.resolve();
76+
expect(clerk.listeners.size).toBe(0);
77+
78+
watchConnectCliAuthorization(request("d"));
79+
await Promise.resolve();
80+
stopConnectCliAuthorization();
81+
clerk.emit({ user: null });
82+
expect(clerk.listeners.size).toBe(0);
83+
expect(clerk.openSignIn).not.toHaveBeenCalled();
84+
});
85+
});
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import type { ConnectAuthorizeRequest } from "@t3tools/shared/connectAuth";
2+
3+
import { resolveClerkSignInProps } from "../components/clerk/authRedirect";
4+
import { isElectron } from "../env";
5+
import { buildConnectCliClerkAuthorizeUrl, connectCliSignInRedirectUrl } from "./connectCliAuth";
6+
import { type ManagedClerk, whenManagedClerk } from "./managedClerk";
7+
8+
export function openConnectCliSignIn(clerk: ManagedClerk, request: ConnectAuthorizeRequest): void {
9+
clerk.openSignIn(
10+
resolveClerkSignInProps(connectCliSignInRedirectUrl(request, window.location.href), isElectron),
11+
);
12+
}
13+
14+
interface ConnectCliAuthorizationWatch {
15+
readonly state: string;
16+
stopped: boolean;
17+
signInOpened: boolean;
18+
redirecting: boolean;
19+
unsubscribe: (() => void) | null;
20+
}
21+
22+
let activeWatch: ConnectCliAuthorizationWatch | null = null;
23+
24+
/**
25+
* Drives one /connect visit from Clerk's own listener: opens sign-in once
26+
* Clerk loads signed out, and leaves for the authorize URL once signed in.
27+
* Keyed by the request's `state` so route reloads for the same request keep
28+
* the watch (and do not reopen sign-in).
29+
*/
30+
export function watchConnectCliAuthorization(request: ConnectAuthorizeRequest | null): void {
31+
if (request && activeWatch?.state === request.state) return;
32+
stopConnectCliAuthorization();
33+
if (!request) return;
34+
35+
const watch: ConnectCliAuthorizationWatch = {
36+
state: request.state,
37+
stopped: false,
38+
signInOpened: false,
39+
redirecting: false,
40+
unsubscribe: null,
41+
};
42+
activeWatch = watch;
43+
44+
// The route loads before ClerkProvider renders, so the instance arrives later.
45+
void whenManagedClerk().then((clerk) => {
46+
if (watch.stopped) return;
47+
watch.unsubscribe = clerk.addListener((resources) => {
48+
// Clerk reports `user: undefined` until it loads.
49+
if (resources.user === undefined || watch.redirecting) return;
50+
if (!clerk.isSignedIn) {
51+
if (!watch.signInOpened) {
52+
watch.signInOpened = true;
53+
openConnectCliSignIn(clerk, request);
54+
}
55+
return;
56+
}
57+
const authorizeUrl = buildConnectCliClerkAuthorizeUrl(request);
58+
if (!authorizeUrl) return;
59+
watch.redirecting = true;
60+
window.location.assign(authorizeUrl);
61+
});
62+
});
63+
}
64+
65+
export function stopConnectCliAuthorization(): void {
66+
const watch = activeWatch;
67+
if (!watch) return;
68+
activeWatch = null;
69+
watch.stopped = true;
70+
watch.unsubscribe?.();
71+
}

‎apps/web/src/cloud/managedAuth.tsx‎

Lines changed: 43 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,21 @@
1-
import { useAuth } from "@clerk/react";
2-
import { ManagedRelay, setManagedRelaySession } from "@t3tools/client-runtime/relay";
1+
import { useClerk } from "@clerk/react";
2+
import {
3+
createCloudAccountService,
4+
ManagedRelay,
5+
setManagedRelaySession,
6+
} from "@t3tools/client-runtime/relay";
37
import {
48
reportAtomCommandResult,
9+
runAtomCommand,
510
settleAsyncResult,
6-
settlePromise,
711
} from "@t3tools/client-runtime/state/runtime";
812
import * as Effect from "effect/Effect";
9-
import { useEffect, useRef, type ReactNode } from "react";
13+
import type { ReactNode } from "react";
1014

1115
import { environmentCatalog } from "../connection/catalog";
1216
import { runtime } from "../lib/runtime";
1317
import { appAtomRegistry } from "../rpc/atomRegistry";
14-
import { useAtomCommand } from "../state/use-atom-command";
18+
import { publishManagedClerk } from "./managedClerk";
1519
import { resolveRelayClerkTokenOptions } from "./publicConfig";
1620

1721
export function deactivateManagedRelayAuthentication(): void {
@@ -28,81 +32,43 @@ export function activateManagedRelayAuthentication(
2832
});
2933
}
3034

31-
export function ManagedRelayAuthProvider({ children }: { readonly children: ReactNode }) {
32-
const { getToken, isLoaded, isSignedIn, userId } = useAuth({
33-
treatPendingAsSignedOut: false,
34-
});
35-
const removeRelayEnvironments = useAtomCommand(environmentCatalog.removeRelayEnvironments, {
36-
reportFailure: false,
37-
reportDefect: false,
38-
});
39-
const observedAccountRef = useRef<string | null | undefined>(undefined);
40-
const accountTransitionRef = useRef<Promise<void> | null>(null);
41-
42-
useEffect(() => {
43-
if (!isLoaded) {
44-
return;
45-
}
46-
47-
let cancelled = false;
48-
const previousAccount = observedAccountRef.current;
49-
const nextAccount = isSignedIn && userId ? userId : null;
50-
observedAccountRef.current = nextAccount;
35+
type ClerkInstance = ReturnType<typeof useClerk>;
5136

52-
const queueAccountCleanup = () => {
53-
const previousTransition = accountTransitionRef.current ?? Promise.resolve();
54-
accountTransitionRef.current = previousTransition.then(async () => {
55-
const results = await Promise.all([
56-
removeRelayEnvironments(),
57-
settleAsyncResult(() =>
58-
runtime.runPromiseExit(
59-
ManagedRelay.ManagedRelayClient.pipe(
60-
Effect.flatMap((client) => client.resetTokenCache),
61-
),
62-
),
63-
),
64-
]);
65-
for (const result of results) {
66-
reportAtomCommandResult(result, { label: "cloud account cleanup" });
67-
}
68-
});
69-
return accountTransitionRef.current;
70-
};
37+
function clerkTokenReader(clerk: ClerkInstance): () => Promise<string | null> {
38+
return async () =>
39+
clerk.session ? await clerk.session.getToken(resolveRelayClerkTokenOptions()) : null;
40+
}
7141

72-
if (!isSignedIn || !userId) {
73-
deactivateManagedRelayAuthentication();
74-
if (previousAccount !== null) {
75-
void queueAccountCleanup();
76-
}
77-
} else {
78-
const tokenProvider = () => getToken(resolveRelayClerkTokenOptions());
79-
const activateSession = () => {
80-
if (!cancelled) {
81-
activateManagedRelayAuthentication(userId, tokenProvider);
82-
}
83-
};
84-
const activateAfterTransition = (transition: Promise<void>) => {
85-
void (async () => {
86-
const result = await settlePromise(async () => {
87-
await transition;
88-
activateSession();
89-
});
90-
reportAtomCommandResult(result, { label: "cloud account activation" });
91-
})();
92-
};
93-
if (previousAccount !== undefined && previousAccount !== null && previousAccount !== userId) {
94-
deactivateManagedRelayAuthentication();
95-
activateAfterTransition(queueAccountCleanup());
96-
} else {
97-
activateAfterTransition(accountTransitionRef.current ?? Promise.resolve());
98-
}
42+
const managedRelayAccountService = createCloudAccountService<ClerkInstance>({
43+
deactivate: deactivateManagedRelayAuthentication,
44+
detach: deactivateManagedRelayAuthentication,
45+
cleanUp: async () => {
46+
const results = await Promise.all([
47+
runAtomCommand(appAtomRegistry, environmentCatalog.removeRelayEnvironments, undefined, {
48+
reportFailure: false,
49+
reportDefect: false,
50+
}),
51+
settleAsyncResult(() =>
52+
runtime.runPromiseExit(
53+
ManagedRelay.ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)),
54+
),
55+
),
56+
]);
57+
for (const result of results) {
58+
reportAtomCommandResult(result, { label: "cloud account cleanup" });
9959
}
100-
return () => {
101-
cancelled = true;
102-
};
103-
}, [getToken, isLoaded, isSignedIn, removeRelayEnvironments, userId]);
104-
105-
useEffect(() => () => deactivateManagedRelayAuthentication(), []);
60+
},
61+
activate: ({ source, accountId }) =>
62+
activateManagedRelayAuthentication(accountId, clerkTokenReader(source)),
63+
});
10664

65+
export function ManagedRelayAuthProvider({ children }: { readonly children: ReactNode }) {
66+
// Render-time attach: ClerkProvider lazy-loads clerk-js, so its context is the
67+
// earliest place the instance exists. attach is idempotent, and IsomorphicClerk
68+
// queues listeners until load, so emissions and their atom writes arrive after
69+
// render.
70+
const clerk = useClerk();
71+
managedRelayAccountService.attach(clerk);
72+
publishManagedClerk(clerk);
10773
return children;
10874
}

‎apps/web/src/cloud/managedClerk.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import type { useClerk } from "@clerk/react";
2+
3+
export type ManagedClerk = ReturnType<typeof useClerk>;
4+
5+
let publish: (clerk: ManagedClerk) => void = () => undefined;
6+
const managedClerk = new Promise<ManagedClerk>((resolve) => {
7+
publish = resolve;
8+
});
9+
10+
/** Called by ManagedRelayAuthProvider, the first place the instance exists. */
11+
export function publishManagedClerk(clerk: ManagedClerk): void {
12+
publish(clerk);
13+
}
14+
15+
/**
16+
* Resolves with the Clerk instance once ClerkProvider renders, for code that
17+
* runs outside React (route hooks). Type-only Clerk import: route files stay
18+
* free of Clerk bytes, and in cloudless mode this simply never resolves.
19+
*/
20+
export function whenManagedClerk(): Promise<ManagedClerk> {
21+
return managedClerk;
22+
}

0 commit comments

Comments
 (0)