diff --git a/apps/mobile/src/features/terminal/terminalLaunchContext.test.ts b/apps/mobile/src/features/terminal/terminalLaunchContext.test.ts index 89d3edc7fa30..a6464d8b0f0d 100644 --- a/apps/mobile/src/features/terminal/terminalLaunchContext.test.ts +++ b/apps/mobile/src/features/terminal/terminalLaunchContext.test.ts @@ -3,6 +3,7 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { resolveTerminalOpenLocation, + stageCommandTerminalLaunch, stagePendingTerminalLaunch, takePendingTerminalLaunch, } from "./terminalLaunchContext"; @@ -55,6 +56,62 @@ describe("resolveTerminalOpenLocation", () => { }); }); +describe("command terminal launches", () => { + it("stages a command in the detail worktree with the project runtime environment", () => { + const target = { + environmentId: EnvironmentId.make("env-command"), + threadId: ThreadId.make("thread-command"), + terminalId: "term-follow-worktree", + }; + const launch = stageCommandTerminalLaunch({ + target, + workspaceRoot: "/repo/root", + threadShellWorktreePath: "/repo/worktrees/stale", + threadDetailWorktreePath: "/repo/worktrees/feature", + command: "tail -n +1 -F '/tmp/task.output'", + }); + + expect(launch).toEqual({ + cwd: "/repo/worktrees/feature", + worktreePath: "/repo/worktrees/feature", + env: { + T3CODE_PROJECT_ROOT: "/repo/root", + T3CODE_WORKTREE_PATH: "/repo/worktrees/feature", + }, + initialInput: " tail -n +1 -F '/tmp/task.output'\r", + }); + expect(takePendingTerminalLaunch(target)).toEqual(launch); + expect(takePendingTerminalLaunch(target)).toBeNull(); + }); + + it("falls back to the shell worktree and then the project checkout", () => { + for (const worktreePath of ["/repo/worktrees/feature", null]) { + const target = { + environmentId: EnvironmentId.make("env-command"), + threadId: ThreadId.make("thread-command"), + terminalId: worktreePath === null ? "term-project" : "term-shell-worktree", + }; + stageCommandTerminalLaunch({ + target, + workspaceRoot: "/repo/root", + threadShellWorktreePath: worktreePath, + threadDetailWorktreePath: null, + command: "printf 'hello'", + }); + + expect(takePendingTerminalLaunch(target)).toEqual({ + cwd: worktreePath ?? "/repo/root", + worktreePath, + env: { + T3CODE_PROJECT_ROOT: "/repo/root", + ...(worktreePath ? { T3CODE_WORKTREE_PATH: worktreePath } : {}), + }, + initialInput: " printf 'hello'\r", + }); + } + }); +}); + describe("pending terminal launches", () => { it("stages and consumes launch details for a specific terminal target", () => { const target = { diff --git a/apps/mobile/src/features/terminal/terminalLaunchContext.ts b/apps/mobile/src/features/terminal/terminalLaunchContext.ts index 1ee18cd20063..fe08b133272d 100644 --- a/apps/mobile/src/features/terminal/terminalLaunchContext.ts +++ b/apps/mobile/src/features/terminal/terminalLaunchContext.ts @@ -1,4 +1,9 @@ import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { + projectScriptCwd, + projectScriptRuntimeEnv, + projectScriptTerminalInput, +} from "@t3tools/shared/projectScripts"; import { useState } from "react"; interface TerminalLocationLike { @@ -37,6 +42,25 @@ export function stagePendingTerminalLaunch(input: { }); } +export function stageCommandTerminalLaunch(input: { + readonly target: PendingTerminalLaunchTarget; + readonly workspaceRoot: string; + readonly threadShellWorktreePath: string | null; + readonly threadDetailWorktreePath: string | null; + readonly command: string; +}) { + const worktreePath = resolvePreferredThreadWorktreePath(input); + const project = { cwd: input.workspaceRoot }; + const launch = { + cwd: projectScriptCwd({ project, worktreePath }), + worktreePath, + env: projectScriptRuntimeEnv({ project, worktreePath }), + initialInput: projectScriptTerminalInput(input.command), + }; + stagePendingTerminalLaunch({ target: input.target, launch }); + return launch; +} + export function takePendingTerminalLaunch( target: PendingTerminalLaunchTarget, ): PendingTerminalLaunch | null { diff --git a/apps/mobile/src/features/threads/ThreadBackgroundWorkSheet.tsx b/apps/mobile/src/features/threads/ThreadBackgroundWorkSheet.tsx index c4db6d7a9375..82dfa296c0a5 100644 --- a/apps/mobile/src/features/threads/ThreadBackgroundWorkSheet.tsx +++ b/apps/mobile/src/features/threads/ThreadBackgroundWorkSheet.tsx @@ -1,12 +1,32 @@ -import { useAtomValue } from "@effect/atom-react"; -import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native"; +import { + StackActions, + useIsFocused, + useNavigation, + type StaticScreenProps, +} from "@react-navigation/native"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { - presentPendingBackgroundWork, - type PendingBackgroundWorkItem, + backgroundCommandOutputFile, + deriveBackgroundWorkDetails, + followOutputFileCommand, + type BackgroundWorkDetail, } from "@t3tools/client-runtime/state/thread-execution"; -import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { + toolCallLines, + turnItemDetailRevision, + turnItemNeedsDetailFetch, + turnItemOutputText, +} from "@t3tools/client-runtime/work-log/item-detail"; +import { + AuthTerminalOperateScope, + type EnvironmentId, + type ThreadId, + type ThreadPullRequestLink, +} from "@t3tools/contracts"; +import { formatDuration } from "@t3tools/shared/orchestrationTiming"; +import { nextTerminalId } from "@t3tools/shared/terminalLabels"; import * as Haptics from "expo-haptics"; +import { useState } from "react"; import { Platform, Pressable, ScrollView, View } from "react-native"; import { ScreenStack } from "react-native-screens"; import { useSafeAreaInsets } from "react-native-safe-area-context"; @@ -14,11 +34,25 @@ import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AndroidSheetHeader } from "../../components/ui/AndroidScreenHeader"; import { SymbolView } from "../../components/ui/AppSymbol"; import { AppText as Text } from "../../components/ui/AppText"; +import { Button } from "../../components/ui/Button"; +import * as Dialog from "../../components/ui/Dialog"; import { ScreenContent } from "../../components/ui/ScreenContent"; +import { cn } from "../../lib/cn"; +import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; +import { uuidv4 } from "../../lib/uuid"; import { NativeStackScreenOptions, nativeHeaderScrollEdgeEffects } from "../../native/StackHeader"; import { NativeHeader, NativeScreen } from "../../native/ThemedScreenStack"; -import { environmentThreadShells } from "../../state/threads"; +import { useProject, useQuietThreadShell } from "../../state/entities"; +import { orchestrationEnvironment } from "../../state/orchestration"; +import { useEnvironmentQuery } from "../../state/query"; +import { readEnvironmentScope, useEnvironmentScope } from "../../state/session"; +import { useQuietThreadStructure } from "../../state/use-thread-detail"; import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout"; +import { pullRequestChecksStatus, pullRequestStatus } from "../pull-requests/pullRequestStatus"; +import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; +import { stageCommandTerminalLaunch } from "../terminal/terminalLaunchContext"; +import { ThreadCommandOutput, useCommandOutputStreaming } from "./thread-command-output"; +import { useVisibleSecondClock } from "./use-visible-second-clock"; const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version); const KIND_LABELS = { @@ -35,10 +69,39 @@ export function ThreadBackgroundWorkSheet({ route }: StaticScreenProps { + if ( + !project?.workspaceRoot || + !readEnvironmentScope(target.environmentId, AuthTerminalOperateScope) + ) + return; + void Haptics.selectionAsync(); + const terminalId = nextTerminalId([], uuidv4()); + stageCommandTerminalLaunch({ + target: { ...target, terminalId }, + workspaceRoot: project.workspaceRoot, + threadShellWorktreePath: thread?.worktreePath ?? null, + threadDetailWorktreePath: structure?.projection.thread.worktreePath ?? null, + command: followOutputFileCommand(path), + }); + void navigation.navigate("ThreadTerminal", { + environmentId: String(target.environmentId), + threadId: String(target.threadId), + terminalId, + }); + }; const openThread = (threadId: ThreadId) => { void Haptics.selectionAsync(); // A thread replaces the leaf sheet so workspace back navigation still works. @@ -54,14 +117,28 @@ export function ThreadBackgroundWorkSheet({ route }: StaticScreenProps - {presentation === null ? ( + {work === null ? ( Nothing running in the background. ) : ( - presentation.items.map((item) => ( - - )) + work.details.map((detail) => + detail.pullRequest ? ( + + ) : ( + + ), + ) )} ); @@ -103,41 +180,240 @@ export function ThreadBackgroundWorkSheet({ route }: StaticScreenProps void; -}) { - const { item } = props; - const childThreadId = item.childThreadId; - const row = ( - - - - {item.label} - {KIND_LABELS[item.kind]} - - {childThreadId === undefined ? null : ( - - )} - +const CHECKS_LABELS = { + passing: "checks passing", + pending: "checks pending", + failing: "checks failing", +} as const; + +function BackgroundWorkElapsed({ startedAtMs }: { readonly startedAtMs: number | null }) { + const nowMs = useVisibleSecondClock(startedAtMs !== null); + return startedAtMs === null ? null : ( + + {` · ${formatDuration(Math.max(0, nowMs - startedAtMs))}`} + ); - return childThreadId === undefined ? ( - {row} - ) : ( +} + +function PullRequestMonitorRow(props: { + readonly link: ThreadPullRequestLink; + readonly startedAtMs: number | null; +}) { + const { link } = props; + // The snapshot arrives from the host after the link, so the row must stay tappable without it. + const snapshot = link.snapshot; + const status = snapshot ? pullRequestStatus(snapshot) : null; + const checksState = snapshot?.state === "open" ? snapshot.checksState : undefined; + const checks = checksState ? pullRequestChecksStatus(checksState) : null; + const checksLabel = checksState ? CHECKS_LABELS[checksState] : undefined; + const title = snapshot?.title ?? `Pull request #${link.number}`; + return ( props.onOpen(childThreadId)} + accessibilityLabel={`Watching pull request ${link.number}, ${title}${status ? `, ${status.label}` : ""}${checksLabel ? `, ${checksLabel}` : ""}`} + accessibilityHint="Opens this pull request externally" + onPress={() => { + void Haptics.selectionAsync(); + void tryOpenExternalUrl(link.url, "pull-request").then((opened) => { + if (!opened) Dialog.alert("Unable to open PR", "The pull request could not be opened."); + }); + }} className="active:opacity-70" > - {row} + + + + + {title} + + + + #{link.number} + + + Monitor · Watching{status ? ` · ${status.label}` : ""} + + + {checks ? ( + + + {checksLabel} + + ) : null} + + + + ); } + +function BackgroundWorkRow(props: { + readonly detail: BackgroundWorkDetail; + readonly target: BackgroundWorkTarget; + readonly onOpen: (threadId: ThreadId) => void; + readonly onFollow: ((path: string) => void) | undefined; +}) { + const { item, childThreadId } = props.detail; + const [expanded, setExpanded] = useState(false); + const focused = useIsFocused(); + return ( + + { + if (childThreadId !== undefined) { + props.onOpen(childThreadId); + } else { + void Haptics.selectionAsync(); + setExpanded((value) => !value); + } + }} + className="active:opacity-70" + > + + + + {item.label} + + {KIND_LABELS[item.kind]} + + + + + + + {expanded && focused ? ( + + ) : null} + + ); +} + +function BackgroundWorkInspection(props: { + readonly detail: BackgroundWorkDetail; + readonly target: BackgroundWorkTarget; + readonly onFollow: ((path: string) => void) | undefined; +}) { + const { detail, target, onFollow } = props; + const { themeAppearance } = useAppearancePreferences(); + const streaming = useCommandOutputStreaming(target.environmentId); + const item = detail.turnItem; + const inspectableItem = + item?.type === "command_execution" || item?.type === "dynamic_tool" ? item : null; + const needsFetch = inspectableItem !== null && turnItemNeedsDetailFetch(inspectableItem); + const fetched = useEnvironmentQuery( + needsFetch + ? orchestrationEnvironment.turnItem({ + environmentId: target.environmentId, + input: { + threadId: inspectableItem.threadId, + itemId: inspectableItem.id, + revision: turnItemDetailRevision(inspectableItem), + }, + }) + : null, + ); + const shownItem = fetched.data?.item ?? item; + const commandItem = shownItem?.type === "command_execution" ? shownItem : null; + const toolItem = shownItem?.type === "dynamic_tool" ? shownItem : null; + const subagent = shownItem?.type === "subagent" ? shownItem : null; + const command = commandItem?.input ?? detail.command; + const description = shownItem?.title?.trim() || detail.item.label; + const outputFile = detail.outputFile ?? backgroundCommandOutputFile(commandItem?.output); + const loading = needsFetch && fetched.data === null && fetched.error === null; + const streamsOutput = streaming && commandItem !== null && outputFile === null && !loading; + const output = inspectableItem ? turnItemOutputText(fetched.data?.item ?? inspectableItem) : null; + const toolInput = toolItem ? toolCallLines({ args: toolItem.input }) : null; + const inputText = + toolInput?.args?.map(([name, value]) => `${name}: ${value}`).join("\n") ?? + toolInput?.argsText ?? + subagent?.prompt; + return ( + + {description !== command?.trim() ? ( + + {description} + + ) : null} + {command ? ( + + + + {command} + + + + ) : null} + {toolItem ? ( + + {toolItem.toolName ?? "Tool"} + + ) : null} + {inputText ? ( + + {inputText} + + ) : null} + {outputFile !== null ? ( + <> + Output file on this environment + + {outputFile} + + {onFollow ? ( + + ) : null} + + )} + {detail.activity ? ( +

{detail.activity}

+ ) : null} + {childThreadId === undefined ? null : ( + + )} + {pullRequest ? ( +
+ {prHref ? ( + + #{pullRequest.number} {pullRequest.snapshot?.title ?? "Pull request"} + + + ) : ( +

+ #{pullRequest.number} {pullRequest.snapshot?.title ?? "Pull request"} +

+ )} +

+ Watching + {pullRequest.snapshot + ? ` · ${pullRequest.snapshot.isDraft ? "Draft · " : ""}${pullRequest.snapshot.state}` + : ""} + {pullRequest.snapshot?.checksState + ? ` · checks ${pullRequest.snapshot.checksState}` + : ""} +

+
+ ) : null} + {turnItem?.type === "dynamic_tool" ? ( + + ) : null} + {turnItem === undefined && pullRequest === undefined ? ( +

No additional details reported yet.

+ ) : null} + + ); +} + +export function BackgroundWorkDetails(props: BackgroundWorkDetailsProps) { + const streamsOutput = useCommandOutputStreaming(props.environmentId); + return ( +
+ {props.details.map((detail) => ( + + ))} +
+ ); +} diff --git a/apps/web/src/components/chat/ThreadActivityBanners.tsx b/apps/web/src/components/chat/ThreadActivityBanners.tsx index e132587a7595..4641a1ac30f4 100644 --- a/apps/web/src/components/chat/ThreadActivityBanners.tsx +++ b/apps/web/src/components/chat/ThreadActivityBanners.tsx @@ -1,18 +1,30 @@ import type { + EnvironmentId, OrchestrationV2PendingBackgroundTask, OrchestrationV2ProviderGoal, ThreadId, + ThreadPullRequestLink, } from "@t3tools/contracts"; -import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import type { EnvironmentThreadShell, ThreadStructure } from "@t3tools/client-runtime/state/shell"; import { - presentPendingBackgroundWork, + deriveBackgroundWorkDetails, presentProviderGoal, } from "@t3tools/client-runtime/state/thread-execution"; import { childThreadInputsTitle } from "@t3tools/client-runtime/state/threads"; -import { GitBranchIcon, MessageCircleIcon, ShieldQuestionIcon, TargetIcon } from "lucide-react"; -import { Fragment } from "react"; -import { cn } from "~/lib/utils"; +import { formatDuration } from "@t3tools/shared/orchestrationTiming"; +import { + CircleDashedIcon, + GitBranchIcon, + MessageCircleIcon, + ShieldQuestionIcon, + TargetIcon, + TerminalIcon, +} from "lucide-react"; +import { Fragment, useState, type ReactNode } from "react"; +import { tickTextContent } from "~/lib/tickTextContent"; import { Button, InlineButton } from "../ui/button"; +import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; +import { BackgroundWorkDetails } from "./BackgroundWorkDetails"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import type { ComposerBannerStackItem } from "./ComposerBannerStack"; import type { ThreadNowItem } from "./ThreadNow"; @@ -95,63 +107,139 @@ export function goalNowItem(input: { }; } +function BackgroundWorkPopover({ + title, + ...props +}: Parameters[0] & { readonly title: ReactNode }) { + const [open, setOpen] = useState(false); + return ( + + }>{title} + + {open ? ( + { + setOpen(false); + props.onOpenThread(threadId); + }} + onRunInTerminal={ + props.onRunInTerminal + ? (command) => { + setOpen(false); + props.onRunInTerminal?.(command); + } + : undefined + } + /> + ) : null} + + + ); +} + /** Background commands and subagents, for the end of the timeline. */ export function backgroundWorkNowItem(input: { + readonly environmentId: EnvironmentId; + readonly pullRequests?: ReadonlyArray | undefined; + readonly onRunInTerminal?: ((command: string) => void) | undefined; readonly threadId: ThreadId; readonly tasks: ReadonlyArray; + readonly turnItems: ThreadStructure["turnItems"]; readonly stopDisabled: boolean; readonly stopping: boolean; readonly onStop: () => Promise; readonly onOpenThread: (threadId: ThreadId) => void; }): ThreadNowItem | null { const { onOpenThread } = input; - const presentation = presentPendingBackgroundWork(input.tasks); - if (presentation === null) return null; + const backgroundWork = deriveBackgroundWorkDetails(input); + if (backgroundWork === null) return null; + const { presentation, details: rows } = backgroundWork; + const [only] = rows.length === 1 ? rows : []; + const newest = rows + .filter((row) => row.activity) + .toSorted((left, right) => right.updatedAtMs - left.updatedAtMs)[0]; + const label = (row: (typeof rows)[number]) => + row.isRawCommand ? {row.item.label} : row.item.label; + const showsRunningState = + only !== undefined && only.item.named && only.activity === null && !presentation.waiting; + const onlyThreadId = only?.childThreadId; + const startedAtMs = only?.startedAtMs ?? null; return { id: `background-work:${input.threadId}`, - icon: ( -