diff --git a/apps/mobile/assets/context-chip-icons/linear.png b/apps/mobile/assets/context-chip-icons/linear.png new file mode 100644 index 0000000000000..87870c2e16669 Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/linear.png differ diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt index 736f7cd3019f0..d4ba5eef976a3 100644 --- a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt +++ b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt @@ -415,6 +415,7 @@ class T3WorkspaceNavigationView( private fun tabTitle(tab: String) = when (tab) { "threads" -> "Chats" "pullRequests" -> "Pulls" + "linear" -> "Linear" "usage" -> "Usage" else -> "Settings" } @@ -427,6 +428,7 @@ class T3WorkspaceNavigationView( when (tab) { "threads" -> R.drawable.t3_chats "pullRequests" -> R.drawable.t3_pull_requests + "linear" -> R.drawable.t3_linear "usage" -> R.drawable.t3_usage else -> R.drawable.t3_settings } diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_linear.xml b/apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_linear.xml new file mode 100644 index 0000000000000..dd52806d170f1 --- /dev/null +++ b/apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_linear.xml @@ -0,0 +1,3 @@ + + + diff --git a/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift b/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift index f96c00962682c..e49dc16602f2b 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift @@ -99,8 +99,8 @@ final class T3SidebarTabBarView: ExpoView, UITabBarDelegate { private func prepareItems() { let iconBundle = Bundle(for: Self.self).url(forResource: "T3NativeControlIcons", withExtension: "bundle").flatMap(Bundle.init(url:)) let pullRequestIcon = UIImage(named: "pull-request", in: iconBundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) - let labels = ["threads": "Chats", "pullRequests": "PRs", "usage": "Usage", "settings": "Settings"] - let symbols = ["threads": "text.bubble", "usage": "chart.bar.xaxis", "settings": "gearshape"] + let labels = ["threads": "Chats", "pullRequests": "PRs", "linear": "Linear", "usage": "Usage", "settings": "Settings"] + let symbols = ["threads": "text.bubble", "linear": "circle.inset.filled", "usage": "chart.bar.xaxis", "settings": "gearshape"] for (tab, label) in labels { let icon = tab == "pullRequests" ? pullRequestIcon : UIImage(systemName: symbols[tab] ?? "circle") let item = UITabBarItem(title: nil, image: tabIcon(icon), tag: 0) diff --git a/apps/mobile/scripts/sync-context-chip-icons.mjs b/apps/mobile/scripts/sync-context-chip-icons.mjs index d99d4d3c98478..2f3dad05676dc 100644 --- a/apps/mobile/scripts/sync-context-chip-icons.mjs +++ b/apps/mobile/scripts/sync-context-chip-icons.mjs @@ -32,6 +32,20 @@ if (!skillSvg) { ); } +const linearIconSource = NodeFS.readFileSync( + NodePath.join(repositoryRoot, "apps/web/src/components/linear/linearIcons.tsx"), + "utf8", +); +const linearLogoPath = linearIconSource.match(/LINEAR_LOGO_PATH =\s*"([^"]*)"/)?.[1]; + +if (!linearLogoPath) { + throw new Error( + "Could not read LINEAR_LOGO_PATH from apps/web/src/components/linear/linearIcons.tsx", + ); +} + +const linearSvg = ``; + const lucideIcons = [ "circle-dashed", "film", @@ -83,8 +97,9 @@ for (const name of lucideIcons) { await renderIcon(name, await lucideSvg(name)); } await renderIcon("skill", skillSvg); +await renderIcon("linear", linearSvg); -const tokens = [...lucideIcons, "skill"].sort(); +const tokens = [...lucideIcons, "skill", "linear"].sort(); const generatedSource = `import type { ImageSourcePropType } from "react-native";\n\nexport const CONTEXT_CHIP_ICON_SOURCES = {\n${tokens .map( (token) => diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx index 225496bb7a407..ee8c99b3fc689 100644 --- a/apps/mobile/src/App.tsx +++ b/apps/mobile/src/App.tsx @@ -21,6 +21,7 @@ import { pipe } from "effect/Function"; import { RegistryContext } from "@effect/atom-react"; import { ProjectChipIconRasterizer } from "./native/ProjectChipIconImages"; +import { LinearStatusKeepAlive } from "./features/linear/LinearStatusKeepAlive"; import { ThreadArrangementHost } from "./features/threads/ThreadArrangementSheet"; import * as Dialog from "./components/ui/Dialog"; import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider"; @@ -226,6 +227,7 @@ function AppContent() { <> + diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index 872ca142c8aaa..3eba18f662d59 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -66,6 +66,18 @@ import { GitConfirmSheet } from "./features/threads/git/GitConfirmSheet"; import { GitOverviewSheet } from "./features/threads/git/GitOverviewSheet"; import { ThreadPullRequestsSheet } from "./features/threads/ThreadPullRequestsSheet"; import { ThreadAgentsSheet } from "./features/threads/ThreadAgentsSheet"; +import { PipelineCoordinatorRouteScreen } from "./features/threads/PipelineCoordinatorSheet"; +import { PipelineFeedbackSheet } from "./features/threads/PipelineFeedbackSheet"; +import { LinearIssueRouteScreen } from "./features/linear/LinearIssueRouteScreen"; +import { + LinearMilestoneScreen, + LinearProjectScreen, + LinearTeamScreen, +} from "./features/linear/LinearLevelScreens"; +import { LinearWorkspaceLinkScreen } from "./features/linear/LinearWorkspaceLinkScreen"; +import { LINEAR_LINK_PATHS } from "./features/linear/linearRoutes"; +import { LinearPipelineSheet } from "./features/linear/LinearPipelineSheet"; +import { LinearProjectPickerSheet } from "./features/linear/LinearProjectPickerSheet"; import { ThreadBackgroundWorkSheet } from "./features/threads/ThreadBackgroundWorkSheet"; import { ThreadQueueSheet } from "./features/threads/ThreadQueueControl"; import { @@ -111,6 +123,12 @@ import { SettingsScheduledTaskNewRouteScreen, SettingsScheduledTaskEditRouteScreen, } from "./features/settings/SettingsScheduledTasksRouteScreen"; +import { + SettingsPipelinesRouteScreen, + SettingsPipelineNewRouteScreen, + SettingsPipelineEditRouteScreen, +} from "./features/settings/SettingsPipelinesRouteScreen"; +import { PipelineStepModelPickerRouteScreen } from "./features/settings/PipelinePickerScreens"; import { ScheduledTaskModelPickerRouteScreen, ScheduledTaskBranchPickerRouteScreen, @@ -415,6 +433,35 @@ const SETTINGS_SCREENS = { }), }, }), + SettingsPipelines: createNativeStackScreen({ + screen: SettingsPipelinesRouteScreen, + linking: "settings/pipelines", + options: { + ...SETTINGS_PAGE_OPTIONS, + title: "Pipelines", + headerTitleStyle: { fontSize: 16, fontWeight: "800" }, + }, + }), + SettingsPipelineNew: createNativeStackScreen({ + screen: SettingsPipelineNewRouteScreen, + options: { ...SETTINGS_PAGE_OPTIONS, title: "New pipeline" }, + }), + SettingsPipelineEdit: createNativeStackScreen({ + screen: SettingsPipelineEditRouteScreen, + options: { ...SETTINGS_PAGE_OPTIONS, title: "Edit pipeline" }, + }), + SettingsPipelineStepModel: createNativeStackScreen({ + screen: PipelineStepModelPickerRouteScreen, + options: { + ...SETTINGS_PAGE_OPTIONS, + headerShown: false, + ...(Platform.OS === "android" + ? { presentation: "card" as const } + : { + ...THREAD_SETTINGS_SHEET_OPTIONS, + }), + }, + }), SettingsClientStorage: createNativeStackScreen({ screen: SettingsClientStorageRouteScreen, linking: "settings/client-storage", @@ -721,6 +768,31 @@ const RootStackConfig = createWorkspaceStackNavigator({ sheetGrabberVisible: true, }, }), + LinearWorkspace: createNativeStackScreen({ + screen: LinearWorkspaceLinkScreen, + linking: LINEAR_LINK_PATHS.LinearWorkspace, + options: { headerShown: false }, + }), + LinearTeam: createNativeStackScreen({ + screen: LinearTeamScreen, + linking: LINEAR_LINK_PATHS.LinearTeam, + options: DETAIL_HEADER_OPTIONS, + }), + LinearProject: createNativeStackScreen({ + screen: LinearProjectScreen, + linking: LINEAR_LINK_PATHS.LinearProject, + options: DETAIL_HEADER_OPTIONS, + }), + LinearMilestone: createNativeStackScreen({ + screen: LinearMilestoneScreen, + linking: LINEAR_LINK_PATHS.LinearMilestone, + options: DETAIL_HEADER_OPTIONS, + }), + LinearIssue: createNativeStackScreen({ + screen: LinearIssueRouteScreen, + linking: LINEAR_LINK_PATHS.LinearIssue, + options: DETAIL_HEADER_OPTIONS, + }), Thread: createNativeStackScreen({ screen: ThreadRouteScreen, linking: { path: "threads/:environmentId?/:threadId?", alias: ["new/draft"] }, @@ -911,6 +983,41 @@ const RootStackConfig = createWorkspaceStackNavigator({ sheetGrabberVisible: true, }, }), + PipelineCoordinator: createNativeStackScreen({ + screen: PipelineCoordinatorRouteScreen, + options: { + ...HORIZONTAL_FORM_SHEET_OPTIONS, + headerShown: false, + sheetAllowedDetents: formSheetDetents(0.9), + sheetGrabberVisible: true, + }, + }), + PipelineFeedback: createNativeStackScreen({ + screen: PipelineFeedbackSheet, + options: { + ...HORIZONTAL_FORM_SHEET_OPTIONS, + sheetAllowedDetents: formSheetDetents(0.7), + sheetGrabberVisible: true, + }, + }), + LinearProjectPicker: createNativeStackScreen({ + screen: LinearProjectPickerSheet, + options: { + ...(Platform.OS === "ios" ? SHEET_GLASS_HEADER_OPTIONS : undefined), + ...HORIZONTAL_FORM_SHEET_OPTIONS, + sheetAllowedDetents: formSheetDetents(0.6), + sheetGrabberVisible: true, + }, + }), + LinearPipeline: createNativeStackScreen({ + screen: LinearPipelineSheet, + options: { + ...(Platform.OS === "ios" ? SHEET_GLASS_HEADER_OPTIONS : undefined), + ...HORIZONTAL_FORM_SHEET_OPTIONS, + sheetAllowedDetents: formSheetDetents(0.9), + sheetGrabberVisible: true, + }, + }), GitOverview: createNativeStackScreen({ screen: GitOverviewSheet, linking: `${THREAD_LINKING_PREFIX}/git`, diff --git a/apps/mobile/src/components/ComposerContextSheet.tsx b/apps/mobile/src/components/ComposerContextSheet.tsx index 8121bfdece763..4f5e959270937 100644 --- a/apps/mobile/src/components/ComposerContextSheet.tsx +++ b/apps/mobile/src/components/ComposerContextSheet.tsx @@ -13,6 +13,7 @@ import type { import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { videoMimeType } from "@t3tools/shared/video"; +import type { LinearIssueContextRecord } from "@t3tools/contracts"; import { Platform, Pressable, ScrollView, View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { REVIEW_MONO_FONT_FAMILY } from "../features/review/reviewDiffRendering"; @@ -23,6 +24,7 @@ import { type DraftComposerAttachment, } from "../lib/composerImages"; import { contextImageGallery } from "../lib/contextImageGallery"; +import { tryOpenWebLink } from "../lib/openExternalUrl"; import { FilePreviewModal } from "./FilePreviewModal"; import { VideoPreviewModal } from "./VideoPreviewModal"; import { ComposerContextAttachment } from "./ComposerContextAttachment"; @@ -75,6 +77,60 @@ function ContextSource(props: { source: ElementContextSource | null }) { ); } +function LinearIssueSnapshot(props: { readonly record: LinearIssueContextRecord }) { + const { record } = props; + const breadcrumb = [record.teamName, record.projectName, record.milestoneName].filter( + (part): part is string => part !== null && part.length > 0, + ); + const meta = [record.stateName, record.priorityLabel, record.assigneeName].filter( + (part): part is string => part !== null && part.length > 0, + ); + const excerpt = record.description.trim().slice(0, 600); + return ( + + + + + + {record.subIssues.length > 0 ? ( + `${sub.identifier} ${sub.title}`) + .concat(record.subIssues.length > 5 ? [`and ${record.subIssues.length - 5} more`] : []) + .join("\n")} + /> + ) : null} + {record.comments.length > 0 ? ( + `${comment.author ?? "Unknown"}: ${comment.body.trim().slice(0, 200)}`, + ) + .join("\n")} + /> + ) : null} + + Snapshot taken when attached; later edits in Linear are not included. + + {/^https?:\/\//i.test(record.url) ? ( + + + + + + { @@ -1855,6 +2052,13 @@ export default function GitActionsControl({ {pendingDefaultBranchActionCopy?.title ?? "Run action on default branch?"} {pendingDefaultBranchActionCopy?.description} + {repositoryName !== undefined && pendingDefaultBranchAction ? ( +

+ {`${repositoryName} · ${pendingDefaultBranchAction.branchName}${ + pushRemoteName === null ? "" : ` → ${pushRemoteName}` + }`} +

+ ) : null} {featureBranchUnavailableReason && (

{featureBranchUnavailableReason}

)} diff --git a/apps/web/src/components/HomeGitInitDialog.tsx b/apps/web/src/components/HomeGitInitDialog.tsx new file mode 100644 index 0000000000000..2c9a94e070f4d --- /dev/null +++ b/apps/web/src/components/HomeGitInitDialog.tsx @@ -0,0 +1,202 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import { threadRepositoriesTarget } from "@t3tools/client-runtime/state/thread-repositories"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import type { WorkspaceHomeGitInitPreview } from "@t3tools/contracts"; +import { useState } from "react"; + +import { appAtomRegistry } from "../rpc/atomRegistry"; +import { useAtomCommand } from "../state/use-atom-command"; +import { vcsEnvironment } from "../state/vcs"; +import { workspaceRepositoryEnvironment } from "../state/workspaceRepositories"; +import { Button } from "./ui/button"; +import { + Dialog, + DialogDescription, + DialogFooter, + DialogHeader, + DialogPanel, + DialogPopup, + DialogTitle, +} from "./ui/dialog"; +import { Label } from "./ui/label"; +import { stackedThreadToast, toastManager } from "./ui/toast"; + +type HomeGitProject = Pick< + EnvironmentProject, + "environmentId" | "id" | "title" | "workspaceRoot" | "trackedFolders" +>; + +function errorMessage(error: unknown) { + return error instanceof Error && error.message.trim().length > 0 + ? error.message + : "An error occurred."; +} + +/** + * "Initialize Git and commit home files" for a plain home folder with tracked repos: worktrees + * need a Git home. `start` loads the preview first, so the confirm shows exactly what commits. + */ +export function useHomeGitInit(project: HomeGitProject | null, onInitialized?: () => void) { + const canInitialize = useAtomValue( + workspaceRepositoryEnvironment.initializeHomeGit.permissionAtom(project?.environmentId ?? null), + ); + const previewHomeGitInit = useAtomCommand(workspaceRepositoryEnvironment.previewHomeGitInit, { + reportFailure: false, + }); + const [preview, setPreview] = useState(null); + const [loading, setLoading] = useState(false); + + const start = async () => { + if (project === null || loading) return; + setLoading(true); + const result = await previewHomeGitInit({ + environmentId: project.environmentId, + input: { projectId: project.id }, + }); + setLoading(false); + if (result._tag === "Failure") { + if (!isAtomCommandInterrupted(result)) { + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not prepare the first commit", + description: errorMessage(squashAtomCommandFailure(result)), + }), + ); + } + return; + } + setPreview(result.value); + }; + + const dialog = + project !== null && preview !== null ? ( + setPreview(null)} + {...(onInitialized ? { onInitialized } : {})} + /> + ) : null; + + return { canInitialize: project !== null && canInitialize, loading, start, dialog }; +} + +function HomeGitInitDialog({ + project, + preview, + onClose, + onInitialized, +}: { + project: HomeGitProject; + preview: WorkspaceHomeGitInitPreview; + onClose: () => void; + onInitialized?: () => void; +}) { + const initializeHomeGit = useAtomCommand(workspaceRepositoryEnvironment.initializeHomeGit, { + reportFailure: false, + }); + const refreshStatus = useAtomCommand(vcsEnvironment.refreshStatus, { reportFailure: false }); + const [submitting, setSubmitting] = useState(false); + const [error, setError] = useState(null); + const hiddenFileCount = preview.fileCount - preview.files.length; + + const submit = async () => { + if (submitting) return; + setSubmitting(true); + setError(null); + const result = await initializeHomeGit({ + environmentId: project.environmentId, + input: { projectId: project.id }, + }); + if (result._tag === "Failure") { + setSubmitting(false); + if (!isAtomCommandInterrupted(result)) + setError(errorMessage(squashAtomCommandFailure(result))); + return; + } + // The composer reads Git-ness from the status stream and the repo list; both changed. + await refreshStatus({ + environmentId: project.environmentId, + input: { cwd: project.workspaceRoot }, + }); + const target = threadRepositoriesTarget({ + environmentId: project.environmentId, + project, + worktreePath: null, + }); + if (target !== null) { + appAtomRegistry.refresh(workspaceRepositoryEnvironment.repositories(target)); + } + toastManager.add( + stackedThreadToast({ + type: "success", + title: `Committed ${result.value.fileCount} ${result.value.fileCount === 1 ? "file" : "files"}`, + description: project.workspaceRoot, + }), + ); + onClose(); + onInitialized?.(); + }; + + return ( + { + if (!open && !submitting) onClose(); + }} + > + + + Initialize Git and commit home files + + New worktrees need {project.title} to be a Git repo. This runs git init in{" "} + {project.workspaceRoot} and makes a first commit. + + + +
+ +
+ {preview.files.map((file) => ( +
+ {file} +
+ ))} + {hiddenFileCount > 0 ? ( +
and {hiddenFileCount} more
+ ) : null} +
+
+ {preview.ignoreEntries.length > 0 ? ( +
+ +
+ {preview.ignoreEntries.map((entry) => ( +
+ {entry} +
+ ))} +
+
+ ) : null} + {error ?

{error}

: null} +
+ + + + +
+
+ ); +} diff --git a/apps/web/src/components/LinearIssueContextChip.tsx b/apps/web/src/components/LinearIssueContextChip.tsx new file mode 100644 index 0000000000000..8949263d60a0c --- /dev/null +++ b/apps/web/src/components/LinearIssueContextChip.tsx @@ -0,0 +1,132 @@ +import type { LinearIssueContextRecord, LinearStateType } from "@t3tools/contracts"; +import { linearIssueExtrasSummary } from "@t3tools/shared/linearLaunch"; + +import { ContextChip, ContextChipLabel } from "./ContextChip"; +import ChatMarkdown from "./ChatMarkdown"; +import { LinearGlyph, LinearStateIcon } from "./linear/linearIcons"; +import { PreviewCard, PreviewCardPopup, PreviewCardTrigger } from "./ui/preview-card"; + +const LINEAR_STATE_TYPES: ReadonlySet = new Set([ + "triage", + "backlog", + "unstarted", + "started", + "completed", + "canceled", +]); + +function asStateType(value: string): LinearStateType { + return LINEAR_STATE_TYPES.has(value) ? (value as LinearStateType) : "unstarted"; +} + +function LinearIssuePreview({ record }: { readonly record: LinearIssueContextRecord }) { + const crumbs = [record.teamName, record.projectName, record.milestoneName].filter( + (part): part is string => part !== null && part.length > 0, + ); + const meta = [record.priorityLabel, record.assigneeName].filter( + (part): part is string => part !== null && part.length > 0, + ); + const excerpt = record.description.trim().slice(0, 600); + return ( +
+
{crumbs.join(" › ")}
+
+ +
+
+ {record.identifier}{" "} + {record.title} +
+
{[record.stateName, ...meta].join(" · ")}
+
+
+ {record.labels.length > 0 ? ( +
+ {record.labels.map((label) => ( + + {label} + + ))} +
+ ) : null} + {excerpt ? ( +
+ +
+ ) : null} + {record.subIssues.length > 0 ? ( +
+
+ Sub-issues ({record.subIssues.length}) +
+ {record.subIssues.slice(0, 5).map((sub) => ( +
+ + {sub.identifier} + {sub.title} +
+ ))} + {record.subIssues.length > 5 ? ( +
+ and {record.subIssues.length - 5} more +
+ ) : null} +
+ ) : null} + {record.comments.length > 0 ? ( +
+
+ Comments ({record.comments.length}) +
+ {record.comments.slice(-2).map((comment) => ( +
+ {comment.author ?? "Unknown"}{" "} + {comment.body.trim()} +
+ ))} +
+ ) : null} +
+ Snapshot taken when attached; later edits in Linear are not included. +
+
+ ); +} + +/** Inline chip for an attached Linear issue, with a hover card of what the agent will read. */ +export function LinearIssueContextChip(props: { + record: LinearIssueContextRecord; + copyMarkdown?: string; +}) { + const { record } = props; + const extras = linearIssueExtrasSummary(record); + return ( + + } + aria-label={`Linear issue, ${record.identifier}: ${record.title}`} + data-markdown-copy={props.copyMarkdown} + className="no-underline" + > + + {`${record.identifier} · ${record.title}`} + {extras ? ( + {extras} + ) : null} + + } + /> + + + + + ); +} diff --git a/apps/web/src/components/PipelineProgressBar.tsx b/apps/web/src/components/PipelineProgressBar.tsx new file mode 100644 index 0000000000000..797ec359bdbcd --- /dev/null +++ b/apps/web/src/components/PipelineProgressBar.tsx @@ -0,0 +1,109 @@ +import { + countFinishedPipelineSegments, + type PipelineProgressStatus, +} from "@t3tools/client-runtime/state/pipeline-nesting"; +import type { ThreadId } from "@t3tools/contracts"; + +import { cn } from "../lib/utils"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; + +export interface PipelineProgressBarSegment { + readonly stepId: string; + readonly label: string; + readonly status: PipelineProgressStatus; + /** The step's latest thread; null until the step starts. */ + readonly threadId: ThreadId | null; +} + +const PIPELINE_PROGRESS_SEGMENT_CLASS: Record = { + completed: "bg-success", + running: "bg-info", + attention: "bg-indigo-500 dark:bg-indigo-400", + failed: "bg-destructive", + stopped: + "bg-[repeating-linear-gradient(135deg,currentColor_0_2px,transparent_2px_4px)] text-muted-foreground/70", + skipped: "bg-muted-foreground/35", + pending: "bg-muted-foreground/15", +}; + +const PIPELINE_PROGRESS_STATUS_LABEL: Record = { + completed: "Done", + running: "Running", + attention: "Needs you", + failed: "Failed", + stopped: "Stopped", + skipped: "Skipped", + pending: "Pending", +}; + +/** One segment per step, coloured by its status, with a done count. A started step's segment opens it. */ +export function PipelineProgressBar(props: { + segments: ReadonlyArray; + onOpenStep: (threadId: ThreadId) => void; + tooltipSide?: "left" | "right" | "top" | "bottom"; + className?: string; +}) { + const { segments } = props; + const finished = countFinishedPipelineSegments(segments); + const summary = `${finished} of ${segments.length} steps done`; + return ( +
+ + } + > + {segments.map((segment) => { + const threadId = segment.threadId; + return ( + { + event.preventDefault(); + event.stopPropagation(); + props.onOpenStep(threadId); + } + } + > + + + ); + })} + + +
    + {segments.map((segment, index) => ( +
  1. + + + {index + 1}. {segment.label} + + + {PIPELINE_PROGRESS_STATUS_LABEL[segment.status]} + +
  2. + ))} +
+
+
+ + {finished}/{segments.length} + +
+ ); +} diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index 596bdee96ad1f..b04a0dd4fab62 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -44,6 +44,7 @@ import { Files, Globe2, MessagesSquare, + MessageSquare as MessageSquareIcon, Plus, TerminalSquare, } from "lucide-react"; @@ -590,6 +591,8 @@ function surfaceTitle( return `#${surface.number}`; case "pull-requests": return "Pull requests"; + case "pipeline-coordinator": + return "Coordinator"; case "device": return surface.title ?? surface.target?.name ?? "Device"; case "side-chat": @@ -684,6 +687,8 @@ function SurfaceIcon({ return ; case "side-chat": return ; + case "pipeline-coordinator": + return ; case "device": return surface.target?.platform === "ios" ? ( diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 669c805492bcc..5400a5ece3424 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -565,6 +565,7 @@ function makeProject(overrides: Partial = {}): Project { createdAt: "2026-03-09T10:00:00.000Z", updatedAt: "2026-03-09T10:00:00.000Z", scripts: [], + trackedFolders: [], ...rest, }; } diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 55cf694c2b79e..2505e6b36a156 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -1,6 +1,13 @@ import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection"; import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment"; import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models"; +import { + aggregatePipelineStepStatus, + pipelineProgressSegments, + type PipelineNestable, + type PipelineProgressStatus, + type PipelineStepStatus, +} from "@t3tools/client-runtime/state/pipeline-nesting"; import { isShownUnderParent } from "@t3tools/client-runtime/state/threads"; import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests"; @@ -21,6 +28,7 @@ import { isListedThreadLineage, type ContextMenuItem, type EnvironmentId, + type PipelineRunSummary, type ThreadId, } from "@t3tools/contracts"; import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings"; @@ -908,6 +916,40 @@ export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): Si return "ready"; } +/** What a pipeline's parent row shows for its steps and live run; see `mergePipelineParentStatus`. */ +export function resolveSidebarPipelineStepStatus( + steps: ReadonlyArray, + run?: Pick | null, +): PipelineStepStatus | null { + return aggregatePipelineStepStatus(steps, resolveSidebarThreadStatus, run); +} + +/** One segment of a pipeline parent's progress bar, flat so row props compare by value. */ +export interface SidebarPipelineProgressSegment { + readonly stepId: string; + readonly label: string; + readonly status: PipelineProgressStatus; + /** The step's latest thread, in the parent's environment; null until the step starts. */ + readonly threadId: ThreadId | null; +} + +/** The segments of a pipeline parent's collapsed progress bar; undefined when it has none. */ +export function resolveSidebarPipelineProgress< + T extends SidebarThreadStatusInput & PipelineNestable & { readonly title: string }, +>( + run: PipelineRunSummary | undefined, + steps: readonly T[], +): ReadonlyArray | undefined { + const segments = pipelineProgressSegments(run, steps, resolveSidebarThreadStatus); + if (segments.length === 0) return undefined; + return segments.map((segment) => ({ + stepId: segment.stepId, + label: segment.label, + status: segment.status, + threadId: segment.thread?.id ?? null, + })); +} + /** * The dot on a closed boring-sidebar folder: the most urgent state among its * hidden threads. Waiting threads stay quiet, like their rows. diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 8eb32a605822a..208a5eff1f088 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -35,6 +35,15 @@ import { isThreadWorking, } from "@t3tools/client-runtime/state/thread-inbox"; import { sortSettledThreads } from "@t3tools/client-runtime/state/thread-sort"; +import { + isPipelineGroupActive, + livePipelineRunOf, + nestPipelineSteps, + pipelineParentsOfSteps, + pipelineStepLabel, + pipelineStepsOfParents, + type PipelineLiveRuns, +} from "@t3tools/client-runtime/state/pipeline-nesting"; import { nextShownOrder, threadSearchMatchKey, @@ -152,7 +161,7 @@ import { useQuietThreadShells, } from "../state/entities"; import { environmentPresentations } from "../state/presentation"; -import { primaryServerKeybindingsAtom } from "../state/server"; +import { primaryServerKeybindingsAtom, serverEnvironment } from "../state/server"; import { environmentProjects } from "../state/projects"; import { threadEnvironment } from "../state/threads"; import { useOlderSettledShelf, useOlderSettledShelfGrowth } from "../state/olderSettledShelf"; @@ -197,6 +206,8 @@ import { resolveSidebarSweepKeys, resolveSidebarDropTarget, resolveSidebarDropVerb, + resolveSidebarPipelineProgress, + resolveSidebarPipelineStepStatus, resolveSidebarThreadSection, resolveSidebarReorderableThreadKeys, searchSidebarThreads, @@ -351,6 +362,7 @@ interface SidebarThreadPartitionInput { readonly delegatedUnderParent: ReadonlySet; readonly serverConfigs: ReadonlyMap; readonly connectedEnvironmentIds: readonly EnvironmentId[]; + readonly pipelineLiveRuns: PipelineLiveRuns; readonly optimisticDrop: SidebarOptimisticDrop | null; readonly workingShelfEnabled: boolean; /** Boring mode: folders list active threads by the user's latest message. */ @@ -402,12 +414,20 @@ function resolveDraggedOrders(input: { }; } +// A pipeline's steps show with their parent, so an open step keeps the parent's row in view. function routeThreadOnly( threads: readonly EnvironmentThreadShell[], routeThreadKey: string | null, + stepsByParentKey: ReadonlyMap, ): readonly EnvironmentThreadShell[] { if (routeThreadKey === null) return EMPTY_THREADS; - const routeThread = threads.find((thread) => threadShellKey(thread) === routeThreadKey); + const routeThread = threads.find( + (thread) => + threadShellKey(thread) === routeThreadKey || + stepsByParentKey + .get(threadShellKey(thread)) + ?.some((step) => threadShellKey(step) === routeThreadKey), + ); return routeThread === undefined ? EMPTY_THREADS : [routeThread]; } @@ -417,6 +437,7 @@ function useSidebarThreads(input: { readonly scopedProjectKeys: ReadonlySet | null; readonly serverConfigs: ReadonlyMap; readonly connectedEnvironmentIds: readonly EnvironmentId[]; + readonly pipelineLiveRuns: PipelineLiveRuns; readonly optimisticDrop: SidebarOptimisticDrop | null; readonly threads: readonly EnvironmentThreadShell[]; readonly delegatedUnderParent: ReadonlySet; @@ -431,6 +452,7 @@ function useSidebarThreads(input: { scopedProjectKeys, serverConfigs, connectedEnvironmentIds, + pipelineLiveRuns, optimisticDrop, threads, delegatedUnderParent, @@ -478,6 +500,8 @@ function useSidebarThreads(input: { // Shared with the old per-project sidebar, so folders keep their open state. const projectExpandedById = useUiStateStore((store) => store.projectExpandedById); const setProjectExpanded = useUiStateStore((store) => store.setProjectExpanded); + const expandedPipelineThreadKeys = useUiStateStore((store) => store.expandedPipelineThreadKeys); + const setPipelineExpanded = useUiStateStore((store) => store.setPipelineExpanded); const [settledTail, setSettledTail] = useState({ scopeKey: projectScopeKey, count: SETTLED_TAIL_INITIAL_COUNT, @@ -494,6 +518,7 @@ function useSidebarThreads(input: { delegatedUnderParent, serverConfigs, connectedEnvironmentIds, + pipelineLiveRuns, optimisticDrop, workingShelfEnabled, sortActiveBySend: folderGroups !== null, @@ -501,8 +526,14 @@ function useSidebarThreads(input: { clockKey: `${nowMinute}:${snoozeWakeClock}:${inboxReturnsVersion}`, }); - const { pinnedThreads, activeThreads, workingThreads, snoozedThreads, settledThreads } = - partition; + const { + pinnedThreads, + activeThreads, + workingThreads, + snoozedThreads, + settledThreads, + pipelineStepsByParentKey, + } = partition; // Older settled threads load in pages; the shelf lists them only as far as they are loaded. const olderSettledShelf = useOlderSettledShelf({ scopes: olderSettledScopes([...serverConfigs.keys()], scopedProjectKeys), @@ -519,22 +550,24 @@ function useSidebarThreads(input: { routeRowThreadKey !== null && !visible.some((thread) => threadShellKey(thread) === routeRowThreadKey) ) { - const routeThread = settledThreads.find( - (thread) => threadShellKey(thread) === routeRowThreadKey, + const [routeThread] = routeThreadOnly( + settledThreads, + routeRowThreadKey, + pipelineStepsByParentKey, ); - if (routeThread !== undefined) visible.push(routeThread); + if (routeThread !== undefined && !visible.includes(routeThread)) visible.push(routeThread); } return visible.length === settledThreads.length ? settledThreads : visible; })(); const renderedSettledThreads = settledShelfExpanded ? visibleSettledThreads - : routeThreadOnly(visibleSettledThreads, routeRowThreadKey); + : routeThreadOnly(visibleSettledThreads, routeRowThreadKey, pipelineStepsByParentKey); const visibleSnoozedThreads = snoozedShelfExpanded ? snoozedThreads - : routeThreadOnly(snoozedThreads, routeRowThreadKey); + : routeThreadOnly(snoozedThreads, routeRowThreadKey, pipelineStepsByParentKey); const visibleWorkingThreads = workingShelfExpanded ? workingThreads - : routeThreadOnly(workingThreads, routeRowThreadKey); + : routeThreadOnly(workingThreads, routeRowThreadKey, pipelineStepsByParentKey); const projectFolders = folderGroups === null ? null @@ -548,21 +581,49 @@ function useSidebarThreads(input: { collapsed, // A closed folder still shows the open thread, and hints at the rest. threads: collapsed - ? routeThreadOnly(folder.threads, routeRowThreadKey) + ? routeThreadOnly(folder.threads, routeRowThreadKey, pipelineStepsByParentKey) : folder.threads, + // Steps count with their parent, so a closed folder still shows a running step. hiddenThreads: collapsed - ? folder.threads.filter((thread) => threadShellKey(thread) !== routeRowThreadKey) + ? folder.threads + .flatMap((thread) => [ + thread, + ...(pipelineStepsByParentKey.get(threadShellKey(thread)) ?? EMPTY_THREADS), + ]) + .filter((thread) => threadShellKey(thread) !== routeRowThreadKey) : EMPTY_THREADS, }; }); + // A collapsed pipeline draws its progress bar instead of its steps, like a closed folder + // keeping only the open step in view. + const expandedPipelines = new Set(expandedPipelineThreadKeys); + const shownPipelineStepsByParentKey = new Map(); + for (const [parentKey, steps] of pipelineStepsByParentKey) { + const shown = expandedPipelines.has(parentKey) + ? steps + : steps.filter((step) => threadShellKey(step) === routeRowThreadKey); + if (shown.length > 0) shownPipelineStepsByParentKey.set(parentKey, shown); + } + const withStepsFrom = + (stepsByParentKey: ReadonlyMap) => + (list: readonly EnvironmentThreadShell[]) => + stepsByParentKey.size === 0 + ? list + : list.flatMap((thread) => [ + thread, + ...(stepsByParentKey.get(threadShellKey(thread)) ?? EMPTY_THREADS), + ]); + const withSteps = withStepsFrom(pipelineStepsByParentKey); + // Keyboard order, jump numbers and range selection follow the rows as drawn: shown steps right after their parent. + const withShownSteps = withStepsFrom(shownPipelineStepsByParentKey); const orderedThreads = [ - ...pinnedThreads, - ...(projectFolders === null - ? activeThreads - : projectFolders.flatMap((folder) => folder.threads)), - ...visibleWorkingThreads, - ...visibleSnoozedThreads, - ...renderedSettledThreads, + ...withShownSteps(pinnedThreads), + ...withShownSteps( + projectFolders === null ? activeThreads : projectFolders.flatMap((folder) => folder.threads), + ), + ...withShownSteps(visibleWorkingThreads), + ...withShownSteps(visibleSnoozedThreads), + ...withShownSteps(renderedSettledThreads), ]; const sectionByThreadKey = new Map(); for (const [list, section] of [ @@ -572,18 +633,18 @@ function useSidebarThreads(input: { [snoozedThreads, "snoozed"], [settledThreads, "settled"], ] as const) { - for (const thread of list) sectionByThreadKey.set(threadShellKey(thread), section); + for (const thread of withSteps(list)) sectionByThreadKey.set(threadShellKey(thread), section); } return { ...partition, threads, workingShelfEnabled, searchableThreads: [ - ...pinnedThreads, - ...activeThreads, - ...workingThreads, - ...snoozedThreads, - ...settledThreads, + ...withSteps(pinnedThreads), + ...withSteps(activeThreads), + ...withSteps(workingThreads), + ...withSteps(snoozedThreads), + ...withSteps(settledThreads), ], settledVisibleCount, settledCount, @@ -600,6 +661,9 @@ function useSidebarThreads(input: { toggleSnoozedShelf: () => setSnoozedShelfExpanded((value) => !value), workingShelfExpanded, toggleWorkingShelf: () => setWorkingShelfExpanded((value) => !value), + shownPipelineStepsByParentKey, + expandedPipelines, + setPipelineExpanded, projectFolders, toggleProjectFolder: (group: SidebarProjectSnapshot) => { const keys = sidebarFolderExpansionKeys(group); @@ -610,8 +674,8 @@ function useSidebarThreads(input: { visibleWorkingThreads, orderedThreadKeys: orderedThreads.map(threadShellKey), threadByKey: new Map(orderedThreads.map((thread) => [threadShellKey(thread), thread] as const)), - settledThreadKeys: new Set(settledThreads.map(threadShellKey)), - snoozedThreadKeys: new Set(snoozedThreads.map(threadShellKey)), + settledThreadKeys: new Set(withSteps(settledThreads).map(threadShellKey)), + snoozedThreadKeys: new Set(withSteps(snoozedThreads).map(threadShellKey)), sectionByThreadKey, pinnedKeys: pinnedThreads.map(threadShellKey), activeKeys: activeThreads.map(threadShellKey), @@ -630,6 +694,7 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) { scopedProjectKeys, delegatedUnderParent, serverConfigs, + pipelineLiveRuns, optimisticDrop, workingShelfEnabled, sortActiveBySend, @@ -641,24 +706,54 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) { const pinned: EnvironmentThreadShell[] = []; const active: EnvironmentThreadShell[] = []; const working: EnvironmentThreadShell[] = []; + const pipelineParentOf = pipelineParentsOfSteps(visible); + const pipelineStepsOf = pipelineStepsOfParents(visible, pipelineParentOf); + // A pipeline counts as working while any of its steps does, so it stays on the shelf. const inbox = (thread: EnvironmentThreadShell, manuallyMoved = false) => belongsInSidebarWorkingShelf(thread, { enabled: workingShelfEnabled, disconnectedEnvironmentIds, - isWorking: manuallyMoved ? isThreadWorking : inboxObservation.isWorking, + isWorking: (candidate) => + isPipelineGroupActive( + candidate, + pipelineStepsOf, + manuallyMoved ? isThreadWorking : inboxObservation.isWorking, + pipelineLiveRuns, + ), }) ? working : active; const snoozed: EnvironmentThreadShell[] = []; const settled: EnvironmentThreadShell[] = []; const { draggableThreadKeys, activeReorderableThreadKeys } = resolveSidebarReorderableThreadKeys({ - threads: visible, + // A pipeline's steps move with their parent, never on their own. + threads: visible.filter((thread) => !pipelineParentOf.has(threadShellKey(thread))), serverConfigs, connectedEnvironmentIds: input.connectedEnvironmentIds, }); - for (const thread of visible) { + for (const step of visible) { + // A pipeline's steps go where their parent goes, so the run stays together. + const parent = pipelineParentOf.get(threadShellKey(step)); + const thread = parent ?? step; const configLoaded = serverConfigs.has(thread.environmentId); - const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); + const threadKey = threadShellKey(thread); + if (parent !== undefined) { + const section = resolveSidebarThreadSection({ + snoozed: configLoaded && effectiveSnoozed(parent, { now: preciseNow }), + settled: configLoaded && parent.settledOverride === "settled", + pinned: parent.pinnedAt != null, + }); + const dropSection = optimisticDrop?.key === threadKey ? optimisticDrop.section : section; + (dropSection === "snoozed" + ? snoozed + : dropSection === "settled" + ? settled + : dropSection === "pinned" + ? pinned + : inbox(parent, optimisticDrop?.key === threadKey) + ).push(step); + continue; + } if (optimisticDrop?.key === threadKey) { const projected = applySidebarThreadDrop( thread, @@ -693,13 +788,47 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) { } } // Availability gates dragging only; sorting must stay consistent across clients. - const sortedPinned = sortPinnedThreadsForSidebar(pinned); - const sortedActive = sortActiveBySend - ? sortWorkingThreadsBySend(active) - : workingShelfEnabled - ? sortInboxThreadsByReturn(active, inboxObservation.returnedAt) - : sortThreadsForSidebar(active); + // Steps sort with everything else, then fold under their parent where the first of the run sits. + const nestedPinned = nestPipelineSteps(sortPinnedThreadsForSidebar(pinned), { + anchored: (parent) => parent.pinOrderKey != null, + }); + const nestedActive = nestPipelineSteps( + sortActiveBySend + ? sortWorkingThreadsBySend(active) + : workingShelfEnabled + ? sortInboxThreadsByReturn(active, inboxObservation.returnedAt) + : sortThreadsForSidebar(active), + { + anchored: (parent) => + !workingShelfEnabled && !sortActiveBySend && parent.activeOrderKey != null, + }, + ); + const nestedWorking = nestPipelineSteps(sortWorkingThreadsBySend(working)); + const nestedSnoozed = nestPipelineSteps( + snoozed.toSorted( + (left, right) => + firstValidTimestampMs(left.snoozedUntil ?? null) - + firstValidTimestampMs(right.snoozedUntil ?? null), + ), + ); + const nestedSettled = nestPipelineSteps(sortSettledThreads(settled)); + const sortedPinned = nestedPinned.rows; + const sortedActive = nestedActive.rows; + const pipelineStepsByParentKey = new Map([ + ...nestedPinned.stepsByParentKey, + ...nestedActive.stepsByParentKey, + ...nestedWorking.stepsByParentKey, + ...nestedSnoozed.stepsByParentKey, + ...nestedSettled.stepsByParentKey, + ]); + // Steps nested under a parent in the list; a step whose parent is absent is an ordinary row. + const pipelineParentKeyByStepKey = new Map(); + for (const [parentKey, steps] of pipelineStepsByParentKey) { + for (const step of steps) pipelineParentKeyByStepKey.set(threadShellKey(step), parentKey); + } return { + pipelineStepsByParentKey, + pipelineParentKeyByStepKey, pinnedThreads: optimisticDrop?.section !== "pinned" || optimisticDrop.order === null ? sortedPinned @@ -718,13 +847,9 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) { preferredIds: optimisticDrop.order, getId: (thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), }), - workingThreads: sortWorkingThreadsBySend(working), - snoozedThreads: snoozed.toSorted( - (left, right) => - firstValidTimestampMs(left.snoozedUntil ?? null) - - firstValidTimestampMs(right.snoozedUntil ?? null), - ), - settledThreads: sortSettledThreads(settled), + workingThreads: nestedWorking.rows, + snoozedThreads: nestedSnoozed.rows, + settledThreads: nestedSettled.rows, visibleThreads: visible, snoozeNow: preciseNow, }; @@ -823,6 +948,16 @@ function useSidebarLookups() { const projects = useProjects(); const environments = useEnvironmentIdentities(); const serverConfigs = useServerConfigs(); + // One stream per environment that offers pipelines; rows read paused runs and step names from it. + const pipelineLiveRuns = useAtomValue( + serverEnvironment.pipelineLiveRunsAtom( + [...serverConfigs] + .filter(([, config]) => config.environment.capabilities.pipelines === true) + .map(([environmentId]) => environmentId) + .toSorted() + .join("\n"), + ), + ); const providerEntriesByEnvironment = useAtomValue(sidebarProviderEntriesAtom); const projectGroups = useSidebarProjectGroups(); const environmentLabelById = new Map( @@ -851,6 +986,7 @@ function useSidebarLookups() { return { projects, serverConfigs, + pipelineLiveRuns, projectGroups, environmentLabelById, providerEntriesByEnvironment, @@ -915,6 +1051,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const { projects, serverConfigs, + pipelineLiveRuns, projectGroups, environmentLabelById, providerEntriesByEnvironment, @@ -1317,6 +1454,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve settledThreads, snoozeNow, searchableThreads, + pipelineStepsByParentKey, + pipelineParentKeyByStepKey, + shownPipelineStepsByParentKey, + expandedPipelines, + setPipelineExpanded, settledVisibleCount, settledCount, olderSettledShelf, @@ -1347,6 +1489,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve scopedProjectKeys, serverConfigs, connectedEnvironmentIds, + pipelineLiveRuns, optimisticDrop, threads, delegatedUnderParent, @@ -1590,12 +1733,18 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve navigateToThread(threadRef); }; + // The route's row: an open pipeline step stands in as its parent, which is what settles or snoozes. + const readRouteRowKey = () => { + const routeKey = readRouteThreadKey(router); + return routeKey === null ? null : (pipelineParentKeyByStepKey.get(routeKey) ?? routeKey); + }; + // Snapshot navigation before partition mutation; background parks use a null plan. const planForwardNavigation = ( threadKey: string, coParkingKeys?: ReadonlySet, ): (() => void) | null => { - if (readRouteThreadKey(router) !== threadKey) return null; + if (readRouteRowKey() !== threadKey) return null; const shell = threadByKeyRef.current.get(threadKey); const orderedKeys = orderedThreadKeysRef.current; const settledKeys = settledThreadKeysRef.current; @@ -1605,7 +1754,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve currentIndex === -1 ? null : ([...orderedKeys.slice(currentIndex + 1), ...orderedKeys.slice(0, currentIndex)].find( - (key) => !settledKeys.has(key) && !snoozedKeys.has(key) && !coParkingKeys?.has(key), + (key) => + !settledKeys.has(key) && + !snoozedKeys.has(key) && + !coParkingKeys?.has(key) && + pipelineParentKeyByStepKey.get(key) !== threadKey, ) ?? null); const nextThread = nextCardKey ? threadByKeyRef.current.get(nextCardKey) : null; return nextThread @@ -1616,9 +1769,16 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }; const attemptSettle = ( - threadRef: ScopedThreadRef, + requestedRef: ScopedThreadRef, opts: { coSettlingKeys?: ReadonlySet } = {}, ) => { + // Only a pipeline's parent settles; a step stands for its run (settle-and-advance from an open step). + const parentKey = pipelineParentKeyByStepKey.get(scopedThreadKey(requestedRef)); + const parent = parentKey === undefined ? undefined : threadByKeyRef.current.get(parentKey); + if (parentKey !== undefined && (parent === undefined || parent.settledOverride === "settled")) { + return; + } + const threadRef = parent ? scopeThreadRef(parent.environmentId, parent.id) : requestedRef; void (async () => { const threadKey = scopedThreadKey(threadRef); if (settlingThreadKeysRef.current.has(threadKey)) return; @@ -1642,7 +1802,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve if ( shouldNavigateAfterThreadPark({ threadKey, - currentThreadKey: readRouteThreadKey(router), + currentThreadKey: readRouteRowKey(), action: "settle", now: new Date().toISOString(), thread: readThreadShell(threadRef), @@ -1804,6 +1964,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const thread = threadByKeyRef.current.get(key); return ( thread !== undefined && + !pipelineParentKeyByStepKey.has(key) && sectionByThreadKeyRef.current.get(key) === originSection && serverConfigs.has(thread.environmentId) ); @@ -2167,7 +2328,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve settled && shouldNavigateAfterThreadPark({ threadKey: activeKey, - currentThreadKey: readRouteThreadKey(router), + currentThreadKey: readRouteRowKey(), action: "settle", now: new Date().toISOString(), thread: readThreadShell(threadRef), @@ -2238,7 +2399,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve if ( shouldNavigateAfterThreadPark({ threadKey, - currentThreadKey: readRouteThreadKey(router), + currentThreadKey: readRouteRowKey(), action: "snooze", // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309) now: new Date().toISOString(), @@ -2286,14 +2447,20 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const thread = threadByKeyRef.current.get(threadKey); return thread ? [thread] : []; }); - const settlingThreads = selectedThreads.filter( - (thread) => thread.settledOverride !== "settled", + // Nested steps follow their parent, so settle, snooze and unpin act on the other rows only. + const parkableThreads = selectedThreads.filter( + (thread) => !pipelineParentKeyByStepKey.has(threadShellKey(thread)), ); - const canSnoozeSelection = selectedThreads.every( - (thread) => - serverConfigs.has(thread.environmentId) && - canSnooze(thread, { now: selectionNow.toISOString() }), + const settlingThreads = parkableThreads.filter( + (thread) => thread.settledOverride !== "settled", ); + const canSnoozeSelection = + parkableThreads.length > 0 && + parkableThreads.every( + (thread) => + serverConfigs.has(thread.environmentId) && + canSnooze(thread, { now: selectionNow.toISOString() }), + ); const titleRegenerationThreads = selectedThreads.filter((thread) => serverConfigs.has(thread.environmentId), ); @@ -2304,7 +2471,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve supportedCount: titleRegenerationThreads.length, actionableCount: regeneratableTitleThreads.length, }); - const pinnedSelectedThreads = selectedThreads.filter( + const pinnedSelectedThreads = parkableThreads.filter( (thread) => serverConfigs.has(thread.environmentId) && thread.pinnedAt != null, ); const unpinMenuItem = buildBulkUnpinContextMenuItem({ @@ -2326,26 +2493,26 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve : []), { id: "settle", - label: `Settle (${count})`, + label: `Settle (${parkableThreads.length})`, disabled: settlingThreads.length === 0 || !canOperateThreads(settlingThreads), }, ...(canSnoozeSelection ? [ { id: "snooze", - label: `Snooze (${count})`, - disabled: !canOperateThreads(selectedThreads), + label: `Snooze (${parkableThreads.length})`, + disabled: !canOperateThreads(parkableThreads), children: [ ...snoozePresets.map((preset) => ({ id: `snooze:${preset.id}`, label: `${preset.label} (${preset.whenLabel})`, - disabled: !canOperateThreads(selectedThreads), + disabled: !canOperateThreads(parkableThreads), })), { id: "snooze:custom", label: "Custom…", separatorBefore: snoozePresets.length > 0, - disabled: !canOperateThreads(selectedThreads), + disabled: !canOperateThreads(parkableThreads), }, ], }, @@ -2385,7 +2552,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); return current && current.settledOverride !== "settled" ? [current] : []; }) - : selectedThreads; + : clicked.value?.startsWith("snooze:") + ? parkableThreads + : selectedThreads; if (clicked.value === "settle" && actionTargets.length === 0) return; if (clicked.value !== "mark-unread" && !checkThreadOperations(actionTargets)) return; if (clicked.value?.startsWith("snooze:")) { @@ -2399,10 +2568,10 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve selectedThreads[0]!.environmentId, ); if (preset) { - const coSnoozingKeys = new Set(threadKeys); + const coSnoozingKeys = new Set(parkableThreads.map((thread) => threadShellKey(thread))); clearSelection(); const outcomes = await Promise.all( - selectedThreads.map(async (thread) => { + parkableThreads.map(async (thread) => { const threadRef = scopeThreadRef(thread.environmentId, thread.id); const outcome = await performSnooze(threadRef, preset, { coSnoozingKeys }); return { outcome, threadRef }; @@ -2597,8 +2766,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve thread.worktreePath ?? projectByKey.get(`${thread.environmentId}:${thread.projectId}`)?.workspaceRoot ?? null; + // A nested step follows its parent's section, so these are the parent's to offer. + const isNestedStep = pipelineParentKeyByStepKey.has(threadKey); const configLoaded = serverConfigs.has(thread.environmentId); const supportsAutoSettleOptOut = + !isNestedStep && serverConfigs.get(thread.environmentId)?.environment.capabilities .threadAutoSettleOptOut === true; const isRegeneratingTitle = thread.titleRegeneration != null; @@ -2646,10 +2818,10 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ), canTurnIntoProject: canTurnThreadIntoProject(threadRef), supports: { - settlement: configLoaded, + settlement: configLoaded && !isNestedStep, autoSettleOptOut: supportsAutoSettleOptOut, - snooze: configLoaded, - pinning: configLoaded, + snooze: configLoaded && !isNestedStep, + pinning: configLoaded && !isNestedStep, titleRegeneration: configLoaded, }, snoozePresets, @@ -3321,6 +3493,82 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve : isCard ? "card" : "slim"; + const rowProps = (row: EnvironmentThreadShell, isStep: boolean) => { + const key = scopedThreadKey(scopeThreadRef(row.environmentId, row.id)); + return { + thread: row, + // Steps follow their parent's section, so they offer no settle, snooze or pin of their own. + settlementSupported: !isStep && serverConfigs.has(row.environmentId), + snoozeSupported: !isStep && serverConfigs.has(row.environmentId), + pinningSupported: !isStep && serverConfigs.has(row.environmentId), + isPinned: !isStep && row.pinnedAt != null, + variantAction: + section === "snoozed" + ? ("unsnooze" as const) + : section === "settled" + ? ("unsettle" as const) + : ("settle" as const), + navigationParent: isStep ? threadKey : undefined, + dropVerb: + !isStep && dragState?.activeKey === key + ? resolveSidebarDropVerb(dragState.activeSection, dragTargetSection) + : null, + dragOverPinned: + !isStep && + dragState?.activeKey === key && + dragTargetSection === "pinned", + sweepAction: actionSweep?.keys.has(key) ? actionSweep.action : null, + snoozeWakeLabelText: + !isStep && section === "snoozed" && row.snoozedUntil != null + ? snoozeWakeLabel(row.snoozedUntil, { + now: new Date().toISOString(), + }) + : null, + stepLabel: isStep + ? pipelineStepLabel(pipelineLiveRuns, row) + : undefined, + wokeAt: threadWokeAt(row, { now: snoozeNow }), + isActive: routeRowThreadKey === key, + revealRef: routeRowThreadKey === key ? revealActiveRow : undefined, + isRouteThread: routeThreadKey === key, + openPullRequestsInRightPanel: routeThreadRef !== null, + jumpLabel: showJumpHints ? (jumpLabelByKey.get(key) ?? null) : null, + currentEnvironmentId: primaryEnvironmentId, + environmentLabel: environmentLabelById.get(row.environmentId) ?? null, + environmentMachine: + environmentMachineById.get(row.environmentId) ?? ("server" as const), + scratchMachineLabel: scratchMachineLabelFor(row), + project: + projectByKey.get(`${row.environmentId}:${row.projectId}`) ?? null, + projectDisplayName: + projectDisplayNameByKey.get( + `${row.environmentId}:${row.projectId}`, + ) ?? null, + providerEntryByInstanceId: + providerEntriesByEnvironment.get(row.environmentId) ?? + EMPTY_PROVIDER_ENTRIES, + timestampFormat, + onThreadClick: handleThreadClick, + onThreadActivate: navigateToThread, + onStartRename: startThreadRename, + onRenameTitleChange: setRenamingTitle, + onCommitRename: commitThreadRename, + onCancelRename: cancelThreadRename, + isRenaming: renamingThreadKey === key, + renamingTitle: renamingThreadKey === key ? renamingTitle : "", + onContextMenu: handleThreadContextMenu, + onSettle: attemptSettle, + onActionSweepStart: startActionSweep, + onUnsettle: attemptUnsettle, + onSnooze: attemptSnooze, + onUnsnooze: attemptUnsnooze, + onUnpin: attemptUnpin, + onAcknowledgeWoke: acknowledgeWoke, + onFileDropThreads: handleThreadFileDrop, + }; + }; + const steps = pipelineStepsByParentKey.get(threadKey); + const liveRun = livePipelineRunOf(pipelineLiveRuns, thread); return ( rowProps(step, true))} + pipelineProgress={ + thread.pipeline != null && thread.pipeline.stepId === null + ? resolveSidebarPipelineProgress(liveRun, steps ?? EMPTY_THREADS) + : undefined } - timestampFormat={timestampFormat} - onThreadClick={handleThreadClick} - onThreadActivate={navigateToThread} - onStartRename={startThreadRename} - onRenameTitleChange={setRenamingTitle} - onCommitRename={commitThreadRename} - onCancelRename={cancelThreadRename} - isRenaming={renamingThreadKey === threadKey} - renamingTitle={renamingThreadKey === threadKey ? renamingTitle : ""} - onContextMenu={handleThreadContextMenu} - onSettle={attemptSettle} - onActionSweepStart={startActionSweep} - onUnsettle={attemptUnsettle} - onSnooze={attemptSnooze} - onUnsnooze={attemptUnsnooze} - onUnpin={attemptUnpin} - onAcknowledgeWoke={acknowledgeWoke} - onFileDropThreads={handleThreadFileDrop} + pipelineExpanded={expandedPipelines.has(threadKey)} + onPipelineExpandedChange={setPipelineExpanded} /> ); }; diff --git a/apps/web/src/components/TrackedFoldersDialog.browser.test.tsx b/apps/web/src/components/TrackedFoldersDialog.browser.test.tsx new file mode 100644 index 0000000000000..801f6a64f8040 --- /dev/null +++ b/apps/web/src/components/TrackedFoldersDialog.browser.test.tsx @@ -0,0 +1,55 @@ +import type { ProjectTrackedFolder, WorkspaceScannedFolder } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +import "~/index.css"; +import { act, render } from "../../test/render"; +import { chooseTrackedFolders, TrackedFoldersDialogHost } from "./TrackedFoldersDialog"; + +function scanned(count: number): WorkspaceScannedFolder[] { + return Array.from({ length: count }, (_, index) => ({ + path: `/code/app/pkg-${index}`, + name: `pkg-${index}`, + isGitRepository: true, + source: "child", + })); +} + +function choose(count: number) { + return chooseTrackedFolders({ + submitLabel: "Add project", + workspaceRoot: "/code/app", + scan: { homeIsGitRepository: true, codeWorkspaceFile: null, folders: scanned(count) }, + }); +} + +describe("TrackedFoldersDialog", () => { + it("starts a large scan unchecked and tracks only the folders the user checks", async () => { + await using _screen = await render(); + let chosen: Promise | undefined; + await act(() => { + chosen = choose(10); + }); + + await expect.element(page.getByText("Found 10 repositories")).toBeInTheDocument(); + await expect.element(page.getByText("0 of 10")).toBeInTheDocument(); + await userEvent.fill(page.getByRole("textbox", { name: "Filter folders" }), "pkg-7"); + await userEvent.click(page.getByRole("checkbox")); + await userEvent.click(page.getByRole("button", { name: "Add project" })); + + await expect(chosen).resolves.toEqual([{ path: "/code/app/pkg-7", name: "pkg-7" }]); + }); + + it("checks every folder of a small scan and resolves null on cancel", async () => { + await using _screen = await render(); + let chosen: Promise | undefined; + await act(() => { + chosen = choose(3); + }); + + await expect.element(page.getByText("3 of 3")).toBeInTheDocument(); + await userEvent.click(page.getByRole("button", { name: "Cancel" })); + + await expect(chosen).resolves.toBeNull(); + }); +}); diff --git a/apps/web/src/components/TrackedFoldersDialog.tsx b/apps/web/src/components/TrackedFoldersDialog.tsx new file mode 100644 index 0000000000000..8c089b467247b --- /dev/null +++ b/apps/web/src/components/TrackedFoldersDialog.tsx @@ -0,0 +1,180 @@ +import type { ProjectTrackedFolder, WorkspaceScanFoldersResult } from "@t3tools/contracts"; +import { useState } from "react"; +import { create } from "zustand"; + +import { + SCAN_PRESELECT_MAX, + filterScannedFolders, + folderKindLabel, + initialScanSelection, + scannedFoldersTitle, + trackedFoldersFromScan, +} from "../lib/multiRepo"; +import { Button } from "./ui/button"; +import { Checkbox } from "./ui/checkbox"; +import { + Dialog, + DialogDescription, + DialogFooter, + DialogHeader, + DialogPanel, + DialogPopup, + DialogTitle, +} from "./ui/dialog"; +import { Input } from "./ui/input"; +import { MiddleTruncate } from "./ui/middle-truncate"; + +interface TrackedFoldersRequest { + readonly title?: string; + readonly submitLabel: string; + readonly workspaceRoot: string; + readonly scan: WorkspaceScanFoldersResult; + readonly resolve: (folders: ProjectTrackedFolder[] | null) => void; +} + +const useRequest = create<{ request: TrackedFoldersRequest | null; session: number }>(() => ({ + request: null, + session: 0, +})); + +/** + * Asks which scanned folders a project tracks. Resolves the checked folders, or null when the + * user cancels. A newer request cancels an open one. + */ +export function chooseTrackedFolders( + input: Omit, +): Promise { + useRequest.getState().request?.resolve(null); + return new Promise((resolve) => { + useRequest.setState((state) => ({ + request: { ...input, resolve }, + session: state.session + 1, + })); + }); +} + +function finish(folders: ProjectTrackedFolder[] | null) { + const request = useRequest.getState().request; + useRequest.setState({ request: null }); + request?.resolve(folders); +} + +export function TrackedFoldersDialogHost() { + const request = useRequest((state) => state.request); + const session = useRequest((state) => state.session); + return request ? : null; +} + +function TrackedFoldersDialog({ request }: { request: TrackedFoldersRequest }) { + const { folders } = request.scan; + const [checked, setChecked] = useState(() => initialScanSelection(folders)); + const [query, setQuery] = useState(""); + const visible = filterScannedFolders(folders, query); + const allVisibleChecked = visible.every((folder) => checked.has(folder.path)); + + const setFolders = (paths: ReadonlyArray, include: boolean) => { + const next = new Set(checked); + for (const path of paths) { + if (include) next.add(path); + else next.delete(path); + } + setChecked(next); + }; + + return ( + { + if (!open) finish(null); + }} + > + +
{ + event.preventDefault(); + finish(trackedFoldersFromScan(folders, checked)); + }} + > + + {request.title ?? scannedFoldersTitle(folders)} + + New worktree threads get a worktree of each checked repo. + {request.scan.codeWorkspaceFile + ? ` Includes folders from ${request.scan.codeWorkspaceFile}.` + : null} + + + +
+ {folders.length > SCAN_PRESELECT_MAX ? ( + setQuery(event.target.value)} + /> + ) : ( + + )} + + {checked.size} of {folders.length} + + +
+
+ {visible.map((folder) => { + const kind = folderKindLabel(folder, request.workspaceRoot); + return ( + + ); + })} + {visible.length === 0 ? ( +

No matching folders.

+ ) : null} +
+
+ + + + +
+
+
+ ); +} diff --git a/apps/web/src/components/chat/AssistantSelectionToolbar.tsx b/apps/web/src/components/chat/AssistantSelectionToolbar.tsx index 6eed862ed7a03..d15818be50eb0 100644 --- a/apps/web/src/components/chat/AssistantSelectionToolbar.tsx +++ b/apps/web/src/components/chat/AssistantSelectionToolbar.tsx @@ -4,8 +4,16 @@ import { type AssistantCitation, type ScopedThreadRef, } from "@t3tools/contracts"; -import { QuoteIcon } from "lucide-react"; -import { use, useEffect, useLayoutEffect, useRef, useState } from "react"; +import { feedbackQuoteExcerpt } from "@t3tools/client-runtime/pipeline-run-presentation"; +import { MessageSquareIcon, QuoteIcon } from "lucide-react"; +import { + use, + useEffect, + useLayoutEffect, + useRef, + useState, + type KeyboardEvent as ReactKeyboardEvent, +} from "react"; import { createPortal } from "react-dom"; import { captureAssistantTextSelection, @@ -24,23 +32,26 @@ export function AssistantSelectionToolbar({ viewport, threadRef, onCite, + onSendFeedback, }: { viewport: HTMLElement | null; threadRef: ScopedThreadRef; onCite: (citation: AssistantCitation, sourceAnchor: AssistantCitationSourceAnchor) => boolean; + /** In a pipeline step's thread: sends the selected text as feedback instead of citing it. */ + onSendFeedback?: ((quote: string) => void) | undefined; }) { const [selection, setSelection] = useState<{ citation: AssistantCitation; position: SelectionActionPoint; sourceAnchor: AssistantCitationSourceAnchor; } | null>(null); - const toolbarRef = useRef(null); + const wrapperRef = useRef(null); const actionsRef = useRef | null>(null); const backgroundThread = use(BackgroundThreadContext); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the toolbar DOM node and clamps its position inside the window before paint useLayoutEffect(() => { - const toolbar = toolbarRef.current; + const toolbar = wrapperRef.current; if (!toolbar || !selection) return; const rect = toolbar.getBoundingClientRect(); toolbar.style.left = `${Math.max(8, Math.min(selection.position.x, window.innerWidth - rect.width - 8))}px`; @@ -139,14 +150,14 @@ export function AssistantSelectionToolbar({ }; const actions = observeSelectionActions({ element: viewport, - getActionElement: () => toolbarRef.current, + getActionElement: () => wrapperRef.current, restoreAfterScroll: true, onSelection: update, onDismiss: clear, }); actionsRef.current = actions; const focusActions = (event: KeyboardEvent) => { - const toolbar = toolbarRef.current; + const wrapper = wrapperRef.current; if ( event.key !== "Tab" || event.shiftKey || @@ -155,15 +166,16 @@ export function AssistantSelectionToolbar({ event.metaKey || event.isComposing || event.defaultPrevented || - !toolbar || - toolbar.contains(event.target as Node) + !wrapper || + wrapper.contains(event.target as Node) ) { return; } - if (toolbar.disabled) return; + const action = wrapper.querySelector("button:not(:disabled)"); + if (!action) return; event.preventDefault(); event.stopPropagation(); - toolbar.focus({ preventScroll: true }); + action.focus({ preventScroll: true }); }; // Tab belongs to the foreground chat; a background timeline only follows its selection. if (!backgroundThread) document.addEventListener("keydown", focusActions, true); @@ -188,29 +200,53 @@ export function AssistantSelectionToolbar({ dismiss(); return true; }; + const sendFeedback = () => { + if (onSendFeedback === undefined) return; + onSendFeedback(feedbackQuoteExcerpt(selection.citation.text)); + window.getSelection()?.removeAllRanges(); + dismiss(); + }; + const handleKeyDown = (event: ReactKeyboardEvent) => { + event.stopPropagation(); + if (event.key === "Escape" && !event.nativeEvent.isComposing) { + event.preventDefault(); + dismiss(); + } + }; return createPortal( - , + + {onSendFeedback ? ( + + ) : null} + , document.body, ); } diff --git a/apps/web/src/components/chat/ChangedFilesTree.tsx b/apps/web/src/components/chat/ChangedFilesTree.tsx index 6b49b81401f33..5b52ffb946711 100644 --- a/apps/web/src/components/chat/ChangedFilesTree.tsx +++ b/apps/web/src/components/chat/ChangedFilesTree.tsx @@ -1,4 +1,5 @@ import { useSyncLayout } from "@legendapp/list/react"; +import type { ChangedFilesByRepository } from "@t3tools/client-runtime/state/thread-repositories"; import { type OrchestrationV2CheckpointFileTotals, type RunId } from "@t3tools/contracts"; import { type MouseEvent, type ReactNode, memo, useLayoutEffect, useRef, useState } from "react"; import { type TurnDiffFileChange } from "../../types"; @@ -23,23 +24,33 @@ interface ChangedFileRow { depth: number; } -type ChangedFileContextMenuHandler = (filePath: string, event: MouseEvent) => void; +/** `cwd` is the repo the path is relative to; null for the thread's own folder. */ +export type ChangedFileContextMenuHandler = ( + filePath: string, + event: MouseEvent, + cwd: string | null, +) => void; +/** `repositoryKey` names the file's repo in a multi-repo thread: `home` or its tracked path. */ +export type OpenTurnDiffHandler = (runId: RunId, filePath?: string, repositoryKey?: string) => void; export const ChangedFilesCard = memo(function ChangedFilesCard(props: { runId: RunId; /** May be a prefix of the changed files; `totals` covers all of them. */ files: ReadonlyArray; totals: OrchestrationV2CheckpointFileTotals; + /** Multi-repo threads list files per repo, home first. */ + repositories?: ChangedFilesByRepository | undefined; allDirectoriesExpanded: boolean; resolvedTheme: "light" | "dark"; onToggleAllDirectories: () => void; - onOpenTurnDiff: (runId: RunId, filePath?: string) => void; + onOpenTurnDiff: OpenTurnDiffHandler; onFileContextMenu?: ChangedFileContextMenuHandler | undefined; }) { const { runId, files, totals, + repositories, allDirectoriesExpanded, resolvedTheme, onToggleAllDirectories, @@ -47,8 +58,32 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: { onFileContextMenu, } = props; const syncTimelineLayout = useSyncLayout(); + const groups = repositories?.multiRepo === true ? repositories.groups : null; + // `files` and `totals` describe the home repo and may be a prefix of it. const hiddenFileCount = totals.count - files.length; - const hasDirectories = files.some((file) => /[/\\]/.test(file.path)); + const hasDirectories = (groups?.flatMap((group) => group.files) ?? files).some((file) => + /[/\\]/.test(file.path), + ); + const summaryTotals = + groups === null + ? totals + : groups.reduce( + (sum, group) => { + const stat = + group.kind === "home" + ? totals + : { count: group.files.length, ...sumStats(group.files) }; + return { + count: sum.count + stat.count, + additions: sum.additions + stat.additions, + deletions: sum.deletions + stat.deletions, + }; + }, + { count: 0, additions: 0, deletions: 0 }, + ); + const unchanged = groups === null ? [] : (repositories?.unchanged ?? []); + const noChanges = unchanged.filter((repository) => !repository.failed); + const notRecorded = unchanged.filter((repository) => repository.failed); return (
- {totals.count.toLocaleString()} changed file{totals.count === 1 ? "" : "s"} + {summaryTotals.count.toLocaleString()} changed file + {summaryTotals.count === 1 ? "" : "s"} - {hasNonZeroStat(totals) && ( + {hasNonZeroStat(summaryTotals) && ( @@ -110,7 +146,11 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: { size="xs" variant="ghost-muted" aria-label="Open diff" - onClick={() => onOpenTurnDiff(runId, files[0]?.path)} + onClick={() => + groups === null + ? onOpenTurnDiff(runId, files[0]?.path) + : onOpenTurnDiff(runId, groups[0]?.files[0]?.path, groups[0]?.key) + } /> } > @@ -121,42 +161,99 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
- + {groups === null ? ( + onOpenTurnDiff(runId, filePath)} + onFileContextMenu={ + onFileContextMenu + ? (filePath, event) => onFileContextMenu(filePath, event, null) + : undefined + } + /> + ) : ( + groups.map((group) => ( +
+
+ {group.name} + +
+ onOpenTurnDiff(runId, filePath, group.key)} + onFileContextMenu={ + onFileContextMenu + ? (filePath, event) => onFileContextMenu(filePath, event, group.cwd) + : undefined + } + /> +
+ )) + )} {hiddenFileCount > 0 && (
)} + {noChanges.length > 0 || notRecorded.length > 0 ? ( +

+ {[ + ...(noChanges.length > 0 + ? [`${noChanges.map((repository) => repository.name).join(", ")}: no changes`] + : []), + ...(notRecorded.length > 0 + ? [`${notRecorded.map((repository) => repository.name).join(", ")}: not recorded`] + : []), + ].join(" · ")} +

+ ) : null} ); }); +function sumStats(files: ReadonlyArray) { + let additions = 0; + let deletions = 0; + for (const file of files) { + additions += file.additions; + deletions += file.deletions; + } + return { additions, deletions }; +} + +function RepositoryStat({ files }: { files: ReadonlyArray }) { + const stat = sumStats(files); + return hasNonZeroStat(stat) ? ( + + ) : null; +} + const ChangedFilesTree = memo(function ChangedFilesTree(props: { - runId: RunId; files: ReadonlyArray; allDirectoriesExpanded: boolean; resolvedTheme: "light" | "dark"; - onOpenTurnDiff: (runId: RunId, filePath?: string) => void; - onFileContextMenu?: ChangedFileContextMenuHandler | undefined; + onOpenFile: (filePath: string) => void; + onFileContextMenu?: ((filePath: string, event: MouseEvent) => void) | undefined; }) { - const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, runId, onFileContextMenu } = - props; + const { files, allDirectoriesExpanded, onOpenFile, resolvedTheme, onFileContextMenu } = props; // Place state before tree derivation to preserve its compiler cache. const [directoryExpansionState, setDirectoryExpansionState] = useState<{ key: string | null; @@ -233,7 +330,7 @@ const ChangedFilesTree = memo(function ChangedFilesTree(props: { type="button" className="group flex h-7 w-full cursor-pointer items-center gap-2 rounded-md py-1.5 pr-2 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background" style={{ paddingLeft: `${leftPadding}px` }} - onClick={() => onOpenTurnDiff(runId, node.path)} + onClick={() => onOpenFile(node.path)} onContextMenu={ onFileContextMenu ? (event) => { diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 9ad9158cd4da3..1163ebaaf0bec 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -27,6 +27,7 @@ import type { PreviewAnnotationPayload, ThreadContextRecord, EnvironmentContextRecord, + LinearIssueContextRecord, ProviderInteractionMode, ResolvedKeybindingsConfig, RuntimeMode, @@ -260,6 +261,14 @@ import { import { useMediaQuery } from "../../hooks/useMediaQuery"; import { useSoftwareKeyboardOpen } from "../../hooks/useSoftwareKeyboardOpen"; import { useStableCallback } from "../../hooks/useStableCallback"; +import type { PipelineId } from "@t3tools/contracts"; +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { appAtomRegistry } from "../../rpc/atomRegistry"; +import { LinearLaunchHint } from "../linear/LinearLaunchHint"; +import { ComposerPipelinePicker } from "./ComposerPipelinePicker"; +import { draftPipelineSelectionAtom } from "./chatViewSend"; +import { PIPELINE_TEXT_ONLY_HINT } from "./composerSend.logic"; +import { useDraftPipelines, useSelectedDraftPipelineId } from "./useDraftPipelines"; import { usePanelAnimationSettings } from "../../panelAnimations"; import { readEnvironmentScope, readPreparedConnection } from "../../state/session"; import type { ReviewCommentContext } from "../../reviewCommentContext"; @@ -331,6 +340,7 @@ export interface ChatComposerHandle { reviewComments: ReviewCommentContext[]; threadContexts: ThreadContextRecord[]; environmentContexts: EnvironmentContextRecord[]; + linearContexts: LinearIssueContextRecord[]; selectedPromptEffort: string | null; selectedModelSelection: ModelSelection; multipleModelSelections: ReadonlyArray | null; @@ -341,6 +351,8 @@ export interface ChatComposerHandle { interactionMode: ProviderInteractionMode; interactionModeEnabled: boolean; shownPendingApprovalIds: ReadonlyArray; + /** The pipeline this draft would start, as the composer shows it; null when none applies. */ + selectedPipelineId: PipelineId | null; }; validateProviderInput: (providerInput: string) => boolean; setMultipleModelSelections: (selections: ReadonlyArray) => void; @@ -713,6 +725,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const composerReviewComments = composerDraft.reviewComments; const composerThreadContexts = attachmentDraft.threadContexts; const composerEnvironmentContexts = composerDraft.environmentContexts; + const composerLinearContexts = composerDraft.linearContexts; const { pendingSnapShotAnimations, pendingSnapShotIds, @@ -764,6 +777,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) previewAnnotations: composerPreviewAnnotations, threadContexts: composerThreadContexts, environmentContexts: composerEnvironmentContexts, + linearContexts: composerLinearContexts, images: composerImages, files: composerFiles, uploadsByImageId, @@ -901,8 +915,29 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) lockedInstanceId: activeThread?.runtime?.providerInstanceId ?? activeThreadModelSelection?.instanceId, }); + // Pipelines start from new threads only (same gate as multiple models), and a pipeline and + // several models exclude each other. + const pipelineSelectionAtom = draftPipelineSelectionAtom(scopedThreadKey(routeThreadRef)); + const pipelinesEnabled = routeKind === "draft" && multipleModelSelections === null; + const draftPipelines = useDraftPipelines(environmentId, pipelinesEnabled); + const selectedPipelineId = useSelectedDraftPipelineId( + scopedThreadKey(routeThreadRef), + environmentId, + pipelinesEnabled, + ); + const pipelineActive = selectedPipelineId !== null; + const selectedPipelineMissing = + pipelineActive && + draftPipelines.loaded && + !draftPipelines.pipelines.some((pipeline) => pipeline.id === selectedPipelineId); + const selectDraftPipeline = useStableCallback((pipelineId: PipelineId | null) => { + appAtomRegistry.set( + pipelineSelectionAtom, + pipelineId === null ? null : { environmentId, pipelineId }, + ); + }); const noProviderAvailable = - selectedProviderEntry === undefined && multipleModelSelections === null; + selectedProviderEntry === undefined && multipleModelSelections === null && !pipelineActive; const providerCatalogPending = noProviderAvailable && !providerCatalogKnown; const showProviderUnavailable = noProviderAvailable && !providerCatalogPending; const providerSetupInstanceId = noProviderAvailable @@ -940,11 +975,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const sendDisabledReason = externalSendDisabledReason ?? (multipleModelSelections?.length === 0 ? "Select at least one model." : null) ?? + (selectedPipelineMissing ? "The selected pipeline no longer exists. Choose another." : null) ?? + (pipelineActive && !draftPipelines.loaded ? "Loading pipelines." : null) ?? + (pipelineActive && (composerImages.length > 0 || composerFiles.length > 0) + ? PIPELINE_TEXT_ONLY_HINT + : null) ?? (activePendingProgress ? attachmentBlockReason : (attachmentBlockReason ?? runtimeModeCeilingDenial ?? - (multipleModelSelections === null ? providerSendBlockReason : null))); + (multipleModelSelections === null && !pipelineActive ? providerSendBlockReason : null))); const isSendDisabled = sendDisabledReason !== null; const selectedProviderStatus = selectedProviderEntry?.snapshot ?? null; const compactCommandAvailable = providerSupportsManualCompaction(selectedProviderEntry); @@ -1202,6 +1242,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) (!isComposerCollapsedMobile && showPlanFollowUpPrompt && activeProposedPlan !== null); const showCollapsedMobilePromptRow = isComposerCollapsedMobile; const showComposerAttachAction = + !pipelineActive && fileStagingLimit !== null && (!activePendingProgress || (supportsQuestionAttachments && @@ -1316,6 +1357,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const setComposerDraftEnvironmentContexts = useComposerDraftStore( (store) => store.setEnvironmentContexts, ); + const setComposerDraftLinearContexts = useComposerDraftStore((store) => store.setLinearContexts); const buildContextClipboardFragment = (contextIds: ReadonlyArray): string | null => { const wanted = new Set(contextIds); const copiedFiles = new Map(); @@ -1333,6 +1375,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) .map(terminalContextRecord), ...composerThreadContexts.filter((record) => wanted.has(record.contextId)), ...composerEnvironmentContexts.filter((record) => wanted.has(record.contextId)), + ...composerLinearContexts.filter((record) => wanted.has(record.contextId)), ...composerReviewComments .filter((c) => wanted.has(reviewCommentContextId(c.id))) .map(reviewCommentContextRecord), @@ -1686,6 +1729,23 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) setComposerDraftEnvironmentContexts(composerDraftTarget, nextEnvironments); } + const liveLinearIds = new Set(composerLinearContexts.map((record) => record.contextId)); + const restoredLinear = [...referenced].flatMap((contextId) => { + if (liveLinearIds.has(contextId)) return []; + const record = retained.linear.get(contextId); + return record ? [record] : []; + }); + const nextLinear = [ + ...composerLinearContexts.filter((record) => referenced.has(record.contextId)), + ...restoredLinear, + ]; + for (const record of composerLinearContexts) { + if (!referenced.has(record.contextId)) retained.linear.set(record.contextId, record); + } + if (nextLinear.length !== composerLinearContexts.length || restoredLinear.length > 0) { + setComposerDraftLinearContexts(composerDraftTarget, nextLinear); + } + for (const comment of composerReviewComments) { const contextId = reviewCommentContextId(comment.id); if (!referenced.has(contextId)) { @@ -2365,6 +2425,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onModelPickerOpenChange={setIsComposerModelPickerOpen} modelPickerIconClassName={composerProviderState.modelPickerIconClassName} getModelDisabledReason={getModelDisabledReason} + pipelineActive={pipelineActive} + pipelinePicker={ + // A selected pipeline keeps the picker, even if it was deleted or has not loaded yet. + draftPipelines.available && (pipelineActive || draftPipelines.pipelines.length > 0) ? ( + + ) : null + } /> ); // An open question owns the space above the composer. Only a machine problem, @@ -3001,6 +3075,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) reviewComments: composerReviewComments, threadContexts: composerThreadContexts, environmentContexts: composerEnvironmentContexts, + linearContexts: composerLinearContexts, selectedPromptEffort, selectedModelSelection, multipleModelSelections: @@ -3014,12 +3089,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) : null, providerAvailable: multipleModelSelections !== null || + pipelineActive || (!noProviderAvailable && providerSendBlockReason === null), selectedProvider, selectedModel, selectedProviderModels, interactionMode, interactionModeEnabled: planModeUiEnabled, + selectedPipelineId, }), setMultipleModelSelections, validateProviderInput: (providerInput: string) => { @@ -3057,6 +3134,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) composerReviewComments, composerThreadContexts, composerEnvironmentContexts, + composerLinearContexts, focusComposer, environmentId, primaryEnvironmentId, @@ -3079,6 +3157,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) setMultipleModelSelections, routeKind, noProviderAvailable, + pipelineActive, + selectedPipelineId, providerSendBlockReason, selectedPromptEffort, selectedProvider, @@ -3430,7 +3510,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ? "Choose a project above to start a thread" : showProviderUnavailable ? "Enable a provider in Settings to send a message" - : DEFAULT_COMPOSER_PLACEHOLDER + : activeThread?.pipeline?.stepId === null + ? "Ask the coordinator to check, fix or steer this run…" + : DEFAULT_COMPOSER_PLACEHOLDER } disabled={ projectSelectionRequired || @@ -3501,6 +3583,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) > {composerControls} + void; + /** Set in a pipeline step's thread: opens the run's coordinator chat beside it. */ + onOpenCoordinator?: (() => void) | undefined; + coordinatorUnread?: boolean | undefined; rightPanelOpen: boolean; onNewThreadInProject: () => void; onOpenProjectSettings?: (() => void) | undefined; @@ -79,6 +83,8 @@ export const ChatHeader = memo(function ChatHeader({ activeProject, parentThreadLink, onOpenThread, + onOpenCoordinator, + coordinatorUnread = false, rightPanelOpen, onNewThreadInProject, onOpenProjectSettings, @@ -430,6 +436,21 @@ export const ChatHeader = memo(function ChatHeader({ ) : null} + {onOpenCoordinator ? ( + + ) : null} {isServerThread ? : null} ); diff --git a/apps/web/src/components/chat/ComposerControlsBar.tsx b/apps/web/src/components/chat/ComposerControlsBar.tsx index 0002beeaf9fef..2f8bc47c48e2b 100644 --- a/apps/web/src/components/chat/ComposerControlsBar.tsx +++ b/apps/web/src/components/chat/ComposerControlsBar.tsx @@ -3,6 +3,7 @@ import type { PromptUltrathink } from "./TraitsPicker"; import type { ProviderInstanceEntry } from "../../providerInstances"; import { type AppModelOption } from "../../modelSelection"; import { CircleAlertIcon } from "lucide-react"; +import type { ReactNode } from "react"; import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu"; import { ComposerControl } from "./ComposerControl"; import { @@ -88,6 +89,10 @@ export function ComposerControlsBar(props: { onModelPickerOpenChange: (open: boolean) => void; modelPickerIconClassName: string | undefined; getModelDisabledReason: ChatComposerProps["getModelDisabledReason"]; + /** The Pipeline chip, on drafts whose server has pipelines; null elsewhere. */ + pipelinePicker: ReactNode; + /** A pipeline is selected: its steps own model, traits and mode, so those controls are gone. */ + pipelineActive: boolean; }) { const { environmentId, @@ -136,6 +141,8 @@ export function ComposerControlsBar(props: { onModelPickerOpenChange, modelPickerIconClassName, getModelDisabledReason, + pipelinePicker, + pipelineActive, } = props; const accessMatchesDefault = compatibleRuntimeMode === defaultRuntimeMode; const { @@ -251,24 +258,29 @@ export function ComposerControlsBar(props: { onOpenProviderSetup={onOpenProviderSetup} /> ); + if (pipelineActive && pipelinePicker) return <>{pipelinePicker}; return showProviderUnavailable ? ( - { - if (providerSetupInstanceId) { - onOpenProviderSetup(providerSetupInstanceId); - } - }} - data-chat-provider-unavailable="true" - className="shrink-0" - > - - {providerSetupInstanceId ? "Open provider settings" : "No provider available"} - + <> + {pipelinePicker} + { + if (providerSetupInstanceId) { + onOpenProviderSetup(providerSetupInstanceId); + } + }} + data-chat-provider-unavailable="true" + className="shrink-0" + > + + {providerSetupInstanceId ? "Open provider settings" : "No provider available"} + + ) : ( <> {composerModelPicker} + {pipelinePicker} <> {restingBlockDefs.map((def, index) => { diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx index a19e7f205cef9..09f123e085abb 100644 --- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx +++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx @@ -1,7 +1,7 @@ import { type RuntimeRequestId, type ScopedThreadRef } from "@t3tools/contracts"; import { markdownProseDirection, textDirection } from "~/textDirection"; import { memo, use, useEffect, useEffectEvent, useRef, useState } from "react"; -import { BackgroundThreadContext } from "./backgroundThread"; +import { BackgroundThreadContext, isFromEmbeddedChat } from "./backgroundThread"; import { useStableCallback } from "~/hooks/useStableCallback"; import { type PendingUserInput } from "../../session-logic"; import type { PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input"; @@ -151,7 +151,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( useEffect(() => { if (!activeQuestion || responseDisabled || isCollapsed || backgroundThread) return; const handler = (event: globalThis.KeyboardEvent) => { - if (event.metaKey || event.ctrlKey || event.altKey) return; + if (event.metaKey || event.ctrlKey || event.altKey || isFromEmbeddedChat(event)) return; const target = event.target; if (isInSideChatPane(target)) return; if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) { diff --git a/apps/web/src/components/chat/ComposerPipelinePicker.tsx b/apps/web/src/components/chat/ComposerPipelinePicker.tsx new file mode 100644 index 0000000000000..f61a5bf298d72 --- /dev/null +++ b/apps/web/src/components/chat/ComposerPipelinePicker.tsx @@ -0,0 +1,106 @@ +import type { PipelineDefinition, PipelineId } from "@t3tools/contracts"; +import { describePipelineSteps } from "@t3tools/client-runtime/pipeline-editor"; +import { useNavigate } from "@tanstack/react-router"; +import { WorkflowIcon } from "lucide-react"; +import { memo } from "react"; + +import { + Menu, + MenuItem, + MenuPopup, + MenuRadioGroup, + MenuRadioItem, + MenuSeparator, + MenuTrigger, +} from "../ui/menu"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { ComposerControl, ComposerControlIcon, type ComposerControlSize } from "./ComposerControl"; +import { useComposerMenuProps } from "./composerEventScope"; + +const NO_PIPELINE_VALUE = ""; + +/** + * The composer's Pipeline chip. A selected pipeline replaces the model, traits and mode controls: + * each step brings its own, and the run takes the draft's text only. + */ +export const ComposerPipelinePicker = memo(function ComposerPipelinePicker(props: { + pipelines: ReadonlyArray; + pipelinesLoaded: boolean; + selectedPipelineId: PipelineId | null; + disabled: boolean; + size: ComposerControlSize; + onSelect: (pipelineId: PipelineId | null) => void; +}) { + const navigate = useNavigate(); + const composerFloatingLayerProps = useComposerMenuProps(); + const selected = props.pipelines.find((pipeline) => pipeline.id === props.selectedPipelineId); + const pending = props.selectedPipelineId !== null && !selected && !props.pipelinesLoaded; + const label = + props.selectedPipelineId === null + ? "Pipeline" + : (selected?.name ?? (pending ? "Loading pipeline" : "Pipeline unavailable")); + const tooltip = selected + ? `${selected.name}: ${describePipelineSteps(selected.steps)}. The run takes text only.` + : props.selectedPipelineId === null + ? "Run a pipeline of agent steps instead of one model" + : pending + ? "Loading pipelines" + : "This pipeline no longer exists. Choose another or none."; + + return ( +
+ {/* Non-modal like the model picker: a modal menu locks page scroll and lays a backdrop over the composer. */} + + + + } + /> + } + > + + + {label} + + + {tooltip} + + + + props.onSelect( + value === NO_PIPELINE_VALUE + ? null + : (props.pipelines.find((pipeline) => pipeline.id === value)?.id ?? null), + ) + } + > + None + {props.pipelines.map((pipeline) => ( + + {pipeline.name} + + {describePipelineSteps(pipeline.steps)} + + + ))} + + + void navigate({ to: "/settings/pipelines" })}> + Manage pipelines… + + + +
+ ); +}); diff --git a/apps/web/src/components/chat/ComposerReposControl.tsx b/apps/web/src/components/chat/ComposerReposControl.tsx new file mode 100644 index 0000000000000..bc692260fce5e --- /dev/null +++ b/apps/web/src/components/chat/ComposerReposControl.tsx @@ -0,0 +1,92 @@ +import type { WorkspaceRepository } from "@t3tools/contracts"; +import { ChevronDownIcon, FolderGit2Icon } from "lucide-react"; + +import { includedRepositoryCount, isRepositoryIncluded } from "~/lib/multiRepo"; +import { useWorktreeRepositorySelectionStore } from "~/worktreeRepositorySelectionStore"; +import { ComposerContextLabel } from "../ComposerContextLabel"; +import { Checkbox } from "../ui/checkbox"; +import { Input } from "../ui/input"; +import { MiddleTruncate } from "../ui/middle-truncate"; +import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; +import { ComposerControl } from "./ComposerControl"; +import { useComposerMenuProps } from "./composerEventScope"; + +/** + * Which tracked repos a new task folder gets. Every repo starts checked and from its own default + * branch, so sending without opening this needs no choices. + */ +export function ComposerReposControl({ + selectionKey, + repositories, +}: { + selectionKey: string; + repositories: ReadonlyArray; +}) { + const selection = useWorktreeRepositorySelectionStore((store) => store.byKey[selectionKey]); + const setIncluded = useWorktreeRepositorySelectionStore((store) => store.setIncluded); + const setBaseRef = useWorktreeRepositorySelectionStore((store) => store.setBaseRef); + const composerFloatingLayerProps = useComposerMenuProps(); + const included = includedRepositoryCount(repositories, selection); + const label = + included === repositories.length ? "Repos" : `Repos ${included}/${repositories.length}`; + + return ( + + } + className="min-w-0 shrink" + aria-label={`Repositories for the new worktree: ${included} of ${repositories.length}`} + data-composer-context-control + > + + {label} + + + +
+ {repositories.map((repository) => { + const checked = isRepositoryIncluded(selection, repository.originalPath); + return ( +
+ + + setBaseRef(selectionKey, repository.originalPath, event.target.value) + } + /> +
+ ); + })} +
+
+
+ ); +} diff --git a/apps/web/src/components/chat/DraftHeroHeadline.tsx b/apps/web/src/components/chat/DraftHeroHeadline.tsx index dac76937a9cc2..5cad04f6cbcfd 100644 --- a/apps/web/src/components/chat/DraftHeroHeadline.tsx +++ b/apps/web/src/components/chat/DraftHeroHeadline.tsx @@ -50,6 +50,7 @@ import { import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { InlineButton } from "../ui/button"; import { DraftProjectName } from "./DraftProjectName"; +import { LinearDraftProjectHint } from "../linear/LinearDraftProjectHint"; import { DraftHeroProjectHeading } from "./DraftHeroProjectHeading"; import { TriageDraftHero } from "./TriageDraftHero"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; @@ -429,6 +430,9 @@ export function DraftHeroHeadline({ )} )} + {draftId ? ( + + ) : null} {scratchWorkspaceRoot === null ? null : (

{isScratchDraft ? projectSelector : orStartWithoutProject} diff --git a/apps/web/src/components/chat/MarkdownFileLink.tsx b/apps/web/src/components/chat/MarkdownFileLink.tsx index 6a250f93d2157..7e756eb29c44a 100644 --- a/apps/web/src/components/chat/MarkdownFileLink.tsx +++ b/apps/web/src/components/chat/MarkdownFileLink.tsx @@ -36,8 +36,9 @@ interface MarkdownFileLinkProps { copyMarkdown: string; theme: "light" | "dark"; threadRef?: ScopedThreadRef | undefined; - onOpen?: (() => Promise>) | undefined; - onOpenInPanel: (panelPath: string, line: number | undefined) => void; + /** `anchor` places a picker when the link matches files in several repos. */ + onOpen?: ((anchor?: LinkAnchor) => Promise>) | undefined; + onOpenInPanel: (panelPath: string, line: number | undefined, anchor?: LinkAnchor) => void; resolveCopyPaths: () => Promise>; openInEditorMenuLabel: string; onOpenInBrowser?: (() => Promise>) | undefined; @@ -48,6 +49,16 @@ interface MarkdownFileLinkProps { const MARKDOWN_FILE_LINK_CLASS_NAME = "chat-markdown-file-link"; +interface LinkAnchor { + readonly x: number; + readonly y: number; +} + +function linkAnchor(element: Element): LinkAnchor { + const bounds = element.getBoundingClientRect(); + return { x: bounds.left, y: bounds.bottom }; +} + export const MarkdownFileLink = memo(function MarkdownFileLink({ environmentId, href, @@ -69,13 +80,13 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ revealLabel, resolveCopyPaths, }: MarkdownFileLinkProps) { - const handleOpenInEditor = () => { + const handleOpenInEditor = (anchor?: LinkAnchor) => { if (!onOpen) { return; } void (async () => { try { - const result = await onOpen(); + const result = await onOpen(anchor); if (result._tag === "Success" || isAtomCommandInterrupted(result)) { return; } @@ -107,16 +118,16 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ })(); }; - const handleOpenInFilePreview = () => { + const handleOpenInFilePreview = (anchor: LinkAnchor) => { if (threadRef && panelPath) { - onOpenInPanel(panelPath, line); + onOpenInPanel(panelPath, line, anchor); return; } if (onOpenMedia) { onOpenMedia(); return; } - handleOpenInEditor(); + handleOpenInEditor(anchor); }; const handleOpenInBrowser = () => { @@ -265,7 +276,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ return; } if (clicked === "open") { - handleOpenInEditor(); + handleOpenInEditor(position); return; } if (clicked === "open-in-browser") { @@ -337,15 +348,16 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ onClick={(event) => { event.preventDefault(); event.stopPropagation(); + const anchor = linkAnchor(event.currentTarget); if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) { - handleOpenInEditor(); + handleOpenInEditor(anchor); return; } if (useBrowserPrimaryAction) { handleOpenInBrowser(); return; } - handleOpenInFilePreview(); + handleOpenInFilePreview(anchor); }} onContextMenu={handleContextMenu} > diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 9b156deaed8a2..bec6dafbd5b76 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -745,6 +745,8 @@ describe("MessagesTimeline automation prompts", () => { checkpointRef: "checkpoint-1" as never, status: "ready", files: [], + repositories: [], + outsideEdits: [], assistantMessageId: MessageId.make("assistant-1"), completedAt: CREATED_AT, }, diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 4c7eba620b5d1..37f61cfd61253 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -850,6 +850,8 @@ describe("deriveMessagesTimelineRows", () => { checkpointRef: "checkpoint-1" as never, status: "ready" as const, files: [{ path: "src/index.ts", kind: "modified", additions: 3, deletions: 1 }], + repositories: [], + outsideEdits: [], }; const rows = deriveMessagesTimelineRows({ @@ -3191,6 +3193,8 @@ describe("streaming v2 row projection", () => { checkpointRef: CheckpointRef.make("refs/t3/checkpoints/history"), status: "ready", files: [], + repositories: [], + outsideEdits: [], assistantMessageId: MessageId.make("history-assistant"), completedAt: source.time(4), }, @@ -3773,6 +3777,7 @@ it("keeps the working header in place across worktree setup handoff", () => { worktreePath: null, setupScript: null, stages: [], + repositories: [], error: null, sequence: 3, }; diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index cea2daa111207..f6f7f8d8416b1 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1,6 +1,5 @@ import { threadEnvironment } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; -import type { ToolCallDiffTarget } from "../../diffPanelStore"; import { AudioPreviewUnmountContext } from "../files/AudioPreview"; import { ThreadFindTimelineContext } from "./ThreadFindProvider"; import { MarkdownFindContext } from "./markdownFindContext"; @@ -8,6 +7,7 @@ import { useChatCanvas } from "./ChatCanvasContext"; import { WorkLogBlock } from "./WorkLog"; import { TimelinePendingApprovalRow } from "./TimelinePendingApprovalRow"; import type { WorktreeSetupSnapshot } from "@t3tools/contracts"; +import { failedSetupRepositories } from "~/lib/multiRepo"; import { deriveTimelineMinimapItems } from "./timelineMinimapItems"; import { type AssistantCitation, @@ -229,7 +229,7 @@ interface MessagesTimelineProps { worktreeSetup?: WorktreeSetupSnapshot | null; onCancelWorktreeSetup?: () => void; retryableWorkspacePreparationRunIds?: ReadonlySet; - onRetryWorkspacePreparation?: (runId: RunId) => void; + onRetryWorkspacePreparation?: (runId: RunId, skipRepositoryPaths?: ReadonlyArray) => void; onWorktreeSetupWorkLocally?: () => void; onOpenWorktreeSetupTerminal?: (terminalId: string) => void; isPreparingWorktree?: boolean; @@ -252,8 +252,9 @@ interface MessagesTimelineProps { displayThreadKey?: string; /** Off where another region already speaks the thread's status, like a subagent's bar. */ announceTurnStatus?: boolean; - onOpenToolDiff?: (target: ToolCallDiffTarget) => void; - onOpenTurnDiff?: (runId: RunId, filePath?: string) => void; + onOpenToolDiff?: TimelineRowSharedState["onOpenToolDiff"]; + onOpenTurnDiff?: TimelineRowSharedState["onOpenTurnDiff"]; + onOpenRepositoryChanges?: TimelineRowSharedState["onOpenRepositoryChanges"]; onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void; renderHtmlRender?: TimelineRowSharedState["renderHtmlRender"]; turnItemSource?: TimelineRowSharedState["turnItemSource"]; @@ -265,11 +266,14 @@ interface MessagesTimelineProps { readonly title: string; /** A side chat's inherited rows collapse into this link. */ readonly sideChat?: boolean; + /** Divider text before the title; subagents by default. */ + readonly label?: string; /** Where it runs, when that is another environment. */ readonly environmentLabel?: string; readonly open?: () => void; } | null; workflowOpening?: WorkflowOpening | null; + onSendFeedback?: (quote: string) => void; onForkFromRun?: (input: { readonly sourceThreadId: ThreadId; readonly runId: RunId; @@ -367,12 +371,14 @@ const ConversationTimeline = memo(function ConversationTimeline({ announceTurnStatus = true, onOpenToolDiff, onOpenTurnDiff, + onOpenRepositoryChanges, onOpenThread, renderHtmlRender, turnItemSource, parentThreadLink = null, workflowOpening = null, onForkFromRun, + onSendFeedback, supportsConversationRollback, threadStartCheckpointReady = false, availableRevertTurnCounts, @@ -1034,11 +1040,13 @@ const ConversationTimeline = memo(function ConversationTimeline({ openPullRequest, onOpenToolDiff, onOpenTurnDiff, + onOpenRepositoryChanges, onOpenThread, renderHtmlRender, turnItemSource, workflowOpening, onForkFromRun, + onSendFeedback, onToggleTurnFold, onToggleAttemptFold, onToggleWorkGroup, @@ -1046,6 +1054,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ onCancelWorktreeSetup: onCancelWorktreeSetup ?? null, retryableWorkspacePreparationRunIds, onRetryWorkspacePreparation: onRetryWorkspacePreparation ?? null, + failedWorktreeRepositories: failedSetupRepositories(worktreeSetup), onWorktreeSetupWorkLocally: onWorktreeSetupWorkLocally ?? null, onOpenWorktreeSetupTerminal: onOpenWorktreeSetupTerminal ?? null, workGroupViewState, @@ -1096,7 +1105,9 @@ const ConversationTimeline = memo(function ConversationTimeline({

) : null} diff --git a/apps/web/src/components/chat/OutsideEditsNotice.tsx b/apps/web/src/components/chat/OutsideEditsNotice.tsx new file mode 100644 index 0000000000000..7c994de4fb8d0 --- /dev/null +++ b/apps/web/src/components/chat/OutsideEditsNotice.tsx @@ -0,0 +1,153 @@ +import { scopeProjectRef } from "@t3tools/client-runtime/environment"; +import { findExistingAddProject } from "@t3tools/client-runtime/operations/projects"; +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import type { ThreadCheckpointOutsideEdit } from "@t3tools/client-runtime/state/thread-checkpoints"; +import { + describeOutsideEdit, + OUTSIDE_EDITS_SHELL_NOTE, +} from "@t3tools/client-runtime/state/thread-repositories"; +import { + isAtomCommandInterrupted, + settlePromise, + squashAtomCommandFailure, + type AtomCommandResult, +} from "@t3tools/client-runtime/state/runtime"; +import { normalizeProjectPathForComparison } from "@t3tools/shared/path"; +import { AuthOrchestrationOperateScope } from "@t3tools/contracts"; +import { useState } from "react"; + +import { useNewThreadHandler } from "../../hooks/useHandleNewThread"; +import { inferProjectTitleFromPath } from "@t3tools/client-runtime/state/projects"; +import { newProjectId } from "../../lib/utils"; +import { readProjects } from "../../state/entities"; +import { projectEnvironment } from "../../state/projects"; +import { useEnvironmentScope } from "../../state/session"; +import { useOrchestrationCommand } from "../../state/use-orchestration-command"; +import { Button } from "../ui/button"; +import { stackedThreadToast, toastManager } from "../ui/toast"; + +function reportFailure(title: string, result: AtomCommandResult): boolean { + if (result._tag !== "Failure") return false; + if (!isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add( + stackedThreadToast({ + type: "error", + title, + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); + } + return true; +} + +/** + * Repos a run edited without a checkpoint: untracked ones can join the project or open as their + * own project, tracked ones open their uncommitted changes. + */ +export function OutsideEditsNotice(props: { + readonly edits: ReadonlyArray; + readonly project: EnvironmentProject | null; + /** Unset where there is no diff panel to open. */ + readonly onReview: ((edit: ThreadCheckpointOutsideEdit) => void) | undefined; +}) { + const { edits, project } = props; + const environmentId = project?.environmentId ?? null; + const canChangeProjects = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope); + const updateProject = useOrchestrationCommand(projectEnvironment.update, { + reportFailure: false, + }); + const createProject = useOrchestrationCommand(projectEnvironment.create, { + reportFailure: false, + }); + const handleNewThread = useNewThreadHandler(); + const [busyRoot, setBusyRoot] = useState(null); + + const track = async (edit: ThreadCheckpointOutsideEdit) => { + if (project === null) return; + setBusyRoot(edit.root); + const result = await updateProject({ + environmentId: project.environmentId, + input: { + projectId: project.id, + trackedFolders: [...project.trackedFolders, { path: edit.root, name: edit.name }], + }, + }); + setBusyRoot(null); + reportFailure(`Could not track ${edit.name}`, result); + }; + + const openAsProject = async (edit: ThreadCheckpointOutsideEdit) => { + if (environmentId === null) return; + const existing = findExistingAddProject({ + projects: readProjects(), + environmentId, + path: edit.root, + }); + const projectId = existing?.id ?? newProjectId(); + if (existing === null) { + setBusyRoot(edit.root); + const result = await createProject({ + environmentId, + input: { + projectId, + title: inferProjectTitleFromPath(edit.root), + workspaceRoot: edit.root, + defaultModelSelection: null, + }, + }); + setBusyRoot(null); + if (reportFailure(`Could not open ${edit.name} as a project`, result)) return; + } + reportFailure( + `Could not open ${edit.name} as a project`, + await settlePromise(() => handleNewThread(scopeProjectRef(environmentId, projectId))), + ); + }; + // The recorded edit keeps its old flag, so a folder tracked since then shows Review. + const trackedRoots = new Set( + project?.trackedFolders.map((folder) => normalizeProjectPathForComparison(folder.path)), + ); + + return ( +
+ {edits.map((recorded) => { + const edit = trackedRoots.has(normalizeProjectPathForComparison(recorded.root)) + ? { ...recorded, tracked: true } + : recorded; + return ( +
+ {describeOutsideEdit(edit)} + {edit.tracked ? ( + props.onReview === undefined ? null : ( + + ) + ) : canChangeProjects ? ( + <> + + + + ) : null} +
+ ); + })} +

{OUTSIDE_EDITS_SHELL_NOTE}

+
+ ); +} diff --git a/apps/web/src/components/chat/PipelineCoordinatorPanel.tsx b/apps/web/src/components/chat/PipelineCoordinatorPanel.tsx new file mode 100644 index 0000000000000..b8e9929c9da24 --- /dev/null +++ b/apps/web/src/components/chat/PipelineCoordinatorPanel.tsx @@ -0,0 +1,129 @@ +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { pipelineRunStateLabel, stepName } from "@t3tools/client-runtime/pipeline-run-presentation"; +import { pipelineProgressSegments } from "@t3tools/client-runtime/state/pipeline-nesting"; +import type { PipelineRun, PipelineRunSummary, ScopedThreadRef } from "@t3tools/contracts"; +import { useNavigate } from "@tanstack/react-router"; +import { lazy, memo, Suspense, useRef } from "react"; + +import { ComposerHandleContext } from "../../composerHandleContext"; +import type { SideChatParentPanel } from "../../lib/sideChatPane"; +import { useEnvironmentQuery } from "../../state/query"; +import { useQuietThreadShell } from "../../state/entities"; +import { serverEnvironment } from "../../state/server"; +import { buildThreadRouteParams } from "../../threadRoutes"; +import { PipelineProgressBar } from "../PipelineProgressBar"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { BackgroundThreadContext, EmbeddedChatContext } from "./backgroundThread"; +import type { ChatComposerHandle } from "./ChatComposer"; + +// ChatView renders this panel, so it loads lazily to keep the import cycle out of module setup. +const ChatView = lazy(() => import("../ChatView")); + +/** The progress bar's input: a full run carries everything a live-run summary does. */ +function summarizeRun(run: PipelineRun): PipelineRunSummary { + return { + id: run.id, + parentThreadId: run.parentThreadId, + name: run.definition.name, + status: run.status, + pauseReason: run.pauseReason, + currentStepIndex: run.currentStepIndex, + steps: run.steps.map((step) => ({ + stepId: step.stepId, + name: stepName(run, step.index), + status: step.status, + childThreadId: step.childThreadId, + })), + }; +} + +/** + * The run's coordinator chat inside a step's thread. It is the parent thread's own conversation + * and composer, so it stays in sync with the run's main page, and it is subscribed only while the + * tab is open. + */ +export const PipelineCoordinatorPanel = memo(function PipelineCoordinatorPanel(props: { + readonly stepThreadRef: ScopedThreadRef; + /** The step's diff panel and terminal, which the embedded chat uses in place of its own. */ + readonly parentPanel: SideChatParentPanel; +}) { + const { environmentId, threadId } = props.stepThreadRef; + const navigate = useNavigate(); + const composerRef = useRef(null); + const runId = useQuietThreadShell(props.stepThreadRef)?.pipeline?.runId ?? null; + const query = useEnvironmentQuery( + runId === null ? null : serverEnvironment.pipelineRunLive({ environmentId, input: { runId } }), + ); + const run = query.data?.run ?? null; + const parentRef = run === null ? null : scopeThreadRef(environmentId, run.parentThreadId); + const parentExists = useQuietThreadShell(parentRef) !== null; + if (run === null || parentRef === null) { + return ( +

+ {query.error ?? "Loading pipeline run..."} +

+ ); + } + const segments = pipelineProgressSegments(summarizeRun(run), [], () => "ready").map( + (segment, index) => ({ + stepId: segment.stepId, + label: segment.label, + status: segment.status, + threadId: run.steps[index]?.childThreadId ?? null, + }), + ); + const currentIndex = run.currentStepIndex; + const openThread = (target: ScopedThreadRef) => + void navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(target) }); + return ( +
+
+
+ openThread(scopeThreadRef(environmentId, stepThreadId))} + /> +
+ + openThread(parentRef)} + /> + } + > + Step {currentIndex + 1}/{run.steps.length} · {stepName(run, currentIndex)} ·{" "} + {pipelineRunStateLabel(run)} + + Open the run's main page + +
+
+ {parentExists ? ( + + + + + + + + + + ) : ( +

+ The coordinator chat is not available. +

+ )} +
+
+ ); +}); diff --git a/apps/web/src/components/chat/PipelineFeedbackDialog.tsx b/apps/web/src/components/chat/PipelineFeedbackDialog.tsx new file mode 100644 index 0000000000000..58ade2750db67 --- /dev/null +++ b/apps/web/src/components/chat/PipelineFeedbackDialog.tsx @@ -0,0 +1,99 @@ +import { stepName } from "@t3tools/client-runtime/pipeline-run-presentation"; +import type { EnvironmentId, PipelineRun } from "@t3tools/contracts"; +import { useState } from "react"; + +import { Button } from "../ui/button"; +import { + Dialog, + DialogDescription, + DialogFooter, + DialogHeader, + DialogPanel, + DialogPopup, + DialogTitle, +} from "../ui/dialog"; +import { Textarea } from "../ui/textarea"; +import { getComposerPromptLengthValidationMessage } from "./composerSubmission"; +import { usePipelineRevise } from "./usePipelineRevise"; + +/** Feedback for one earlier step: it fixes its work, then every later step redoes theirs. */ +export function PipelineFeedbackDialog(props: { + readonly environmentId: EnvironmentId; + readonly run: PipelineRun; + readonly stepIndex: number; + readonly onClose: () => void; + readonly onRevised: (run: PipelineRun) => void; +}) { + const { run, stepIndex } = props; + const { canRevise, revise } = usePipelineRevise(props.environmentId); + const [feedback, setFeedback] = useState(""); + const [sending, setSending] = useState(false); + const name = stepName(run, stepIndex); + const lengthMessage = getComposerPromptLengthValidationMessage(feedback); + const laterRunning = + run.status === "running" && run.currentStepIndex > stepIndex && run.steps.length > stepIndex; + + const submit = async () => { + if (sending || feedback.trim() === "" || lengthMessage !== null) return; + setSending(true); + const revised = await revise({ runId: run.id, stepIndex, feedback }); + setSending(false); + if (revised !== null) { + props.onRevised(revised); + props.onClose(); + } + }; + + return ( + { + if (!open) props.onClose(); + }} + > + +
{ + event.preventDefault(); + void submit(); + }} + > + + Send feedback to {name} + + {name} fixes its work in its own thread, then every later step redoes its work. + {laterRunning ? " The step that is running now is stopped first." : ""} + + + +