The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import * as Dialog from "../../components/ui/Dialog"; |
| 3 | import { |
| 4 | StackActions, |
| 5 | type NavigationState, |
| 6 | type PartialState, |
| 7 | type StackActionType, |
| 8 | } from "@react-navigation/native"; |
| 9 | import { availableScratchWorkspaceRoot } from "@t3tools/client-runtime/operations/projects"; |
| 10 | import { |
| 11 | findPromptLinkProjects, |
| 12 | findPromptLinkPullRequestThread, |
| 13 | resolvePromptLinkModelSelection, |
| 14 | } from "@t3tools/client-runtime/prompt-links"; |
| 15 | import { |
| 16 | executeAtomQuery, |
| 17 | isAtomCommandInterrupted, |
| 18 | runAtomCommand, |
| 19 | squashAtomCommandFailure, |
| 20 | } from "@t3tools/client-runtime/state/runtime"; |
| 21 | import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; |
| 22 | import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; |
| 23 | import type { |
| 24 | LinkedPrompt, |
| 25 | PromptLinkPullRequest, |
| 26 | PromptLinkRepository, |
| 27 | } from "@t3tools/shared/promptLinks"; |
| 28 | import { parseNewThreadLink } from "@t3tools/shared/promptLinksCopy"; |
| 29 | import { Atom, type AsyncResult } from "effect/reactivity"; |
| 30 | import { msg } from "gt-react-native"; |
| 31 | |
| 32 | import { m } from "../../i18n/messages"; |
| 33 | import { findLinkedRoute, findStackRoute, updateLinkedRoute } from "../../lib/appLinking"; |
| 34 | import { rootNavigationRef } from "../../lib/rootNavigation"; |
| 35 | import { scopedThreadKey } from "../../lib/scopedEntities"; |
| 36 | import { appAtomRegistry } from "../../state/atom-registry"; |
| 37 | import { environmentProjects, projectEnvironment } from "../../state/projects"; |
| 38 | import { composerPullRequests } from "../../state/pull-requests"; |
| 39 | import { environmentServerConfigsAtom } from "../../state/server"; |
| 40 | import { environmentThreadShells } from "../../state/threads"; |
| 41 | import { |
| 42 | createNewTaskDraft, |
| 43 | setComposerDraftText, |
| 44 | updateComposerDraftSettings, |
| 45 | waitForComposerDraftsLoaded, |
| 46 | } from "../../state/use-composer-drafts"; |
| 47 | import { workspaceConnections, workspaceStateAtom } from "../../state/workspace"; |
| 48 | import { applyLinkedPromptToThreadDraft, showPromptLinkNotice } from "./prompt-link-actions"; |
| 49 | import { |
| 50 | latestThreadEnvironmentIds, |
| 51 | promptLinkNotice, |
| 52 | promptLinkRepositoryName, |
| 53 | promptLinkScratchEnvironmentId, |
| 54 | promptLinkSearchFromParams, |
| 55 | stepPendingPromptLink, |
| 56 | withoutPromptLinkParams, |
| 57 | } from "./prompt-link-model"; |
| 58 | |
| 59 | // Found at any depth, both in the parsed link and on the live stack, so the two never disagree on |
| 60 | // whether the link has landed. |
| 61 | const NEW_TASK_ROUTE = "NewTaskProject"; |
| 62 | const NEW_TASK_ROUTES = [NEW_TASK_ROUTE]; |
| 63 | |
| 64 | type LinkedDraftRequest = { |
| 65 | readonly prompt: LinkedPrompt | null; |
| 66 | readonly provider: string | null; |
| 67 | readonly model: string | null; |
| 68 | readonly pullRequest: PromptLinkPullRequest | null; |
| 69 | }; |
| 70 | |
| 71 | // A cold launch from a link has no projects or threads yet. Matching then would offer to clone a |
| 72 | // repository the user already has. |
| 73 | const shellsSettledAtom = Atom.make((get) => { |
| 74 | const workspace = get(workspaceStateAtom); |
| 75 | return !( |
| 76 | workspace.isLoadingConnections || |
| 77 | workspace.hasPendingShellSnapshot || |
| 78 | // A machine still connecting may hold the repository or thread. One that keeps failing to |
| 79 | // reconnect has settled offline, and must not hold every link. |
| 80 | workspace.connectingEnvironments.some( |
| 81 | (environment) => |
| 82 | environment.connectionState === "connecting" || environment.connectionError === null, |
| 83 | ) |
| 84 | ); |
| 85 | }).pipe(Atom.withLabel("mobile:prompt-link-shells-settled")); |
| 86 | |
| 87 | let pendingLink: string | null = null; |
| 88 | let stopWaitingForShells: (() => void) | null = null; |
| 89 | |
| 90 | /** |
| 91 | * `new?prompt=…&repo=…` drops its params as it arrives, so the screen never sees them and each |
| 92 | * opening resolves once. It resolves when its screen is on the navigation state that follows and |
| 93 | * the shells have settled; a newer link replaces one still waiting. |
| 94 | */ |
| 95 | export function takeNewTaskPromptLink( |
| 96 | state: PartialState<NavigationState> | undefined, |
| 97 | ): PartialState<NavigationState> | undefined { |
| 98 | const route = findLinkedRoute(state, NEW_TASK_ROUTES); |
| 99 | const search = promptLinkSearchFromParams( |
| 100 | route?.params as Readonly<Record<string, unknown>> | undefined, |
| 101 | ); |
| 102 | if (search === null) return state; |
| 103 | pendingLink = search; |
| 104 | return updateLinkedRoute(state, NEW_TASK_ROUTES, (linked) => ({ |
| 105 | ...linked, |
| 106 | params: withoutPromptLinkParams(linked.params), |
| 107 | })); |
| 108 | } |
| 109 | |
| 110 | /** Wired to the navigation container's state changes. */ |
| 111 | export function resolvePendingNewTaskPromptLink(state: NavigationState | undefined): void { |
| 112 | if (pendingLink === null) return; |
| 113 | const step = stepPendingPromptLink(pendingLink, { |
| 114 | // A screen pushed above New task (such as Add project) drops the link, so it never lands |
| 115 | // over the wrong screen. |
| 116 | screenOnStack: findStackRoute(state, NEW_TASK_ROUTE)?.focused === true, |
| 117 | ready: appAtomRegistry.get(shellsSettledAtom), |
| 118 | }); |
| 119 | if (step.pending === null) dropPendingLink(); |
| 120 | else pendingLink = step.pending; |
| 121 | if (step.resolve !== null) resolveLink(step.resolve); |
| 122 | else if (step.pending !== null) { |
| 123 | stopWaitingForShells ??= appAtomRegistry.subscribe(shellsSettledAtom, (settled) => { |
| 124 | if (settled) resolvePendingNewTaskPromptLink(rootNavigationRef.getRootState()); |
| 125 | }); |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | function dropPendingLink(): void { |
| 130 | pendingLink = null; |
| 131 | stopWaitingForShells?.(); |
| 132 | stopWaitingForShells = null; |
| 133 | } |
| 134 | |
| 135 | /** Dispatches as the new-task screen would, so `replace` swaps that screen out. */ |
| 136 | function dispatchFromNewTask(action: StackActionType): void { |
| 137 | const root = rootNavigationRef.getRootState(); |
| 138 | const screen = findStackRoute(root, NEW_TASK_ROUTE); |
| 139 | const target = screen?.navigatorKey ?? root?.key; |
| 140 | rootNavigationRef.dispatch({ |
| 141 | ...action, |
| 142 | ...(target ? { target } : {}), |
| 143 | ...(screen ? { source: screen.routeKey } : {}), |
| 144 | }); |
| 145 | } |
| 146 | |
| 147 | function runQuery<A, E>(atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>) { |
| 148 | return executeAtomQuery(appAtomRegistry, atom, { |
| 149 | label: atom.label?.[0] ?? "atom query", |
| 150 | reportFailure: false, |
| 151 | }); |
| 152 | } |
| 153 | |
| 154 | function writeDraft( |
| 155 | draftKey: string, |
| 156 | environmentId: EnvironmentId, |
| 157 | request: LinkedDraftRequest, |
| 158 | ): boolean { |
| 159 | if (request.prompt) setComposerDraftText(draftKey, request.prompt.text); |
| 160 | if (request.provider === null) return false; |
| 161 | const resolved = resolvePromptLinkModelSelection( |
| 162 | appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.providers ?? [], |
| 163 | { provider: request.provider, model: request.model }, |
| 164 | ); |
| 165 | if (resolved) updateComposerDraftSettings(draftKey, { modelSelection: resolved.selection }); |
| 166 | return resolved?.exact !== true; |
| 167 | } |
| 168 | |
| 169 | function openThread( |
| 170 | thread: { readonly environmentId: EnvironmentId; readonly id: ThreadId }, |
| 171 | prompt: LinkedDraftRequest["prompt"], |
| 172 | ) { |
| 173 | dispatchFromNewTask( |
| 174 | StackActions.replace("Thread", { |
| 175 | environmentId: String(thread.environmentId), |
| 176 | threadId: String(thread.id), |
| 177 | }), |
| 178 | ); |
| 179 | if (prompt) { |
| 180 | void applyLinkedPromptToThreadDraft( |
| 181 | scopedThreadKey(thread.environmentId, thread.id), |
| 182 | prompt, |
| 183 | promptLinkNotice({ hiddenCharacters: prompt.hiddenCharacters }), |
| 184 | ); |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | // A pull request's thread can be an older settled thread no shell holds, so ask every |
| 189 | // connected environment with the repository. A lookup on another one would wait forever. |
| 190 | async function findServerPullRequestThread( |
| 191 | projects: ReadonlyArray<EnvironmentProject>, |
| 192 | pullRequest: PromptLinkPullRequest, |
| 193 | ) { |
| 194 | const connected = new Set( |
| 195 | appAtomRegistry |
| 196 | .get(workspaceConnections.environmentsAtom) |
| 197 | .filter((environment) => environment.connectionState === "connected") |
| 198 | .map((environment) => environment.environmentId), |
| 199 | ); |
| 200 | const lookups = projects |
| 201 | .filter((project) => connected.has(project.environmentId)) |
| 202 | .map(async (project) => { |
| 203 | const linked = await runQuery( |
| 204 | composerPullRequests.linkedThreadsUncached({ |
| 205 | environmentId: project.environmentId, |
| 206 | input: { |
| 207 | projectId: project.id, |
| 208 | repository: promptLinkRepositoryName(pullRequest), |
| 209 | number: pullRequest.number, |
| 210 | }, |
| 211 | }), |
| 212 | ); |
| 213 | const thread = |
| 214 | linked._tag === "Success" |
| 215 | ? linked.value.threads.find((candidate) => candidate.archivedAt === null) |
| 216 | : undefined; |
| 217 | return thread && { environmentId: project.environmentId, id: thread.id }; |
| 218 | }); |
| 219 | // The most recent project wins without waiting for the lookups after it. |
| 220 | for (const lookup of lookups) { |
| 221 | const thread = await lookup; |
| 222 | if (thread) return thread; |
| 223 | } |
| 224 | return undefined; |
| 225 | } |
| 226 | |
| 227 | async function openProjectDraft(project: EnvironmentProject, request: LinkedDraftRequest) { |
| 228 | try { |
| 229 | await waitForComposerDraftsLoaded(); |
| 230 | } catch { |
| 231 | Dialog.alert( |
| 232 | m(msg("Could not open link")), |
| 233 | m(msg("Drafts could not be loaded, so the prompt was not added.")), |
| 234 | ); |
| 235 | return; |
| 236 | } |
| 237 | const draftKey = createNewTaskDraft({ |
| 238 | environmentId: project.environmentId, |
| 239 | projectId: project.id, |
| 240 | }); |
| 241 | let pullRequestUnavailable: number | null = null; |
| 242 | if (request.pullRequest) { |
| 243 | const detail = await runQuery( |
| 244 | composerPullRequests.detail({ |
| 245 | environmentId: project.environmentId, |
| 246 | input: { |
| 247 | projectId: project.id, |
| 248 | repository: promptLinkRepositoryName(request.pullRequest), |
| 249 | number: request.pullRequest.number, |
| 250 | }, |
| 251 | }), |
| 252 | ); |
| 253 | if (detail._tag === "Success") { |
| 254 | updateComposerDraftSettings(draftKey, { |
| 255 | workspaceSelection: { |
| 256 | mode: "worktree", |
| 257 | branch: detail.value.headBranch, |
| 258 | worktreePath: null, |
| 259 | startFromOrigin: false, |
| 260 | pullRequestReference: detail.value.url, |
| 261 | }, |
| 262 | }); |
| 263 | } else { |
| 264 | pullRequestUnavailable = request.pullRequest.number; |
| 265 | } |
| 266 | } |
| 267 | const modelUnavailable = writeDraft(draftKey, project.environmentId, request); |
| 268 | dispatchFromNewTask( |
| 269 | StackActions.push("Thread", { |
| 270 | draft: { |
| 271 | draftId: draftKey, |
| 272 | title: request.pullRequest |
| 273 | ? m(msg("PR #{number}", { number: request.pullRequest.number })) |
| 274 | : project.title, |
| 275 | }, |
| 276 | }), |
| 277 | ); |
| 278 | if (request.prompt || pullRequestUnavailable !== null || modelUnavailable) { |
| 279 | showPromptLinkNotice( |
| 280 | promptLinkNotice({ |
| 281 | hiddenCharacters: request.prompt?.hiddenCharacters ?? 0, |
| 282 | modelUnavailable, |
| 283 | pullRequestUnavailable, |
| 284 | }), |
| 285 | ); |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | async function openScratchDraft(request: LinkedDraftRequest) { |
| 290 | const serverConfigs = appAtomRegistry.get(environmentServerConfigsAtom); |
| 291 | const environmentId = promptLinkScratchEnvironmentId( |
| 292 | latestThreadEnvironmentIds(appAtomRegistry.get(environmentThreadShells.threadShellsAtom)), |
| 293 | appAtomRegistry |
| 294 | .get(workspaceConnections.environmentsAtom) |
| 295 | .filter( |
| 296 | (environment) => |
| 297 | availableScratchWorkspaceRoot( |
| 298 | environment.connectionState, |
| 299 | serverConfigs.get(environment.environmentId), |
| 300 | ) !== null, |
| 301 | ) |
| 302 | .map((environment) => environment.environmentId), |
| 303 | ); |
| 304 | if (environmentId === null) { |
| 305 | Dialog.alert( |
| 306 | m(msg("Could not start without a project")), |
| 307 | m(msg("No connected environment offers threads without a project.")), |
| 308 | ); |
| 309 | return; |
| 310 | } |
| 311 | const result = await runAtomCommand( |
| 312 | appAtomRegistry, |
| 313 | projectEnvironment.openScratch, |
| 314 | { environmentId, input: {} }, |
| 315 | { reportFailure: false }, |
| 316 | ); |
| 317 | if (result._tag === "Failure") { |
| 318 | if (!isAtomCommandInterrupted(result)) { |
| 319 | const error = squashAtomCommandFailure(result); |
| 320 | Dialog.alert( |
| 321 | m(msg("Could not start without a project")), |
| 322 | error instanceof Error |
| 323 | ? (errorDisplayMessage(error, m) ?? error.message) |
| 324 | : m(msg("The folder for threads without a project could not be created.")), |
| 325 | ); |
| 326 | } |
| 327 | return; |
| 328 | } |
| 329 | await openProjectDraft(result.value, { ...request, pullRequest: null }); |
| 330 | } |
| 331 | |
| 332 | function cloneRepository(repository: PromptLinkRepository, request: LinkedDraftRequest) { |
| 333 | // The clone screen lets the user pick another environment before cloning. |
| 334 | const environmentId = |
| 335 | appAtomRegistry.get(environmentProjects.projectsAtom)[0]?.environmentId ?? |
| 336 | appAtomRegistry.get(workspaceConnections.environmentsAtom)[0]?.environmentId ?? |
| 337 | null; |
| 338 | if (environmentId === null) { |
| 339 | Dialog.alert(m(msg("Could not clone")), m(msg("Connect an environment first."))); |
| 340 | return; |
| 341 | } |
| 342 | const prompt = |
| 343 | request.pullRequest === null && |
| 344 | appAtomRegistry.get(environmentServerConfigsAtom).has(environmentId) |
| 345 | ? request.prompt |
| 346 | : null; |
| 347 | const name = promptLinkRepositoryName(repository); |
| 348 | dispatchFromNewTask( |
| 349 | StackActions.push("AddProjectDestination", { |
| 350 | environmentId, |
| 351 | remoteUrl: `https://github.com/${name}.git`, |
| 352 | repositoryTitle: name, |
| 353 | repositoryName: repository.name, |
| 354 | ...(prompt ? { prompt: prompt.text } : {}), |
| 355 | }), |
| 356 | ); |
| 357 | if (!request.prompt) return; |
| 358 | showPromptLinkNotice( |
| 359 | [ |
| 360 | promptLinkNotice({ |
| 361 | hiddenCharacters: request.prompt.hiddenCharacters, |
| 362 | modelUnavailable: prompt !== null && request.provider !== null, |
| 363 | }), |
| 364 | prompt |
| 365 | ? m(msg("The prompt opens in a new task once the clone starts.")) |
| 366 | : m(msg("Open the link again after the clone to get the prompt.")), |
| 367 | ].join("\n\n"), |
| 368 | ); |
| 369 | } |
| 370 | |
| 371 | function resolveLink(linkSearch: string) { |
| 372 | const threads = appAtomRegistry.get(environmentThreadShells.threadShellsAtom); |
| 373 | const parsed = parseNewThreadLink(linkSearch, m); |
| 374 | if (!parsed.ok) { |
| 375 | Dialog.alert(m(msg("Could not open link")), parsed.error); |
| 376 | return; |
| 377 | } |
| 378 | const link = parsed.value; |
| 379 | const request: LinkedDraftRequest = |
| 380 | link.kind === "new" |
| 381 | ? { prompt: link.prompt, provider: link.provider, model: link.model, pullRequest: null } |
| 382 | : { prompt: link.prompt, provider: null, model: null, pullRequest: link.pullRequest }; |
| 383 | |
| 384 | if (link.kind === "pull-request") { |
| 385 | const thread = findPromptLinkPullRequestThread(threads, link.pullRequest); |
| 386 | if (thread) { |
| 387 | openThread(thread, link.prompt); |
| 388 | return; |
| 389 | } |
| 390 | } |
| 391 | |
| 392 | const repository = link.kind === "new" ? link.repository : link.pullRequest; |
| 393 | if (repository === null) { |
| 394 | void openScratchDraft(request); |
| 395 | return; |
| 396 | } |
| 397 | const lastActivity = new Map<string, string>(); |
| 398 | for (const thread of threads) { |
| 399 | const key = `${thread.environmentId}:${thread.projectId}`; |
| 400 | if (thread.updatedAt > (lastActivity.get(key) ?? "")) lastActivity.set(key, thread.updatedAt); |
| 401 | } |
| 402 | const activityOf = (project: EnvironmentProject) => |
| 403 | lastActivity.get(`${project.environmentId}:${project.id}`) ?? ""; |
| 404 | const projects = findPromptLinkProjects( |
| 405 | [...appAtomRegistry.get(environmentProjects.projectsAtom)].sort((left, right) => |
| 406 | activityOf(right).localeCompare(activityOf(left)), |
| 407 | ), |
| 408 | repository, |
| 409 | ); |
| 410 | const project = projects[0]; |
| 411 | if (project) { |
| 412 | const { pullRequest } = request; |
| 413 | void (async () => { |
| 414 | const thread = pullRequest && (await findServerPullRequestThread(projects, pullRequest)); |
| 415 | if (thread) openThread(thread, request.prompt); |
| 416 | else await openProjectDraft(project, request); |
| 417 | })(); |
| 418 | return; |
| 419 | } |
| 420 | Dialog.alert( |
| 421 | m(msg("You don't have {repository}", { repository: promptLinkRepositoryName(repository) })), |
| 422 | undefined, |
| 423 | [ |
| 424 | { text: m(msg("Cancel")), style: "cancel" }, |
| 425 | ...(request.prompt |
| 426 | ? [{ text: m(msg("Use without project")), onPress: () => void openScratchDraft(request) }] |
| 427 | : []), |
| 428 | { |
| 429 | text: m(msg("Clone", { $context: "verb, clones the repository" })), |
| 430 | onPress: () => cloneRepository(repository, request), |
| 431 | }, |
| 432 | ], |
| 433 | ); |
| 434 | } |