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, 04:45 UTC
| 1 | import { reportAtomCommandResult, settlePromise } from "../state/runtime.ts"; |
| 2 | |
| 3 | /** |
| 4 | * The slice of a Clerk instance the account service needs. Clerk emits on |
| 5 | * every resource change (token refreshes, profile edits), so the service |
| 6 | * dedupes emissions down to account changes. |
| 7 | */ |
| 8 | export interface CloudAccountSource { |
| 9 | readonly addListener: ( |
| 10 | listener: (resources: { |
| 11 | readonly client?: { readonly id?: string | null | undefined } | null | undefined; |
| 12 | readonly user?: { readonly id: string } | null | undefined; |
| 13 | }) => void, |
| 14 | ) => () => void; |
| 15 | } |
| 16 | |
| 17 | /** |
| 18 | * Clerk's load status cannot prove its API answered: offline it emits an |
| 19 | * id-less client, and a failed launch fetch emits a "client_init" placeholder |
| 20 | * built from the session cookie. Only a real /v1/client response has an id. |
| 21 | */ |
| 22 | const isClientFromClerkApi = ( |
| 23 | client: { readonly id?: string | null | undefined } | null | undefined, |
| 24 | ) => Boolean(client?.id) && client?.id !== "client_init"; |
| 25 | |
| 26 | interface CloudAccountSignIn { |
| 27 | readonly _tag: "SignIn"; |
| 28 | readonly accountId: string; |
| 29 | /** Signed-in account being replaced; its data is removed before activation. */ |
| 30 | readonly switchFromAccountId: string | null; |
| 31 | readonly isAccountTransition: boolean; |
| 32 | } |
| 33 | |
| 34 | export type CloudAccountStep = |
| 35 | | { readonly _tag: "None" } |
| 36 | | { |
| 37 | readonly _tag: "SignOut"; |
| 38 | /** Account whose data is removed; null removes data of any account. */ |
| 39 | readonly previousAccountId: string | null; |
| 40 | readonly isAccountTransition: boolean; |
| 41 | } |
| 42 | | CloudAccountSignIn; |
| 43 | |
| 44 | /** |
| 45 | * `previous` is undefined until Clerk's first emission. A first emission that |
| 46 | * is signed out still cleans up, so data left by an account that signed out |
| 47 | * while the app was closed does not linger. The service only plans that step |
| 48 | * once Clerk's API has confirmed the sign-out. |
| 49 | */ |
| 50 | export function planCloudAccountStep( |
| 51 | previous: string | null | undefined, |
| 52 | next: string | null, |
| 53 | ): CloudAccountStep { |
| 54 | if (previous === next) return { _tag: "None" }; |
| 55 | const isAccountTransition = previous !== undefined; |
| 56 | if (next === null) { |
| 57 | return { _tag: "SignOut", previousAccountId: previous ?? null, isAccountTransition }; |
| 58 | } |
| 59 | return { |
| 60 | _tag: "SignIn", |
| 61 | accountId: next, |
| 62 | switchFromAccountId: previous ?? null, |
| 63 | isAccountTransition, |
| 64 | }; |
| 65 | } |
| 66 | |
| 67 | export interface CloudAccountHandlers<S extends CloudAccountSource> { |
| 68 | /** Synchronously drops every credential so nothing reads the old account during cleanup. */ |
| 69 | readonly deactivate: () => void; |
| 70 | readonly cleanUp: (input: { |
| 71 | readonly source: S; |
| 72 | readonly accountId: string | null; |
| 73 | /** Whether `accountId` finished activating, so per-account registrations exist. */ |
| 74 | readonly wasActive: boolean; |
| 75 | }) => Promise<void>; |
| 76 | /** Async work that must finish before the session is visible (draft restore etc.). */ |
| 77 | readonly prepare?: (input: { |
| 78 | readonly source: S; |
| 79 | readonly accountId: string; |
| 80 | readonly isCurrent: () => boolean; |
| 81 | }) => Promise<void>; |
| 82 | readonly activate: (input: { |
| 83 | readonly source: S; |
| 84 | readonly accountId: string; |
| 85 | readonly isAccountTransition: boolean; |
| 86 | }) => void; |
| 87 | readonly onSignOutTransition?: () => void; |
| 88 | /** Releases credentials when the service stops observing a Clerk instance. */ |
| 89 | readonly detach: () => void; |
| 90 | } |
| 91 | |
| 92 | export type CloudAccountState = |
| 93 | | { readonly _tag: "Unobserved" } |
| 94 | | { readonly _tag: "SignedOut" } |
| 95 | | { readonly _tag: "Activating"; readonly accountId: string } |
| 96 | | { readonly _tag: "Active"; readonly accountId: string } |
| 97 | /** |
| 98 | * Activation rejected. The next emission for the same account retries the |
| 99 | * original step, so a transient failure recovers on Clerk's next resource |
| 100 | * change (token refreshes emit regularly) without re-requesting onboarding. |
| 101 | */ |
| 102 | | { |
| 103 | readonly _tag: "Failed"; |
| 104 | readonly accountId: string; |
| 105 | readonly step: CloudAccountSignIn; |
| 106 | readonly wasActive: boolean; |
| 107 | }; |
| 108 | |
| 109 | export interface CloudAccountService<S extends CloudAccountSource> { |
| 110 | /** |
| 111 | * Observes `source` until the returned function runs. Attaching while another |
| 112 | * source is attached detaches that one first. |
| 113 | */ |
| 114 | readonly attach: (source: S) => () => void; |
| 115 | readonly getState: () => CloudAccountState; |
| 116 | } |
| 117 | |
| 118 | export function createCloudAccountService<S extends CloudAccountSource>( |
| 119 | handlers: CloudAccountHandlers<S>, |
| 120 | ): CloudAccountService<S> { |
| 121 | let attached: { readonly source: S; readonly unsubscribe: () => void } | null = null; |
| 122 | let state: CloudAccountState = { _tag: "Unobserved" }; |
| 123 | // Bumped on every account change so a superseded activation never applies. |
| 124 | let generation = 0; |
| 125 | let tail: Promise<void> = Promise.resolve(); |
| 126 | |
| 127 | const enqueue = (label: string, operation: () => Promise<void>) => { |
| 128 | const run = tail.then(operation, operation); |
| 129 | tail = run.then( |
| 130 | () => undefined, |
| 131 | () => undefined, |
| 132 | ); |
| 133 | void settlePromise(() => run).then((result) => reportAtomCommandResult(result, { label })); |
| 134 | }; |
| 135 | |
| 136 | const observedAccount = (): string | null | undefined => { |
| 137 | switch (state._tag) { |
| 138 | case "Unobserved": |
| 139 | return undefined; |
| 140 | case "SignedOut": |
| 141 | return null; |
| 142 | default: |
| 143 | return state.accountId; |
| 144 | } |
| 145 | }; |
| 146 | |
| 147 | const activate = (source: S, step: CloudAccountSignIn, wasActive: boolean) => { |
| 148 | const activation = generation; |
| 149 | const isCurrent = () => activation === generation; |
| 150 | state = { _tag: "Activating", accountId: step.accountId }; |
| 151 | if (step.switchFromAccountId !== null) handlers.deactivate(); |
| 152 | enqueue("cloud account activation", async () => { |
| 153 | try { |
| 154 | if (step.switchFromAccountId !== null) { |
| 155 | await handlers.cleanUp({ source, accountId: step.switchFromAccountId, wasActive }); |
| 156 | } |
| 157 | if (!isCurrent()) return; |
| 158 | await handlers.prepare?.({ source, accountId: step.accountId, isCurrent }); |
| 159 | } catch (error) { |
| 160 | if (isCurrent()) state = { _tag: "Failed", accountId: step.accountId, step, wasActive }; |
| 161 | throw error; |
| 162 | } |
| 163 | if (!isCurrent()) return; |
| 164 | state = { _tag: "Active", accountId: step.accountId }; |
| 165 | handlers.activate({ |
| 166 | source, |
| 167 | accountId: step.accountId, |
| 168 | isAccountTransition: step.isAccountTransition, |
| 169 | }); |
| 170 | }); |
| 171 | }; |
| 172 | |
| 173 | const observe = (source: S, next: string | null) => { |
| 174 | const previousState = state; |
| 175 | if (previousState._tag === "Failed" && previousState.accountId === next) { |
| 176 | generation += 1; |
| 177 | activate(source, previousState.step, previousState.wasActive); |
| 178 | return; |
| 179 | } |
| 180 | const step = planCloudAccountStep(observedAccount(), next); |
| 181 | if (step._tag === "None") return; |
| 182 | generation += 1; |
| 183 | const wasActive = previousState._tag === "Active"; |
| 184 | |
| 185 | if (step._tag === "SignOut") { |
| 186 | state = { _tag: "SignedOut" }; |
| 187 | if (step.isAccountTransition) handlers.onSignOutTransition?.(); |
| 188 | handlers.deactivate(); |
| 189 | enqueue("cloud account cleanup", () => |
| 190 | handlers.cleanUp({ source, accountId: step.previousAccountId, wasActive }), |
| 191 | ); |
| 192 | return; |
| 193 | } |
| 194 | |
| 195 | activate(source, step, wasActive); |
| 196 | }; |
| 197 | |
| 198 | const detach = () => { |
| 199 | if (!attached) return; |
| 200 | attached.unsubscribe(); |
| 201 | attached = null; |
| 202 | generation += 1; |
| 203 | state = { _tag: "Unobserved" }; |
| 204 | handlers.detach(); |
| 205 | }; |
| 206 | |
| 207 | return { |
| 208 | attach(source) { |
| 209 | detach(); |
| 210 | const current = { |
| 211 | source, |
| 212 | unsubscribe: source.addListener((resources) => { |
| 213 | // Clerk reports `user: undefined` until it loads; pending sessions |
| 214 | // still carry a user and count as signed in. |
| 215 | if (resources.user === undefined) return; |
| 216 | const next = resources.user?.id ?? null; |
| 217 | // An unreachable Clerk API at launch looks signed out; stay unobserved |
| 218 | // until Clerk confirms it, so saved environments survive offline starts. |
| 219 | if ( |
| 220 | next === null && |
| 221 | state._tag === "Unobserved" && |
| 222 | !isClientFromClerkApi(resources.client) |
| 223 | ) { |
| 224 | return; |
| 225 | } |
| 226 | observe(source, next); |
| 227 | }), |
| 228 | }; |
| 229 | attached = current; |
| 230 | return () => { |
| 231 | if (attached === current) detach(); |
| 232 | }; |
| 233 | }, |
| 234 | getState: () => state, |
| 235 | }; |
| 236 | } |