The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { useAtomMount } from "@effect/atom-react"; |
| 2 | import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; |
| 3 | |
| 4 | import { EnvironmentProject, EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; |
| 5 | import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime"; |
| 6 | import { |
| 7 | createVcsStatusRevalidationAtomFamily, |
| 8 | type GitActionRequestInput, |
| 9 | type VcsActionOperation, |
| 10 | type VcsRef, |
| 11 | } from "@t3tools/client-runtime/state/vcs"; |
| 12 | import { |
| 13 | AuthOrchestrationOperateScope, |
| 14 | AuthSourceControlWriteScope, |
| 15 | EnvironmentAuthorizationError, |
| 16 | type GitRunStackedActionResult, |
| 17 | } from "@t3tools/contracts"; |
| 18 | import { |
| 19 | dedupeRemoteBranchesWithLocalMatches, |
| 20 | sanitizeFeatureBranchName, |
| 21 | } from "@t3tools/shared/git"; |
| 22 | import * as Cause from "effect/Cause"; |
| 23 | import { msg } from "gt-react-native"; |
| 24 | import { m } from "../i18n/messages"; |
| 25 | import { AsyncResult } from "effect/reactivity"; |
| 26 | |
| 27 | import { useBranches } from "./queries"; |
| 28 | import { threadEnvironment } from "./threads"; |
| 29 | import { vcsActionManager, vcsEnvironment } from "./vcs"; |
| 30 | import { uuidv4 } from "../lib/uuid"; |
| 31 | import { appAtomRegistry } from "./atom-registry"; |
| 32 | import { readEnvironmentScope, useEnvironmentScope } from "./session"; |
| 33 | import { |
| 34 | environmentConnectedAtom, |
| 35 | setPendingConnectionError, |
| 36 | } from "./use-remote-environment-registry"; |
| 37 | import { useAtomCommand } from "./use-atom-command"; |
| 38 | import { showGitActionResult } from "./use-vcs-action-state"; |
| 39 | import { useThreadSelection } from "./use-thread-selection"; |
| 40 | import { useSelectedThreadWorktree } from "./use-selected-thread-worktree"; |
| 41 | |
| 42 | function refreshFailureMessage(cause: Cause.Cause<unknown>): string { |
| 43 | const error = Cause.squash(cause); |
| 44 | return errorDisplayMessage(error, m) ?? m(msg("Failed to refresh git status.")); |
| 45 | } |
| 46 | |
| 47 | // Selecting a thread or reconnecting its environment refreshes the checkout's |
| 48 | // status once, shared by every sheet that shows it. |
| 49 | const selectedThreadStatusRevalidation = createVcsStatusRevalidationAtomFamily({ |
| 50 | refreshStatus: vcsEnvironment.refreshStatus, |
| 51 | connected: environmentConnectedAtom, |
| 52 | onRefreshed: (result) => |
| 53 | setPendingConnectionError( |
| 54 | AsyncResult.isFailure(result) ? refreshFailureMessage(result.cause) : null, |
| 55 | ), |
| 56 | }); |
| 57 | |
| 58 | export function useSelectedThreadGitActions() { |
| 59 | const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, { |
| 60 | reportFailure: false, |
| 61 | }); |
| 62 | const readRefs = useAtomCommand(vcsEnvironment.readRefs, { reportFailure: false }); |
| 63 | const refreshStatus = useAtomCommand(vcsEnvironment.refreshStatus, { reportFailure: false }); |
| 64 | const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false }); |
| 65 | const createRef = useAtomCommand(vcsEnvironment.createRef, { reportFailure: false }); |
| 66 | const createWorktree = useAtomCommand(vcsEnvironment.createWorktree, { reportFailure: false }); |
| 67 | const pull = useAtomCommand(vcsEnvironment.pull, { reportFailure: false }); |
| 68 | const { selectedThread, selectedThreadProject } = useThreadSelection(); |
| 69 | const canWriteSourceControl = useEnvironmentScope( |
| 70 | selectedThread?.environmentId ?? null, |
| 71 | AuthSourceControlWriteScope, |
| 72 | ); |
| 73 | const canOperateThread = useEnvironmentScope( |
| 74 | selectedThread?.environmentId ?? null, |
| 75 | AuthOrchestrationOperateScope, |
| 76 | ); |
| 77 | const canChangeThreadBranch = canWriteSourceControl && canOperateThread; |
| 78 | const { selectedThreadCwd, selectedThreadWorktreePath } = useSelectedThreadWorktree(); |
| 79 | const runStackedAction = useAtomCommand( |
| 80 | vcsActionManager.runStackedAction({ |
| 81 | environmentId: selectedThread?.environmentId ?? null, |
| 82 | cwd: selectedThreadCwd, |
| 83 | }), |
| 84 | { reportFailure: false }, |
| 85 | ); |
| 86 | |
| 87 | const selectedThreadGitRootCwd = selectedThreadProject?.workspaceRoot ?? null; |
| 88 | const branchTarget = { |
| 89 | environmentId: selectedThread?.environmentId ?? null, |
| 90 | cwd: selectedThreadGitRootCwd, |
| 91 | query: null, |
| 92 | }; |
| 93 | const branchState = useBranches(branchTarget); |
| 94 | const updateThreadGitContext = async ( |
| 95 | thread: NonNullable<typeof selectedThread>, |
| 96 | nextState: { |
| 97 | readonly branch?: string | null; |
| 98 | readonly worktreePath?: string | null; |
| 99 | }, |
| 100 | ) => { |
| 101 | if (!readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope)) { |
| 102 | return AsyncResult.failure<never, EnvironmentAuthorizationError>( |
| 103 | Cause.fail( |
| 104 | new EnvironmentAuthorizationError({ |
| 105 | requiredScope: AuthOrchestrationOperateScope, |
| 106 | message: m(msg("This connection cannot update the thread's branch.")), |
| 107 | }), |
| 108 | ), |
| 109 | ); |
| 110 | } |
| 111 | return updateThreadMetadata({ |
| 112 | environmentId: thread.environmentId, |
| 113 | input: { |
| 114 | threadId: thread.id, |
| 115 | ...(nextState.branch !== undefined ? { branch: nextState.branch } : {}), |
| 116 | ...(nextState.worktreePath !== undefined ? { worktreePath: nextState.worktreePath } : {}), |
| 117 | }, |
| 118 | }); |
| 119 | }; |
| 120 | |
| 121 | const refreshSelectedThreadGitStatus = async (options?: { |
| 122 | readonly quiet?: boolean; |
| 123 | readonly cwd?: string | null; |
| 124 | }) => { |
| 125 | if (!selectedThread || !selectedThreadProject) { |
| 126 | return null; |
| 127 | } |
| 128 | |
| 129 | const cwd = options?.cwd ?? selectedThreadCwd; |
| 130 | if (!cwd) { |
| 131 | return null; |
| 132 | } |
| 133 | |
| 134 | const target = { environmentId: selectedThread.environmentId, cwd }; |
| 135 | const execute = () => |
| 136 | refreshStatus({ |
| 137 | environmentId: selectedThread.environmentId, |
| 138 | input: { cwd }, |
| 139 | }); |
| 140 | const result = options?.quiet |
| 141 | ? await execute() |
| 142 | : await vcsActionManager.track( |
| 143 | appAtomRegistry, |
| 144 | target, |
| 145 | { |
| 146 | operation: "refresh_status", |
| 147 | label: m(msg("Refreshing source control status")), |
| 148 | }, |
| 149 | execute, |
| 150 | ); |
| 151 | if (AsyncResult.isFailure(result)) { |
| 152 | setPendingConnectionError(refreshFailureMessage(result.cause)); |
| 153 | return null; |
| 154 | } |
| 155 | setPendingConnectionError(null); |
| 156 | return result.value; |
| 157 | }; |
| 158 | |
| 159 | useAtomMount( |
| 160 | selectedThreadStatusRevalidation( |
| 161 | selectedThread && selectedThreadProject && selectedThreadCwd |
| 162 | ? { environmentId: selectedThread.environmentId, cwd: selectedThreadCwd } |
| 163 | : null, |
| 164 | ), |
| 165 | ); |
| 166 | |
| 167 | const runSelectedThreadGitMutation = async <T, E>( |
| 168 | operation: VcsActionOperation, |
| 169 | label: string, |
| 170 | execute: (input: { |
| 171 | readonly thread: EnvironmentThreadShell; |
| 172 | readonly project: EnvironmentProject; |
| 173 | readonly cwd: string; |
| 174 | }) => Promise<AtomCommandResult<T, E>>, |
| 175 | options?: { readonly managedExternally?: boolean; readonly changesThreadBranch?: boolean }, |
| 176 | ): Promise<T | null> => { |
| 177 | if ( |
| 178 | !selectedThread || |
| 179 | !selectedThreadProject || |
| 180 | !selectedThreadCwd || |
| 181 | !readEnvironmentScope(selectedThread.environmentId, AuthSourceControlWriteScope) || |
| 182 | (options?.changesThreadBranch === true && |
| 183 | !readEnvironmentScope(selectedThread.environmentId, AuthOrchestrationOperateScope)) |
| 184 | ) { |
| 185 | return null; |
| 186 | } |
| 187 | |
| 188 | const target = { |
| 189 | environmentId: selectedThread.environmentId, |
| 190 | cwd: selectedThreadCwd, |
| 191 | }; |
| 192 | setPendingConnectionError(null); |
| 193 | const run = () => |
| 194 | execute({ |
| 195 | thread: selectedThread, |
| 196 | project: selectedThreadProject, |
| 197 | cwd: selectedThreadCwd, |
| 198 | }); |
| 199 | const result = |
| 200 | options?.managedExternally === true |
| 201 | ? await run() |
| 202 | : await vcsActionManager.track(appAtomRegistry, target, { operation, label }, run); |
| 203 | if (AsyncResult.isFailure(result)) { |
| 204 | const error = Cause.squash(result.cause); |
| 205 | const message = errorDisplayMessage(error, m) ?? m(msg("Git action failed.")); |
| 206 | setPendingConnectionError(message); |
| 207 | showGitActionResult({ |
| 208 | type: "error", |
| 209 | title: m(msg("Git action failed")), |
| 210 | description: message, |
| 211 | }); |
| 212 | return null; |
| 213 | } |
| 214 | return result.value; |
| 215 | }; |
| 216 | |
| 217 | const refreshSelectedThreadBranches = async (): Promise<ReadonlyArray<VcsRef> | null> => { |
| 218 | if (branchTarget.environmentId === null || branchTarget.cwd === null) return null; |
| 219 | const result = await readRefs({ |
| 220 | environmentId: branchTarget.environmentId, |
| 221 | input: { cwd: branchTarget.cwd, limit: 100, refresh: true }, |
| 222 | }); |
| 223 | if (AsyncResult.isFailure(result)) { |
| 224 | const error = Cause.squash(result.cause); |
| 225 | const message = errorDisplayMessage(error, m) ?? m(msg("Failed to refresh branches.")); |
| 226 | setPendingConnectionError(message); |
| 227 | showGitActionResult({ |
| 228 | type: "error", |
| 229 | title: m(msg("Git action failed")), |
| 230 | description: message, |
| 231 | }); |
| 232 | return null; |
| 233 | } |
| 234 | setPendingConnectionError(null); |
| 235 | return dedupeRemoteBranchesWithLocalMatches(result.value.refs).filter( |
| 236 | (branch) => !branch.isRemote, |
| 237 | ); |
| 238 | }; |
| 239 | |
| 240 | const syncSelectedThreadBranchState = async (input: { |
| 241 | readonly thread: EnvironmentThreadShell; |
| 242 | readonly cwd: string; |
| 243 | readonly nextThreadState?: { |
| 244 | readonly branch?: string | null; |
| 245 | readonly worktreePath?: string | null; |
| 246 | }; |
| 247 | }): Promise<AtomCommandResult<void, unknown>> => { |
| 248 | // Git already changed; refresh even if metadata updates fail so the sheet shows the current branch. |
| 249 | const updateResult = input.nextThreadState |
| 250 | ? await updateThreadGitContext(input.thread, input.nextThreadState) |
| 251 | : AsyncResult.success(undefined); |
| 252 | branchState.refresh(); |
| 253 | await refreshSelectedThreadGitStatus({ quiet: true, cwd: input.cwd }); |
| 254 | return AsyncResult.isFailure(updateResult) |
| 255 | ? AsyncResult.failure(updateResult.cause) |
| 256 | : AsyncResult.success(undefined); |
| 257 | }; |
| 258 | |
| 259 | const onCheckoutSelectedThreadBranch = async (branch: string) => { |
| 260 | return runSelectedThreadGitMutation( |
| 261 | "switch_ref", |
| 262 | m(msg("Switching branch")), |
| 263 | async ({ thread, cwd }) => { |
| 264 | const result = await switchRef({ |
| 265 | environmentId: thread.environmentId, |
| 266 | input: { cwd, refName: branch }, |
| 267 | }); |
| 268 | if (AsyncResult.isFailure(result)) { |
| 269 | return result; |
| 270 | } |
| 271 | const syncResult = await syncSelectedThreadBranchState({ |
| 272 | thread, |
| 273 | cwd, |
| 274 | nextThreadState: { |
| 275 | branch: result.value.refName ?? thread.branch, |
| 276 | worktreePath: selectedThreadWorktreePath, |
| 277 | }, |
| 278 | }); |
| 279 | return AsyncResult.isFailure(syncResult) ? AsyncResult.failure(syncResult.cause) : result; |
| 280 | }, |
| 281 | { changesThreadBranch: true }, |
| 282 | ); |
| 283 | }; |
| 284 | |
| 285 | const onCreateSelectedThreadBranch = async (branch: string) => { |
| 286 | return runSelectedThreadGitMutation( |
| 287 | "create_ref", |
| 288 | m(msg("Creating branch")), |
| 289 | async ({ thread, cwd }) => { |
| 290 | const result = await createRef({ |
| 291 | environmentId: thread.environmentId, |
| 292 | input: { cwd, refName: branch, switchRef: true }, |
| 293 | }); |
| 294 | if (AsyncResult.isFailure(result)) { |
| 295 | return result; |
| 296 | } |
| 297 | const syncResult = await syncSelectedThreadBranchState({ |
| 298 | thread, |
| 299 | cwd, |
| 300 | nextThreadState: { |
| 301 | branch: result.value.refName ?? thread.branch, |
| 302 | worktreePath: selectedThreadWorktreePath, |
| 303 | }, |
| 304 | }); |
| 305 | return AsyncResult.isFailure(syncResult) ? AsyncResult.failure(syncResult.cause) : result; |
| 306 | }, |
| 307 | { changesThreadBranch: true }, |
| 308 | ); |
| 309 | }; |
| 310 | |
| 311 | const onCreateSelectedThreadWorktree = async (nextWorktree: { |
| 312 | readonly baseBranch: string; |
| 313 | readonly newBranch: string; |
| 314 | }) => { |
| 315 | return runSelectedThreadGitMutation( |
| 316 | "create_worktree", |
| 317 | m(msg("Creating worktree")), |
| 318 | async ({ thread, project }) => { |
| 319 | const result = await createWorktree({ |
| 320 | environmentId: thread.environmentId, |
| 321 | input: { |
| 322 | cwd: project.workspaceRoot, |
| 323 | refName: nextWorktree.baseBranch, |
| 324 | newRefName: sanitizeFeatureBranchName(nextWorktree.newBranch), |
| 325 | path: null, |
| 326 | }, |
| 327 | }); |
| 328 | if (AsyncResult.isFailure(result)) { |
| 329 | return result; |
| 330 | } |
| 331 | const syncResult = await syncSelectedThreadBranchState({ |
| 332 | thread, |
| 333 | cwd: result.value.worktree.path, |
| 334 | nextThreadState: { |
| 335 | branch: result.value.worktree.refName, |
| 336 | worktreePath: result.value.worktree.path, |
| 337 | }, |
| 338 | }); |
| 339 | return AsyncResult.isFailure(syncResult) ? AsyncResult.failure(syncResult.cause) : result; |
| 340 | }, |
| 341 | { changesThreadBranch: true }, |
| 342 | ); |
| 343 | }; |
| 344 | |
| 345 | const onPullSelectedThreadBranch = async () => { |
| 346 | await runSelectedThreadGitMutation( |
| 347 | "pull", |
| 348 | m(msg("Pulling latest changes")), |
| 349 | async ({ thread, cwd }) => { |
| 350 | const result = await pull({ |
| 351 | environmentId: thread.environmentId, |
| 352 | input: { cwd }, |
| 353 | }); |
| 354 | if (AsyncResult.isFailure(result)) { |
| 355 | return result; |
| 356 | } |
| 357 | await refreshSelectedThreadGitStatus({ quiet: true, cwd }); |
| 358 | showGitActionResult({ |
| 359 | type: "success", |
| 360 | title: |
| 361 | result.value.status === "skipped_up_to_date" |
| 362 | ? m(msg("Already up to date")) |
| 363 | : m(msg("Pulled latest on {branch}", { branch: result.value.refName })), |
| 364 | }); |
| 365 | return result; |
| 366 | }, |
| 367 | ); |
| 368 | }; |
| 369 | |
| 370 | const onRunSelectedThreadGitAction = async ( |
| 371 | input: GitActionRequestInput, |
| 372 | ): Promise<GitRunStackedActionResult | null> => { |
| 373 | const actionId = uuidv4(); |
| 374 | return await runSelectedThreadGitMutation( |
| 375 | "run_change_request", |
| 376 | m(msg("Running source control action")), |
| 377 | async ({ thread, cwd }) => { |
| 378 | const result = await runStackedAction({ |
| 379 | actionId, |
| 380 | action: input.action, |
| 381 | ...(input.commitMessage ? { commitMessage: input.commitMessage } : {}), |
| 382 | ...(input.featureBranch ? { featureBranch: input.featureBranch } : {}), |
| 383 | ...(input.filePaths?.length ? { filePaths: [...input.filePaths] } : {}), |
| 384 | threadId: thread.id, |
| 385 | }); |
| 386 | if (AsyncResult.isFailure(result)) { |
| 387 | return result; |
| 388 | } |
| 389 | |
| 390 | if (result.value.branch.status === "created" && result.value.branch.name) { |
| 391 | const syncResult = await syncSelectedThreadBranchState({ |
| 392 | thread, |
| 393 | cwd, |
| 394 | nextThreadState: { |
| 395 | branch: result.value.branch.name, |
| 396 | worktreePath: selectedThreadWorktreePath, |
| 397 | }, |
| 398 | }); |
| 399 | if (AsyncResult.isFailure(syncResult)) { |
| 400 | return AsyncResult.failure(syncResult.cause); |
| 401 | } |
| 402 | } else { |
| 403 | await refreshSelectedThreadGitStatus({ quiet: true, cwd }); |
| 404 | } |
| 405 | showGitActionResult({ |
| 406 | type: "success", |
| 407 | title: result.value.toast.title, |
| 408 | description: result.value.toast.description, |
| 409 | prUrl: result.value.toast.cta.kind === "open_pr" ? result.value.toast.cta.url : undefined, |
| 410 | }); |
| 411 | return result; |
| 412 | }, |
| 413 | { managedExternally: true, changesThreadBranch: input.featureBranch === true }, |
| 414 | ); |
| 415 | }; |
| 416 | |
| 417 | return { |
| 418 | canWriteSourceControl, |
| 419 | canChangeThreadBranch, |
| 420 | refreshSelectedThreadGitStatus, |
| 421 | refreshSelectedThreadBranches, |
| 422 | onCheckoutSelectedThreadBranch, |
| 423 | onCreateSelectedThreadBranch, |
| 424 | onCreateSelectedThreadWorktree, |
| 425 | onPullSelectedThreadBranch, |
| 426 | onRunSelectedThreadGitAction, |
| 427 | }; |
| 428 | } |