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 * as Dialog from "../../components/ui/Dialog"; |
| 2 | import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; |
| 3 | import { useRememberThreadProject } from "./useRememberThreadProject"; |
| 4 | import { useOpenPullRequest } from "../../native/useOpenPullRequest"; |
| 5 | import { makeTurnCommandMetadata } from "../../lib/commandMetadata"; |
| 6 | import { buildProjectThreadStartTurnInput } from "../../lib/projectThreadStartTurn"; |
| 7 | import { useWorktreeSetup } from "./use-worktree-setup"; |
| 8 | import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup"; |
| 9 | import { AppBar } from "../../components/ui/AppBar"; |
| 10 | import { |
| 11 | StackActions, |
| 12 | useNavigation, |
| 13 | useRoute, |
| 14 | type StaticScreenProps, |
| 15 | } from "@react-navigation/native"; |
| 16 | import { |
| 17 | createContext, |
| 18 | use, |
| 19 | useEffect, |
| 20 | useEffectEvent, |
| 21 | useRef, |
| 22 | useState, |
| 23 | type ReactNode, |
| 24 | } from "react"; |
| 25 | import { useGT, useMessages } from "gt-react-native"; |
| 26 | import * as Option from "effect/Option"; |
| 27 | import { |
| 28 | AuthOrchestrationOperateScope, |
| 29 | AuthTerminalOperateScope, |
| 30 | AuthTerminalReadScope, |
| 31 | DEFAULT_SERVER_SETTINGS, |
| 32 | EnvironmentId, |
| 33 | isProviderNativeSubagentThread, |
| 34 | MessageId, |
| 35 | ThreadId, |
| 36 | type ProjectScript, |
| 37 | } from "@t3tools/contracts"; |
| 38 | import { |
| 39 | projectScriptCwd, |
| 40 | projectScriptRuntimeEnv, |
| 41 | projectScriptTerminalInput, |
| 42 | resolveProjectScripts, |
| 43 | } from "@t3tools/shared/projectScripts"; |
| 44 | import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView"; |
| 45 | import { useConnectionsReady } from "../../state/workspace"; |
| 46 | import { useEnvironmentShellReadiness } from "../../state/shell"; |
| 47 | import { restoredNewTaskDraftKey } from "../../state/new-task-draft-key"; |
| 48 | import { clearPendingThreadCreationOutcome } from "../../state/pending-thread-creation"; |
| 49 | import { recoverFailedThreadDraft } from "../../state/recover-failed-thread-draft"; |
| 50 | import { useEnvironmentQuery } from "../../state/query"; |
| 51 | import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state"; |
| 52 | import { vcsEnvironment } from "../../state/vcs"; |
| 53 | import { EmptyState } from "../../components/ui/EmptyState"; |
| 54 | import { LoadingScreen } from "../../components/LoadingScreen"; |
| 55 | import { scopedThreadKey } from "../../lib/scopedEntities"; |
| 56 | import { useDelayedStatus } from "../../lib/useDelayedStatus"; |
| 57 | import { connectionRetryLabel } from "./floating-working-status"; |
| 58 | import { scopeThreadRef } from "@t3tools/client-runtime/environment"; |
| 59 | import { useThreadShell } from "../../state/entities"; |
| 60 | import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass"; |
| 61 | import { connectionTone } from "../connection/connectionTone"; |
| 62 | import { runtimeConnectionErrorText } from "../connection/environmentStatusText"; |
| 63 | import { |
| 64 | useRemoteConnections, |
| 65 | useRemoteConnectionStatus, |
| 66 | useRemoteEnvironmentRuntime, |
| 67 | } from "../../state/use-remote-environment-registry"; |
| 68 | import { useKnownTerminalSessions } from "../../state/use-terminal-session"; |
| 69 | import { uuidv4 } from "../../lib/uuid"; |
| 70 | import { |
| 71 | isAtomCommandInterrupted, |
| 72 | squashAtomCommandFailure, |
| 73 | } from "@t3tools/client-runtime/state/runtime"; |
| 74 | import { readEnvironmentScope, useEnvironmentScope } from "../../state/session"; |
| 75 | import { useSelectedThreadDetailState } from "../../state/use-thread-detail"; |
| 76 | import { useThreadSelection } from "../../state/use-thread-selection"; |
| 77 | import { GitActionProgressOverlay } from "./GitActionProgressOverlay"; |
| 78 | import { |
| 79 | buildTerminalMenuSessions, |
| 80 | nextOpenTerminalId, |
| 81 | resolveProjectScriptTerminalId, |
| 82 | } from "../terminal/terminalMenu"; |
| 83 | import { |
| 84 | resolvePreferredThreadWorktreePath, |
| 85 | stagePendingTerminalLaunch, |
| 86 | } from "../terminal/terminalLaunchContext"; |
| 87 | import type { ThreadDetailScreenProps } from "./ThreadDetailScreen"; |
| 88 | import { ThreadScreenBinding, ThreadScreenFallback, ThreadScreenHost } from "./ThreadScreenHost"; |
| 89 | import { draftRouteIdentity } from "./thread-route-state"; |
| 90 | import { NewTaskDraftRouteScreen, type NewTaskDraftRouteParams } from "./NewTaskDraftRouteScreen"; |
| 91 | import { GitOverviewSheet } from "./git/GitOverviewSheet"; |
| 92 | import { useAtomCommand } from "../../state/use-atom-command"; |
| 93 | import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions"; |
| 94 | import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state"; |
| 95 | import { useSelectedThreadRequests } from "../../state/use-selected-thread-requests"; |
| 96 | import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree"; |
| 97 | import { useThreadComposerState } from "../../state/use-thread-composer-state"; |
| 98 | import { resolveMergeBackTargetThreadId } from "@t3tools/client-runtime/state/thread-relationships"; |
| 99 | import { resolveLatestMergeBackRun } from "@t3tools/client-runtime/state/thread-workflows"; |
| 100 | import { threadEnvironment } from "../../state/threads"; |
| 101 | import { |
| 102 | EMPTY_ENVIRONMENT_THREAD_STATE, |
| 103 | threadErrorText, |
| 104 | } from "@t3tools/client-runtime/state/threads"; |
| 105 | import { useProjects } from "../../state/entities"; |
| 106 | import { |
| 107 | projectThreadContentPresentation, |
| 108 | threadSyncStatusLabel, |
| 109 | } from "./threadContentPresentation"; |
| 110 | import { |
| 111 | Inspector, |
| 112 | useAdaptiveWorkspaceLayout, |
| 113 | useWorkspacePaneState, |
| 114 | } from "../layout/AdaptiveWorkspaceLayout"; |
| 115 | import { ThreadFileNavigatorPane } from "../files/thread-file-navigator-pane"; |
| 116 | import { InspectorSheetContext } from "../layout/workspace-inspector-sheet"; |
| 117 | import type { InspectorContent } from "../layout/inspector-panes"; |
| 118 | import { |
| 119 | threadDetailErrorIsCurrent, |
| 120 | threadRouteIsHydrating, |
| 121 | threadRouteOpensDraft, |
| 122 | } from "./thread-route-hydration"; |
| 123 | import { ThreadHeader } from "./ThreadHeader"; |
| 124 | import { resumeThread } from "./resume-thread"; |
| 125 | import { |
| 126 | useAndroidWorkspaceBack, |
| 127 | useWorkspaceBackNavigation, |
| 128 | } from "../layout/workspace/useAndroidWorkspaceNavigation"; |
| 129 | import { openSettings } from "../settings/settings-navigation"; |
| 130 | import { ThreadInspectorHeader, type ThreadInspectorPresentation } from "./thread-inspector-header"; |
| 131 | import { InspectorContentScope, ThreadInspectorPreview } from "./thread-inspector-preview"; |
| 132 | import { useStartSideChat } from "./useStartSideChat"; |
| 133 | import { useThreadStatusAnnouncements } from "./useThreadStatusAnnouncements"; |
| 134 | import type { ThreadInspectorMode, ThreadInspectorTarget } from "./thread-inspector-navigation"; |
| 135 | import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail"; |
| 136 | |
| 137 | function firstRouteParam(value: string | string[] | undefined): string | null { |
| 138 | const first = Array.isArray(value) ? value[0] : value; |
| 139 | return first === undefined || first.trim().length === 0 ? null : first; |
| 140 | } |
| 141 | |
| 142 | const RECONNECT_ERROR_DELAY_MS = 5_000; |
| 143 | |
| 144 | // The inspector pane's bar belongs to ThreadInspectorHeader; the fallback must not draw its own. |
| 145 | const InspectorHeaderShownContext = createContext(false); |
| 146 | |
| 147 | function ThreadRouteFallbackLayout(props: { readonly children: ReactNode }) { |
| 148 | const gt = useGT(); |
| 149 | const goBack = useWorkspaceBackNavigation(); |
| 150 | const inspectorHeaderShown = use(InspectorHeaderShownContext); |
| 151 | return ( |
| 152 | <ThreadScreenFallback |
| 153 | header={ |
| 154 | inspectorHeaderShown ? undefined : ( |
| 155 | <AppBar title={gt("Thread")} onBackToList={goBack} hideBottomBorder /> |
| 156 | ) |
| 157 | } |
| 158 | > |
| 159 | {props.children} |
| 160 | </ThreadScreenFallback> |
| 161 | ); |
| 162 | } |
| 163 | |
| 164 | function OpeningThreadLoadingScreen() { |
| 165 | const gt = useGT(); |
| 166 | return ( |
| 167 | <ThreadRouteFallbackLayout> |
| 168 | <LoadingScreen message={gt("Opening thread…")} messagePlacement="above-spinner" embedded /> |
| 169 | </ThreadRouteFallbackLayout> |
| 170 | ); |
| 171 | } |
| 172 | |
| 173 | type ThreadRouteScreenRouteProps = StaticScreenProps<{ |
| 174 | readonly environmentId?: string; |
| 175 | readonly threadId?: string; |
| 176 | readonly draft?: NewTaskDraftRouteParams; |
| 177 | readonly inspector?: ThreadInspectorTarget; |
| 178 | readonly prompt?: string | string[]; |
| 179 | }>; |
| 180 | |
| 181 | interface ThreadRouteScreenProps extends ThreadRouteScreenRouteProps { |
| 182 | readonly inspectorPresentation?: ThreadInspectorPresentation; |
| 183 | readonly onReturnToThread?: () => void; |
| 184 | readonly renderInspector?: () => ReactNode; |
| 185 | } |
| 186 | |
| 187 | function ThreadUnavailableScreen(props: { |
| 188 | readonly actionLabel: string; |
| 189 | readonly onAction: () => void; |
| 190 | }) { |
| 191 | const gt = useGT(); |
| 192 | return ( |
| 193 | <ThreadRouteFallbackLayout> |
| 194 | <ScrollView |
| 195 | contentInsetAdjustmentBehavior="automatic" |
| 196 | contentContainerStyle={{ |
| 197 | flexGrow: 1, |
| 198 | justifyContent: "center", |
| 199 | paddingHorizontal: 24, |
| 200 | paddingVertical: 32, |
| 201 | }} |
| 202 | className="bg-screen flex-1 android:bg-transparent" |
| 203 | > |
| 204 | <EmptyState |
| 205 | title={gt("Thread unavailable")} |
| 206 | detail={gt("This thread is not available in the current mobile snapshot.")} |
| 207 | actionLabel={props.actionLabel} |
| 208 | onAction={props.onAction} |
| 209 | /> |
| 210 | </ScrollView> |
| 211 | </ThreadRouteFallbackLayout> |
| 212 | ); |
| 213 | } |
| 214 | |
| 215 | /** A thread that can't load opens a new task in its environment instead of a dead end. */ |
| 216 | function UnavailableThreadDraftRedirect(props: { readonly environmentId: EnvironmentId }) { |
| 217 | const navigation = useNavigation(); |
| 218 | const projects = useProjects(); |
| 219 | const openDraft = useEffectEvent(() => { |
| 220 | const project = projects.find((candidate) => candidate.environmentId === props.environmentId); |
| 221 | navigation.dispatch( |
| 222 | StackActions.replace("Thread", { |
| 223 | draft: project |
| 224 | ? { |
| 225 | requestId: uuidv4(), |
| 226 | environmentId: String(project.environmentId), |
| 227 | projectId: String(project.id), |
| 228 | } |
| 229 | : { requestId: uuidv4() }, |
| 230 | }), |
| 231 | ); |
| 232 | }); |
| 233 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- replaces this route with a new draft thread route for the environment's project on mount |
| 234 | useEffect(() => { |
| 235 | openDraft(); |
| 236 | }, []); |
| 237 | return <OpeningThreadLoadingScreen />; |
| 238 | } |
| 239 | |
| 240 | export function ThreadRouteScreen(props: ThreadRouteScreenProps) { |
| 241 | return ( |
| 242 | <ThreadScreenHost> |
| 243 | {props.route.params?.draft ? ( |
| 244 | <NewTaskDraftRouteScreen |
| 245 | key={draftRouteIdentity(props.route.params.draft)} |
| 246 | route={{ ...props.route, params: props.route.params.draft }} |
| 247 | /> |
| 248 | ) : ( |
| 249 | <LiveThreadRouteController {...props} /> |
| 250 | )} |
| 251 | </ThreadScreenHost> |
| 252 | ); |
| 253 | } |
| 254 | |
| 255 | function LiveThreadRouteController(props: ThreadRouteScreenProps) { |
| 256 | const gt = useGT(); |
| 257 | useAndroidWorkspaceBack(); |
| 258 | const connectionsReady = useConnectionsReady(); |
| 259 | const { connectionState } = useRemoteConnectionStatus(); |
| 260 | const { selectedThread } = useThreadSelection(); |
| 261 | const params = props.route.params ?? {}; |
| 262 | const environmentIdRaw = firstRouteParam(params.environmentId); |
| 263 | const threadIdRaw = firstRouteParam(params.threadId); |
| 264 | const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null; |
| 265 | const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId); |
| 266 | const routeEnvironmentShellState = useEnvironmentShellReadiness(environmentId); |
| 267 | const { onReconnectEnvironment } = useRemoteConnections(); |
| 268 | const navigation = useNavigation(); |
| 269 | const routeName = useRoute().name; |
| 270 | const routeConnectionState = |
| 271 | routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState); |
| 272 | const routeThreadKey = |
| 273 | environmentId !== null && threadIdRaw !== null |
| 274 | ? scopedThreadKey(environmentId, ThreadId.make(threadIdRaw)) |
| 275 | : null; |
| 276 | const selectedThreadKey = |
| 277 | selectedThread === null |
| 278 | ? null |
| 279 | : scopedThreadKey(selectedThread.environmentId, selectedThread.id); |
| 280 | const selectedThreadDetailState = useSelectedThreadDetailState(); |
| 281 | const detailError = selectedThreadDetailState.error; |
| 282 | const [errorBeforeConnected, setErrorBeforeConnected] = useState(() => |
| 283 | routeConnectionState === "connected" ? Option.none<string>() : detailError, |
| 284 | ); |
| 285 | if (routeConnectionState !== "connected" && errorBeforeConnected !== detailError) { |
| 286 | setErrorBeforeConnected(detailError); |
| 287 | } |
| 288 | const withInspectorHeader = (content: ReactNode) => |
| 289 | props.inspectorPresentation ? ( |
| 290 | <InspectorHeaderShownContext value> |
| 291 | <ThreadInspectorHeader |
| 292 | title={selectedThread?.title ?? gt("Thread")} |
| 293 | {...props.inspectorPresentation} |
| 294 | /> |
| 295 | {content} |
| 296 | </InspectorHeaderShownContext> |
| 297 | ) : ( |
| 298 | content |
| 299 | ); |
| 300 | |
| 301 | if (environmentId === null || threadIdRaw === null) { |
| 302 | return withInspectorHeader(<OpeningThreadLoadingScreen />); |
| 303 | } |
| 304 | |
| 305 | if (selectedThread !== null && selectedThreadKey === routeThreadKey) { |
| 306 | // ThreadRouteContent draws its own inspector header so it can show the sync status. |
| 307 | return ( |
| 308 | <InspectorHeaderShownContext value={props.inspectorPresentation !== undefined}> |
| 309 | <ThreadRouteContent {...props} selectedThreadDetailState={selectedThreadDetailState} /> |
| 310 | </InspectorHeaderShownContext> |
| 311 | ); |
| 312 | } |
| 313 | |
| 314 | const stillHydrating = threadRouteIsHydrating({ |
| 315 | isLoadingConnections: !connectionsReady, |
| 316 | environmentRegistered: routeEnvironmentRuntime !== null, |
| 317 | localCacheRead: |
| 318 | routeEnvironmentShellState.cacheRead && |
| 319 | selectedThreadDetailState !== EMPTY_ENVIRONMENT_THREAD_STATE, |
| 320 | connectionState: routeConnectionState, |
| 321 | shellStatus: routeEnvironmentShellState.status, |
| 322 | shellHasError: routeEnvironmentShellState.hasError, |
| 323 | detailStatus: selectedThreadDetailState.status, |
| 324 | detailHasError: threadDetailErrorIsCurrent({ |
| 325 | connectionState: routeConnectionState, |
| 326 | error: detailError, |
| 327 | errorBeforeConnected, |
| 328 | }), |
| 329 | }); |
| 330 | |
| 331 | if (stillHydrating) { |
| 332 | return withInspectorHeader(<OpeningThreadLoadingScreen />); |
| 333 | } |
| 334 | |
| 335 | if ( |
| 336 | routeName === "Thread" && |
| 337 | !props.inspectorPresentation && |
| 338 | threadRouteOpensDraft({ |
| 339 | connectionState: routeConnectionState, |
| 340 | detailStatus: selectedThreadDetailState.status, |
| 341 | }) |
| 342 | ) { |
| 343 | return <UnavailableThreadDraftRedirect environmentId={environmentId} />; |
| 344 | } |
| 345 | |
| 346 | return withInspectorHeader( |
| 347 | <ThreadUnavailableScreen |
| 348 | actionLabel={ |
| 349 | routeEnvironmentRuntime === null ? gt("Manage environments") : gt("Reconnect environment") |
| 350 | } |
| 351 | onAction={() => { |
| 352 | if (routeEnvironmentRuntime !== null) { |
| 353 | onReconnectEnvironment(environmentId); |
| 354 | return; |
| 355 | } |
| 356 | openSettings(navigation, "SettingsEnvironments"); |
| 357 | }} |
| 358 | />, |
| 359 | ); |
| 360 | } |
| 361 | |
| 362 | function ThreadRouteContent( |
| 363 | props: ThreadRouteScreenProps & { |
| 364 | readonly selectedThreadDetailState: ReturnType<typeof useSelectedThreadDetailState>; |
| 365 | }, |
| 366 | ) { |
| 367 | const gt = useGT(); |
| 368 | const m = useMessages(); |
| 369 | const { layout, showInspector, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout(); |
| 370 | const { connectionState } = useRemoteConnectionStatus(); |
| 371 | const { onReconnectEnvironment } = useRemoteConnections(); |
| 372 | const { |
| 373 | selectedThread, |
| 374 | selectedThreadCreation, |
| 375 | selectedThreadDetailRef, |
| 376 | selectedThreadProject, |
| 377 | selectedEnvironmentConnection, |
| 378 | } = useThreadSelection(); |
| 379 | useRememberThreadProject(selectedThreadProject); |
| 380 | const canOperateThread = useEnvironmentScope( |
| 381 | selectedThread?.environmentId ?? null, |
| 382 | AuthOrchestrationOperateScope, |
| 383 | ); |
| 384 | const canReadTerminal = useEnvironmentScope( |
| 385 | selectedThread?.environmentId ?? null, |
| 386 | AuthTerminalReadScope, |
| 387 | ); |
| 388 | const canOperateTerminal = useEnvironmentScope( |
| 389 | selectedThread?.environmentId ?? null, |
| 390 | AuthTerminalOperateScope, |
| 391 | ); |
| 392 | const selectedThreadDetailState = props.selectedThreadDetailState; |
| 393 | const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data); |
| 394 | const { selectedThreadCwd } = useSelectedThreadWorktree(); |
| 395 | const startSideChat = useStartSideChat(); |
| 396 | const composer = useThreadComposerState({ startSideChat }); |
| 397 | const gitState = useSelectedThreadGitState(); |
| 398 | const gitActions = useSelectedThreadGitActions(); |
| 399 | const requests = useSelectedThreadRequests(); |
| 400 | useThreadStatusAnnouncements({ |
| 401 | threadKey: |
| 402 | selectedThread === null || isProviderNativeSubagentThread(selectedThread.source) |
| 403 | ? null |
| 404 | : scopedThreadKey(selectedThread.environmentId, selectedThread.id), |
| 405 | // A preview beside its host names its thread, so the two threads' statuses can't be confused. |
| 406 | subject: |
| 407 | props.inspectorPresentation !== undefined && "onMaximize" in props.inspectorPresentation |
| 408 | ? (selectedThread?.title ?? null) |
| 409 | : null, |
| 410 | approvalRequestId: requests.activePendingApproval?.requestId ?? null, |
| 411 | userInputRequestId: requests.activePendingUserInput?.requestId ?? null, |
| 412 | shellRequestId: selectedThread?.source.pendingRuntimeRequest?.id ?? null, |
| 413 | shellPendingUserInput: selectedThread?.hasPendingUserInput === true, |
| 414 | working: composer.activeWorkStartedAt !== null || composer.isCompacting, |
| 415 | run: composer.selectedThreadAnnouncedRun, |
| 416 | detailBehind: composer.selectedThreadDetailBehindShell, |
| 417 | }); |
| 418 | const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt"); |
| 419 | const resumeThreadQueue = useAtomCommand(threadEnvironment.resumeThreadQueue, { |
| 420 | label: "resume queue", |
| 421 | reportFailure: false, |
| 422 | }); |
| 423 | const continueThreadRun = useAtomCommand(threadEnvironment.startTurn, { |
| 424 | label: "continue thread", |
| 425 | reportFailure: false, |
| 426 | }); |
| 427 | const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, { |
| 428 | label: "set thread runtime mode", |
| 429 | reportFailure: false, |
| 430 | }); |
| 431 | const setThreadInteractionMode = useAtomCommand(threadEnvironment.setInteractionMode, { |
| 432 | label: "set thread interaction mode", |
| 433 | reportFailure: false, |
| 434 | }); |
| 435 | const loadEarlierHistory = useAtomCommand(threadEnvironment.loadEarlierHistory, { |
| 436 | label: "load earlier thread history", |
| 437 | reportFailure: false, |
| 438 | }); |
| 439 | const historyControls = (() => { |
| 440 | const history = selectedThreadDetailState.history; |
| 441 | if (!selectedThread) { |
| 442 | return undefined; |
| 443 | } |
| 444 | if (!history.hasMoreHistory && history.error === null) { |
| 445 | return undefined; |
| 446 | } |
| 447 | return { |
| 448 | hasMoreHistory: history.hasMoreHistory, |
| 449 | loading: history.loading, |
| 450 | error: history.error === null ? null : threadErrorText(history.error, m), |
| 451 | onLoadEarlier: () => { |
| 452 | void loadEarlierHistory({ |
| 453 | environmentId: selectedThread.environmentId, |
| 454 | input: { threadId: selectedThread.id }, |
| 455 | }); |
| 456 | }, |
| 457 | onLoadThrough: (throughEntryId: string) => { |
| 458 | void loadEarlierHistory({ |
| 459 | environmentId: selectedThread.environmentId, |
| 460 | input: { threadId: selectedThread.id, throughEntryId }, |
| 461 | }); |
| 462 | }, |
| 463 | }; |
| 464 | })(); |
| 465 | const navigation = useNavigation(); |
| 466 | const selectDetail = useSelectWorkspaceDetail(); |
| 467 | const openPullRequest = useOpenPullRequest(); |
| 468 | const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back"); |
| 469 | const mergeBackTargetThreadId = resolveMergeBackTargetThreadId(selectedThreadDetail); |
| 470 | const mergeBackRun = |
| 471 | selectedThreadDetail === null ? null : resolveLatestMergeBackRun(selectedThreadDetail); |
| 472 | const mergeBackBusyRef = useRef(false); |
| 473 | const handleMergeBack = async () => { |
| 474 | if ( |
| 475 | mergeBackBusyRef.current || |
| 476 | !selectedThread || |
| 477 | mergeBackTargetThreadId === null || |
| 478 | mergeBackRun === null |
| 479 | ) { |
| 480 | return; |
| 481 | } |
| 482 | mergeBackBusyRef.current = true; |
| 483 | const result = await mergeBack({ |
| 484 | environmentId: selectedThread.environmentId, |
| 485 | input: { |
| 486 | sourceThreadId: selectedThread.id, |
| 487 | targetThreadId: mergeBackTargetThreadId, |
| 488 | runId: mergeBackRun.id, |
| 489 | creationSource: "mobile", |
| 490 | }, |
| 491 | }); |
| 492 | mergeBackBusyRef.current = false; |
| 493 | if (result._tag !== "Success") return; |
| 494 | selectDetail({ |
| 495 | name: "Thread", |
| 496 | params: { environmentId: selectedThread.environmentId, threadId: mergeBackTargetThreadId }, |
| 497 | }); |
| 498 | }; |
| 499 | const params = props.route.params ?? {}; |
| 500 | const environmentIdRaw = firstRouteParam(params.environmentId); |
| 501 | const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null; |
| 502 | const threadId = firstRouteParam(params.threadId); |
| 503 | const routeThreadIdentity = |
| 504 | environmentIdRaw !== null && threadId !== null ? `${environmentIdRaw}:${threadId}` : null; |
| 505 | // The chosen mode survives thread switches; "route" only applies while the route |
| 506 | // supplies an inspector, which is also the default whenever it does. |
| 507 | const [chosenInspectorMode, setChosenInspectorMode] = useState<ThreadInspectorMode | null>(null); |
| 508 | const previewTarget = props.inspectorPresentation ? undefined : params.inspector; |
| 509 | const inspectorMode = (() => { |
| 510 | if (previewTarget) return "preview"; |
| 511 | const mode = |
| 512 | props.renderInspector === undefined |
| 513 | ? chosenInspectorMode === "route" |
| 514 | ? null |
| 515 | : chosenInspectorMode |
| 516 | : chosenInspectorMode === null || chosenInspectorMode === "route" |
| 517 | ? "route" |
| 518 | : chosenInspectorMode; |
| 519 | return mode === "files" && selectedThreadCwd === null ? null : mode; |
| 520 | })(); |
| 521 | const revealPreview = useEffectEvent(() => showInspector()); |
| 522 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens the workspace navigator's inspector pane when route params bring a preview target |
| 523 | useEffect(() => { |
| 524 | if (previewTarget) revealPreview(); |
| 525 | }, [previewTarget]); |
| 526 | const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId); |
| 527 | const routeConnectionState = |
| 528 | routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState); |
| 529 | const routeConnectionError = routeEnvironmentRuntime |
| 530 | ? runtimeConnectionErrorText(routeEnvironmentRuntime, m) |
| 531 | : null; |
| 532 | const selectedThreadWithDraftSettings = selectedThread |
| 533 | ? { |
| 534 | ...selectedThread, |
| 535 | modelSelection: composer.modelSelection ?? selectedThread.modelSelection, |
| 536 | runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode, |
| 537 | interactionMode: composer.interactionMode ?? selectedThread.interactionMode, |
| 538 | } |
| 539 | : null; |
| 540 | |
| 541 | const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED; |
| 542 | const delegatedFrom = selectedThread?.delegatedFrom ?? null; |
| 543 | const delegatedFromRef = |
| 544 | delegatedFrom === null |
| 545 | ? null |
| 546 | : scopeThreadRef(delegatedFrom.environmentId, delegatedFrom.threadId); |
| 547 | // The title it had at delegation, until this client sees the parent itself. |
| 548 | const delegatedFromThread = useThreadShell(delegatedFromRef); |
| 549 | const headerSubtitle = [ |
| 550 | selectedThreadProject?.title ?? null, |
| 551 | selectedEnvironmentConnection?.environmentLabel ?? null, |
| 552 | // A linked environment's delegated task names its parent; other linked work its origin. |
| 553 | delegatedFrom !== null |
| 554 | ? gt("Subagent of {title}", { title: delegatedFromThread?.title ?? delegatedFrom.title }) |
| 555 | : selectedThread?.linkOrigin |
| 556 | ? gt("From {origin}", { origin: selectedThread.linkOrigin.label }) |
| 557 | : null, |
| 558 | ] |
| 559 | .filter(Boolean) |
| 560 | .join(" · "); |
| 561 | const gitStatus = useEnvironmentQuery( |
| 562 | selectedThread !== null && selectedThreadCwd !== null |
| 563 | ? vcsEnvironment.status({ |
| 564 | environmentId: selectedThread.environmentId, |
| 565 | input: { cwd: selectedThreadCwd }, |
| 566 | }) |
| 567 | : null, |
| 568 | ); |
| 569 | const { sessions: knownTerminalSessions } = useKnownTerminalSessions({ |
| 570 | environmentId: selectedThread?.environmentId ?? null, |
| 571 | threadId: selectedThread?.id ?? null, |
| 572 | }); |
| 573 | const terminalMenuSessions = buildTerminalMenuSessions( |
| 574 | { |
| 575 | knownSessions: knownTerminalSessions ?? [], |
| 576 | workspaceRoot: selectedThreadProject?.workspaceRoot ?? null, |
| 577 | }, |
| 578 | m, |
| 579 | ); |
| 580 | const selectedThreadDetailWorktreePath = selectedThreadDetail?.thread.worktreePath ?? null; |
| 581 | const handleReconnectEnvironment = () => { |
| 582 | if (!environmentId) { |
| 583 | return; |
| 584 | } |
| 585 | onReconnectEnvironment(environmentId); |
| 586 | }; |
| 587 | |
| 588 | const gitActionProgressTarget = { |
| 589 | environmentId: selectedThread?.environmentId ?? null, |
| 590 | cwd: selectedThreadCwd, |
| 591 | }; |
| 592 | const gitActionProgress = useGitActionProgress(gitActionProgressTarget); |
| 593 | |
| 594 | const handleOpenGitInspector = () => { |
| 595 | navigation.setParams({ inspector: undefined }); |
| 596 | setChosenInspectorMode("git"); |
| 597 | showInspector(); |
| 598 | }; |
| 599 | const handleOpenFilesInspector = () => { |
| 600 | if (selectedThread === null || selectedThreadCwd === null) { |
| 601 | return; |
| 602 | } |
| 603 | navigation.setParams({ inspector: undefined }); |
| 604 | setChosenInspectorMode(props.renderInspector === undefined ? "files" : "route"); |
| 605 | showInspector(); |
| 606 | }; |
| 607 | const handleSelectInspectorFile = (path: string) => { |
| 608 | if (selectedThread === null) { |
| 609 | return; |
| 610 | } |
| 611 | const params = { |
| 612 | environmentId: String(selectedThread.environmentId), |
| 613 | threadId: String(selectedThread.id), |
| 614 | path: path.split("/").filter((segment) => segment.length > 0), |
| 615 | }; |
| 616 | navigation.navigate("ThreadFile", params); |
| 617 | }; |
| 618 | const renderGitInspector = () => ( |
| 619 | <GitOverviewSheet |
| 620 | presentation="inspector" |
| 621 | route={{ params: { environmentId: environmentId!, threadId: threadId! } }} |
| 622 | /> |
| 623 | ); |
| 624 | const renderFilesInspector = () => |
| 625 | selectedThread !== null && selectedThreadCwd !== null ? ( |
| 626 | <InspectorSheetContext.Consumer> |
| 627 | {(closeInspectorSheet) => ( |
| 628 | <ThreadFileNavigatorPane |
| 629 | cwd={selectedThreadCwd} |
| 630 | environmentId={selectedThread.environmentId} |
| 631 | projectName={selectedThreadProject?.title ?? gt("Files")} |
| 632 | selectedPath={null} |
| 633 | onSelectFile={(path) => |
| 634 | closeInspectorSheet |
| 635 | ? closeInspectorSheet(() => handleSelectInspectorFile(path)) |
| 636 | : handleSelectInspectorFile(path) |
| 637 | } |
| 638 | /> |
| 639 | )} |
| 640 | </InspectorSheetContext.Consumer> |
| 641 | ) : null; |
| 642 | const renderPreviewInspector = () => |
| 643 | previewTarget ? ( |
| 644 | <ThreadInspectorPreviewWhileVisible |
| 645 | target={previewTarget} |
| 646 | renderThread={(screen) => <ThreadRouteScreen {...screen} />} |
| 647 | onClose={toggleAuxiliaryPane} |
| 648 | onOpen={(inspector) => { |
| 649 | if ( |
| 650 | inspector.type === "thread" && |
| 651 | inspector.environmentId === environmentId && |
| 652 | inspector.threadId === threadId |
| 653 | ) { |
| 654 | toggleAuxiliaryPane(); |
| 655 | return; |
| 656 | } |
| 657 | navigation.setParams({ inspector }); |
| 658 | }} |
| 659 | /> |
| 660 | ) : null; |
| 661 | const inspectorContent: InspectorContent | null = |
| 662 | inspectorMode === null |
| 663 | ? null |
| 664 | : { |
| 665 | active: inspectorMode, |
| 666 | resetKeys: [routeThreadIdentity, selectedThreadCwd], |
| 667 | panes: [ |
| 668 | ...(inspectorMode === "preview" |
| 669 | ? [ |
| 670 | { |
| 671 | key: "preview", |
| 672 | render: renderPreviewInspector, |
| 673 | }, |
| 674 | ] |
| 675 | : []), |
| 676 | { key: "files", render: renderFilesInspector, prewarm: true }, |
| 677 | { key: "git", render: renderGitInspector, prewarm: true }, |
| 678 | ...(props.renderInspector ? [{ key: "route", render: props.renderInspector }] : []), |
| 679 | ], |
| 680 | }; |
| 681 | |
| 682 | const handleOpenConnectionEditor = () => { |
| 683 | void navigation.navigate("Connections"); |
| 684 | }; |
| 685 | const handleStopThread = () => { |
| 686 | if ( |
| 687 | !selectedThread || |
| 688 | !readEnvironmentScope(selectedThread.environmentId, AuthOrchestrationOperateScope) || |
| 689 | composer.interruptibleRunId === null |
| 690 | ) { |
| 691 | return; |
| 692 | } |
| 693 | return interruptThreadTurn({ |
| 694 | environmentId: selectedThread.environmentId, |
| 695 | input: { |
| 696 | threadId: selectedThread.id, |
| 697 | runId: composer.interruptibleRunId, |
| 698 | }, |
| 699 | }); |
| 700 | }; |
| 701 | |
| 702 | const handleResumeQueue = async () => { |
| 703 | if (!selectedThread) return; |
| 704 | const result = await resumeThread({ |
| 705 | thread: selectedThread, |
| 706 | resumableRunId: composer.resumableRunId, |
| 707 | queueHeld: composer.queueHeld, |
| 708 | runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode, |
| 709 | interactionMode: composer.interactionMode ?? selectedThread.interactionMode, |
| 710 | modelSelection: composer.modelSelection, |
| 711 | messageId: MessageId.make(uuidv4()), |
| 712 | createdAt: new Date().toISOString(), |
| 713 | setRuntimeMode: setThreadRuntimeMode, |
| 714 | setInteractionMode: setThreadInteractionMode, |
| 715 | startTurn: continueThreadRun, |
| 716 | resumeQueue: resumeThreadQueue, |
| 717 | }); |
| 718 | if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { |
| 719 | const error = squashAtomCommandFailure(result); |
| 720 | Dialog.alert( |
| 721 | gt("Could not resume thread"), |
| 722 | errorDisplayMessage(error, m) ?? gt("Try again."), |
| 723 | ); |
| 724 | } |
| 725 | }; |
| 726 | |
| 727 | const handleOpenTerminal = (nextTerminalId?: string | null) => { |
| 728 | if ( |
| 729 | !selectedThread || |
| 730 | !selectedThreadProject?.workspaceRoot || |
| 731 | (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope) && |
| 732 | !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)) |
| 733 | ) { |
| 734 | return; |
| 735 | } |
| 736 | |
| 737 | void navigation.navigate("ThreadTerminal", { |
| 738 | environmentId: String(selectedThread.environmentId), |
| 739 | threadId: String(selectedThread.id), |
| 740 | ...(nextTerminalId ? { terminalId: nextTerminalId } : {}), |
| 741 | }); |
| 742 | }; |
| 743 | |
| 744 | const handleOpenNewTerminal = () => { |
| 745 | if ( |
| 746 | !selectedThread || |
| 747 | !selectedThreadProject?.workspaceRoot || |
| 748 | !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope) |
| 749 | ) { |
| 750 | return; |
| 751 | } |
| 752 | |
| 753 | const nextId = nextOpenTerminalId({ |
| 754 | listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId), |
| 755 | ...(knownTerminalSessions === null || |
| 756 | !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope) |
| 757 | ? { uniqueSuffix: uuidv4() } |
| 758 | : {}), |
| 759 | }); |
| 760 | void navigation.navigate("ThreadTerminal", { |
| 761 | environmentId: String(selectedThread.environmentId), |
| 762 | threadId: String(selectedThread.id), |
| 763 | terminalId: nextId, |
| 764 | }); |
| 765 | }; |
| 766 | |
| 767 | const handleRunProjectScript = async (script: ProjectScript) => { |
| 768 | if ( |
| 769 | !selectedThread || |
| 770 | !selectedThreadProject?.workspaceRoot || |
| 771 | !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope) |
| 772 | ) { |
| 773 | return; |
| 774 | } |
| 775 | |
| 776 | const targetTerminalId = resolveProjectScriptTerminalId({ |
| 777 | existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId), |
| 778 | ...(knownTerminalSessions === null || |
| 779 | !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope) |
| 780 | ? { uniqueSuffix: uuidv4() } |
| 781 | : {}), |
| 782 | hasRunningTerminal: terminalMenuSessions.some( |
| 783 | (session) => session.status === "running" || session.status === "starting", |
| 784 | ), |
| 785 | }); |
| 786 | const preferredWorktreePath = resolvePreferredThreadWorktreePath({ |
| 787 | threadShellWorktreePath: selectedThread.worktreePath ?? null, |
| 788 | threadDetailWorktreePath: selectedThreadDetailWorktreePath, |
| 789 | }); |
| 790 | const cwd = projectScriptCwd({ |
| 791 | project: { cwd: selectedThreadProject.workspaceRoot }, |
| 792 | worktreePath: preferredWorktreePath, |
| 793 | }); |
| 794 | const env = projectScriptRuntimeEnv({ |
| 795 | project: { cwd: selectedThreadProject.workspaceRoot }, |
| 796 | worktreePath: preferredWorktreePath, |
| 797 | }); |
| 798 | stagePendingTerminalLaunch({ |
| 799 | target: { |
| 800 | environmentId: selectedThread.environmentId, |
| 801 | threadId: selectedThread.id, |
| 802 | terminalId: targetTerminalId, |
| 803 | }, |
| 804 | launch: { |
| 805 | cwd, |
| 806 | worktreePath: preferredWorktreePath, |
| 807 | env, |
| 808 | initialInput: projectScriptTerminalInput(script.command), |
| 809 | stopOnSettle: script.stopOnSettle ?? false, |
| 810 | }, |
| 811 | }); |
| 812 | |
| 813 | void navigation.navigate("ThreadTerminal", { |
| 814 | environmentId: String(selectedThread.environmentId), |
| 815 | threadId: String(selectedThread.id), |
| 816 | terminalId: targetTerminalId, |
| 817 | }); |
| 818 | }; |
| 819 | const threadGitControlProps = { |
| 820 | environmentId: environmentIdRaw ?? "", |
| 821 | threadId: threadId ?? "", |
| 822 | onOpenFilesInspector: selectedThreadCwd !== null ? handleOpenFilesInspector : undefined, |
| 823 | onOpenGitInspector: handleOpenGitInspector, |
| 824 | onMergeBack: |
| 825 | mergeBackTargetThreadId !== null && mergeBackRun !== null |
| 826 | ? () => void handleMergeBack() |
| 827 | : undefined, |
| 828 | currentBranch: selectedThread?.branch ?? null, |
| 829 | gitStatus: gitStatus.data, |
| 830 | gitOperationLabel: gitState.gitOperationLabel, |
| 831 | canOpenTerminal: |
| 832 | Boolean(selectedThreadProject?.workspaceRoot) && (canReadTerminal || canOperateTerminal), |
| 833 | canOperateTerminal, |
| 834 | canOpenFiles: Boolean(selectedThreadProject?.workspaceRoot), |
| 835 | projectScripts: selectedThreadProject |
| 836 | ? resolveProjectScripts( |
| 837 | routeEnvironmentRuntime?.serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS, |
| 838 | selectedThreadProject, |
| 839 | ) |
| 840 | : [], |
| 841 | terminalSessions: terminalMenuSessions, |
| 842 | onOpenTerminal: handleOpenTerminal, |
| 843 | onOpenNewTerminal: handleOpenNewTerminal, |
| 844 | onRunProjectScript: handleRunProjectScript, |
| 845 | onPull: gitActions.onPullSelectedThreadBranch, |
| 846 | onRunAction: gitActions.onRunSelectedThreadGitAction, |
| 847 | }; |
| 848 | const handleEditFailedCreation = async () => { |
| 849 | const creation = selectedThreadCreation?.message; |
| 850 | if (!creation?.creation || routeThreadIdentity === null) { |
| 851 | return; |
| 852 | } |
| 853 | // Open recovery by draft id or the sheet creates an empty draft and strands restored content. |
| 854 | try { |
| 855 | await recoverFailedThreadDraft(creation); |
| 856 | } catch (error) { |
| 857 | Dialog.alert(gt("Could not restore draft"), errorDisplayMessage(error, m) ?? String(error)); |
| 858 | return; |
| 859 | } |
| 860 | clearPendingThreadCreationOutcome(routeThreadIdentity); |
| 861 | navigation.dispatch( |
| 862 | StackActions.replace("Thread", { |
| 863 | draft: { |
| 864 | draftId: restoredNewTaskDraftKey(creation.messageId), |
| 865 | environmentId: String(creation.environmentId), |
| 866 | projectId: String(creation.creation.projectId), |
| 867 | ...(selectedThreadProject ? { title: selectedThreadProject.title } : {}), |
| 868 | }, |
| 869 | }), |
| 870 | ); |
| 871 | }; |
| 872 | const setupTurnStartedAt = composer.selectedThreadActivityRun?.startedAt ?? null; |
| 873 | const { visible: worktreeSetup } = useWorktreeSetup({ |
| 874 | environmentId: selectedThread?.environmentId ?? null, |
| 875 | threadId: selectedThread?.id ?? null, |
| 876 | preparing: |
| 877 | composer.selectedThreadActivityRun?.status === "preparing" || |
| 878 | selectedThread?.runtime?.status === "preparing" || |
| 879 | selectedThread?.worktreePath != null || |
| 880 | (selectedThreadCreation?.message.creation?.workspaceMode === "worktree" && |
| 881 | selectedThreadCreation.outcome == null), |
| 882 | runs: selectedThreadDetail?.runs ?? [], |
| 883 | followUpSent: |
| 884 | composer.selectedThreadFeed.filter( |
| 885 | (entry) => entry.type === "message" && entry.message.role === "user", |
| 886 | ).length + |
| 887 | composer.selectedThreadQueueCount > |
| 888 | 1, |
| 889 | }); |
| 890 | const awaitingBootstrapTurn = |
| 891 | worktreeSetup !== null |
| 892 | ? worktreeSetup.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup) |
| 893 | : (selectedThreadDetail?.runs.some((run) => run.status === "preparing") ?? false); |
| 894 | const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup); |
| 895 | const handleCancelWorktreeSetup = () => { |
| 896 | if (!selectedThread) return; |
| 897 | void cancelWorktreeSetup({ |
| 898 | environmentId: selectedThread.environmentId, |
| 899 | input: { threadId: selectedThread.id }, |
| 900 | }); |
| 901 | }; |
| 902 | const startLocalThread = useAtomCommand(threadEnvironment.startTurn, "work locally"); |
| 903 | const localResendBusy = useRef(false); |
| 904 | const setupMessage = selectedThreadDetail?.messages.find((message) => message.role === "user"); |
| 905 | const handleWorkLocally = async () => { |
| 906 | if (!selectedThread || !selectedThreadProject || !setupMessage || localResendBusy.current) |
| 907 | return; |
| 908 | localResendBusy.current = true; |
| 909 | const result = await cancelWorktreeSetup({ |
| 910 | environmentId: selectedThread.environmentId, |
| 911 | input: { threadId: selectedThread.id }, |
| 912 | }); |
| 913 | if (result._tag !== "Success" || !result.value.cancelled) { |
| 914 | localResendBusy.current = false; |
| 915 | return; |
| 916 | } |
| 917 | // V2 accepts launch before setup; cancellation cannot reject that delivery, so reuse server-owned prompt and uploads. |
| 918 | const metadata = makeTurnCommandMetadata(); |
| 919 | const launched = await startLocalThread({ |
| 920 | environmentId: selectedThread.environmentId, |
| 921 | input: buildProjectThreadStartTurnInput({ |
| 922 | ...metadata, |
| 923 | projectId: selectedThread.projectId, |
| 924 | projectCwd: selectedThreadProject.workspaceRoot, |
| 925 | text: setupMessage.text, |
| 926 | titleText: selectedThread.title, |
| 927 | ...(setupMessage.context ? { context: setupMessage.context } : {}), |
| 928 | uploadedAttachments: setupMessage.attachments, |
| 929 | modelSelection: selectedThread.modelSelection, |
| 930 | runtimeMode: selectedThread.runtimeMode, |
| 931 | interactionMode: selectedThread.interactionMode, |
| 932 | workspaceMode: "local", |
| 933 | branch: null, |
| 934 | worktreePath: null, |
| 935 | startFromOrigin: false, |
| 936 | worktreeBranchName: "", |
| 937 | }), |
| 938 | }); |
| 939 | localResendBusy.current = false; |
| 940 | if (launched._tag !== "Success") return; |
| 941 | navigation.dispatch( |
| 942 | StackActions.replace("Thread", { |
| 943 | environmentId: String(selectedThread.environmentId), |
| 944 | threadId: metadata.threadId, |
| 945 | }), |
| 946 | ); |
| 947 | }; |
| 948 | const creationState = ((): ThreadDetailScreenProps["creationState"] => { |
| 949 | if (selectedThreadCreation === null) { |
| 950 | return awaitingBootstrapTurn |
| 951 | ? { kind: "preparing", preparingWorktree: true, serverOwned: true } |
| 952 | : null; |
| 953 | } |
| 954 | if (selectedThreadCreation.outcome?.kind === "failed") { |
| 955 | return { |
| 956 | kind: "failed", |
| 957 | reason: selectedThreadCreation.outcome.reason, |
| 958 | onEditTask: handleEditFailedCreation, |
| 959 | }; |
| 960 | } |
| 961 | return { |
| 962 | kind: "preparing", |
| 963 | preparingWorktree: selectedThreadCreation.message.creation?.workspaceMode === "worktree", |
| 964 | serverOwned: false, |
| 965 | }; |
| 966 | })(); |
| 967 | // Queued creation displays its prompt before server creation; temporary not-found is expected. |
| 968 | const contentPresentation = |
| 969 | creationState !== null |
| 970 | ? { kind: "ready" as const } |
| 971 | : projectThreadContentPresentation({ |
| 972 | hasDetail: selectedThreadDetail !== null, |
| 973 | detailError: Option.getOrNull(selectedThreadDetailState.error), |
| 974 | detailDeleted: selectedThreadDetailState.status === "deleted", |
| 975 | connectionState: routeConnectionState, |
| 976 | resolve: m, |
| 977 | }); |
| 978 | const connectionRetrying = |
| 979 | routeConnectionState === "connecting" || routeConnectionState === "reconnecting"; |
| 980 | // Connection failures survive retries and app suspension. |
| 981 | const retryConnectionError = useDelayedStatus( |
| 982 | `${environmentId}:${connectionRetrying && routeConnectionError !== null}`, |
| 983 | connectionRetrying ? routeConnectionError : null, |
| 984 | RECONNECT_ERROR_DELAY_MS, |
| 985 | ); |
| 986 | const connectionStatusLabel = connectionRetryLabel( |
| 987 | { |
| 988 | connectionError: retryConnectionError, |
| 989 | connectionState: routeConnectionState, |
| 990 | connectionAwaitingApproval: routeEnvironmentRuntime?.connectionAwaitingApproval === true, |
| 991 | }, |
| 992 | m, |
| 993 | ); |
| 994 | // A thread this client is creating has nothing older to sync. |
| 995 | const threadSyncLabel = |
| 996 | creationState === null |
| 997 | ? threadSyncStatusLabel(selectedThreadDetailState.status, contentPresentation.kind, m) |
| 998 | : null; |
| 999 | // Transient states go in the header subtitle so the composer's status slot doesn't jump. |
| 1000 | const threadStatusLabel = useDelayedStatus( |
| 1001 | selectedThread === null ? "" : scopedThreadKey(selectedThread.environmentId, selectedThread.id), |
| 1002 | connectionStatusLabel !== null ? connectionStatusLabel : threadSyncLabel, |
| 1003 | ); |
| 1004 | const inspectorHeader = props.inspectorPresentation ? ( |
| 1005 | <ThreadInspectorHeader |
| 1006 | title={selectedThread?.title ?? gt("Thread")} |
| 1007 | subtitle={threadStatusLabel ?? undefined} |
| 1008 | {...props.inspectorPresentation} |
| 1009 | /> |
| 1010 | ) : null; |
| 1011 | if (!environmentId || !threadId || !selectedThread) { |
| 1012 | return ( |
| 1013 | <> |
| 1014 | {inspectorHeader} |
| 1015 | <OpeningThreadLoadingScreen /> |
| 1016 | </> |
| 1017 | ); |
| 1018 | } |
| 1019 | |
| 1020 | const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null; |
| 1021 | const renderThreadRouteBody = () => ( |
| 1022 | <> |
| 1023 | <GitActionProgressOverlay |
| 1024 | progress={gitActionProgress} |
| 1025 | onDismiss={dismissGitActionResult} |
| 1026 | onOpenPullRequest={openPullRequest} |
| 1027 | /> |
| 1028 | |
| 1029 | <> |
| 1030 | <ThreadScreenBinding |
| 1031 | header={ |
| 1032 | props.inspectorPresentation ? null : ( |
| 1033 | <ThreadHeader |
| 1034 | title={selectedThread.title} |
| 1035 | subtitle={threadStatusLabel ?? headerSubtitle} |
| 1036 | gitControls={threadGitControlProps} |
| 1037 | hasThreadCwd={selectedThreadCwd !== null} |
| 1038 | inspectorMode={inspectorMode} |
| 1039 | onOpenFilesInspector={handleOpenFilesInspector} |
| 1040 | onReturnToThread={props.onReturnToThread} |
| 1041 | /> |
| 1042 | ) |
| 1043 | } |
| 1044 | canOperateThread={canOperateThread} |
| 1045 | selectedThread={selectedThreadWithDraftSettings ?? selectedThread} |
| 1046 | selectedThreadDetailRef={selectedThreadDetailRef} |
| 1047 | contentPresentation={contentPresentation} |
| 1048 | screenTone={connectionTone( |
| 1049 | routeConnectionState, |
| 1050 | routeEnvironmentRuntime?.connectionAwaitingApproval === true, |
| 1051 | m, |
| 1052 | )} |
| 1053 | connectionError={routeConnectionError} |
| 1054 | environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null} |
| 1055 | feedbackSubmissions={composer.feedbackSubmissions} |
| 1056 | onDismissFeedback={composer.dismissFeedback} |
| 1057 | selectedThreadFeed={composer.selectedThreadFeed} |
| 1058 | pendingHandoff={composer.pendingHandoff} |
| 1059 | activityRun={composer.selectedThreadActivityRun} |
| 1060 | activeWorkStartedAt={ |
| 1061 | creationState?.kind === "preparing" || |
| 1062 | (worktreeSetup !== null && setupTurnStartedAt === null) |
| 1063 | ? null |
| 1064 | : composer.activeWorkStartedAt |
| 1065 | } |
| 1066 | isCompacting={composer.isCompacting} |
| 1067 | compactBeforeSend={composer.compactBeforeSend} |
| 1068 | runlessWorkActive={composer.runlessWorkActive} |
| 1069 | extensionStatuses={composer.extensionStatuses} |
| 1070 | providerSubagentStatus={composer.providerSubagentStatus} |
| 1071 | creationState={creationState} |
| 1072 | worktreeSetup={ |
| 1073 | worktreeSetup |
| 1074 | ? { |
| 1075 | snapshot: worktreeSetup, |
| 1076 | turnStarted: setupTurnStartedAt !== null, |
| 1077 | onCancel: handleCancelWorktreeSetup, |
| 1078 | onWorkLocally: setupMessage && selectedThreadProject ? handleWorkLocally : null, |
| 1079 | } |
| 1080 | : null |
| 1081 | } |
| 1082 | activePendingApproval={requests.activePendingApproval} |
| 1083 | activePendingApprovals={requests.activePendingApprovals} |
| 1084 | respondingApprovalId={requests.respondingApprovalId} |
| 1085 | activePendingUserInput={requests.activePendingUserInput} |
| 1086 | activePendingUserInputDrafts={requests.activePendingUserInputDrafts} |
| 1087 | activePendingUserInputAnswers={requests.activePendingUserInputAnswers} |
| 1088 | respondingUserInputId={requests.respondingUserInputId} |
| 1089 | connectionStateLabel={routeConnectionState} |
| 1090 | historyControls={historyControls} |
| 1091 | activeThreadBusy={composer.activeThreadBusy} |
| 1092 | canStopThread={awaitingBootstrapTurn || composer.interruptibleRunId !== null} |
| 1093 | queuedRunEdit={composer.queuedRunEdit} |
| 1094 | composerDraftKey={composer.composerDraftKey} |
| 1095 | followUpBehavior={composer.followUpBehavior} |
| 1096 | canSteerActiveTurn={composer.canSteerActiveTurn} |
| 1097 | isSavingQueuedEdit={composer.isSavingQueuedEdit} |
| 1098 | onCancelQueuedRunEdit={composer.cancelQueuedRunEdit} |
| 1099 | onRemoveQueuedEditAttachment={composer.onRemoveQueuedEditAttachment} |
| 1100 | environmentId={selectedThread.environmentId} |
| 1101 | projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null} |
| 1102 | threadCwd={selectedThreadCwd} |
| 1103 | selectedThreadQueueCount={composer.selectedThreadQueueCount} |
| 1104 | queuedMessages={ |
| 1105 | selectedThreadCreation && selectedThreadCreation.outcome?.kind !== "delivered" |
| 1106 | ? [selectedThreadCreation.message, ...composer.selectedThreadQueuedMessages] |
| 1107 | : composer.selectedThreadQueuedMessages |
| 1108 | } |
| 1109 | dispatchingMessageId={composer.dispatchingQueuedMessageId} |
| 1110 | layoutVariant={layout.variant} |
| 1111 | usesAutomaticContentInsets={usesNativeHeaderGlass} |
| 1112 | onOpenConnectionEditor={handleOpenConnectionEditor} |
| 1113 | onChangeDraftMessage={composer.onChangeDraftMessage} |
| 1114 | onPickDraftMedia={composer.onPickDraftMedia} |
| 1115 | onPickDraftFiles={composer.onPickDraftFiles} |
| 1116 | onNativePasteImages={composer.onNativePasteImages} |
| 1117 | onNativePasteText={composer.onNativePasteText} |
| 1118 | onRemoveDraftImage={composer.onRemoveDraftImage} |
| 1119 | serverConfig={serverConfig} |
| 1120 | onStopThread={awaitingBootstrapTurn ? handleCancelWorktreeSetup : handleStopThread} |
| 1121 | onResumeQueue={composer.canResume ? handleResumeQueue : null} |
| 1122 | onSendMessage={composer.onSendMessage} |
| 1123 | offersSideChat={composer.sideChatUnavailableReason === null} |
| 1124 | onSendCommand={composer.onSendCommand} |
| 1125 | onReconnectEnvironment={handleReconnectEnvironment} |
| 1126 | canSwitchThreadProvider={composer.canSwitchThreadProvider} |
| 1127 | onRespondToApproval={requests.onRespondToApproval} |
| 1128 | onSelectUserInputOption={requests.onSelectUserInputOption} |
| 1129 | onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer} |
| 1130 | onSubmitUserInput={requests.onSubmitUserInput} |
| 1131 | onDismissUserInput={requests.onDismissUserInput} |
| 1132 | /> |
| 1133 | </> |
| 1134 | </> |
| 1135 | ); |
| 1136 | |
| 1137 | return ( |
| 1138 | <> |
| 1139 | {inspectorHeader} |
| 1140 | {!props.inspectorPresentation && inspectorContent ? ( |
| 1141 | <Inspector |
| 1142 | // A route's own inspector (files) opens once per thread; going back keeps the user's choice. |
| 1143 | revealKey={ |
| 1144 | props.renderInspector !== undefined && selectedThreadCwd !== null |
| 1145 | ? (routeThreadIdentity ?? undefined) |
| 1146 | : undefined |
| 1147 | } |
| 1148 | content={inspectorContent} |
| 1149 | /> |
| 1150 | ) : null} |
| 1151 | |
| 1152 | {renderThreadRouteBody()} |
| 1153 | </> |
| 1154 | ); |
| 1155 | } |
| 1156 | |
| 1157 | export function FullscreenThreadRouteScreen( |
| 1158 | props: StaticScreenProps<{ |
| 1159 | readonly environmentId: string; |
| 1160 | readonly threadId: string; |
| 1161 | }>, |
| 1162 | ) { |
| 1163 | const navigation = useNavigation(); |
| 1164 | return ( |
| 1165 | <InspectorContentScope> |
| 1166 | <ThreadRouteScreen |
| 1167 | route={props.route} |
| 1168 | inspectorPresentation={{ onClose: () => navigation.goBack() }} |
| 1169 | /> |
| 1170 | </InspectorContentScope> |
| 1171 | ); |
| 1172 | } |
| 1173 | |
| 1174 | /** Reads the pane state itself, so a sidebar toggle doesn't re-render the whole thread screen. */ |
| 1175 | function ThreadInspectorPreviewWhileVisible(props: Parameters<typeof ThreadInspectorPreview>[0]) { |
| 1176 | const { panes } = useWorkspacePaneState(); |
| 1177 | return panes.auxiliaryPaneVisible ? <ThreadInspectorPreview {...props} /> : null; |
| 1178 | } |