From 19de9c54011c5a0af4fac5869134d8226333da02 Mon Sep 17 00:00:00 2001 From: Farseen M Date: Mon, 9 Nov 2026 15:31:05 +0530 Subject: [PATCH 1/6] feat(web): add a global project actions menu with headless runs Project actions were only reachable from a thread header, and running one opened and focused the terminal drawer. Add a global actions menu in the sidebar that lists every project and its actions, runs them in a headless PTY, and reports status through a compact run bar and a detail dialog with recent runs and output. Co-Authored-By: Claude Code --- apps/web/src/appInit.tsx | 2 + apps/web/src/components/AppSidebarLayout.tsx | 2 + apps/web/src/components/Sidebar.tsx | 2 + .../ProjectScriptRunCoordinator.ts | 176 +++++++++++ .../ProjectScriptRunDetail.tsx | 195 ++++++++++++ .../ProjectScriptRunStatusIcon.tsx | 30 ++ .../ProjectScriptRunsBar.tsx | 83 ++++++ .../ProjectScriptRunsControl.tsx | 142 +++++++++ .../ProjectScriptRunsHost.tsx | 40 +++ .../src/components/sidebar/SidebarChrome.tsx | 2 + .../sidebar/SidebarThreadHeader.tsx | 3 + apps/web/src/hooks/useProjectScriptRuns.ts | 278 ++++++++++++++++++ apps/web/src/projectScriptRuns.test.ts | 180 ++++++++++++ apps/web/src/projectScriptRuns.ts | 198 +++++++++++++ apps/web/src/projectScriptRunsStore.ts | 67 +++++ 15 files changed, 1400 insertions(+) create mode 100644 apps/web/src/components/projectScriptRuns/ProjectScriptRunCoordinator.ts create mode 100644 apps/web/src/components/projectScriptRuns/ProjectScriptRunDetail.tsx create mode 100644 apps/web/src/components/projectScriptRuns/ProjectScriptRunStatusIcon.tsx create mode 100644 apps/web/src/components/projectScriptRuns/ProjectScriptRunsBar.tsx create mode 100644 apps/web/src/components/projectScriptRuns/ProjectScriptRunsControl.tsx create mode 100644 apps/web/src/components/projectScriptRuns/ProjectScriptRunsHost.tsx create mode 100644 apps/web/src/hooks/useProjectScriptRuns.ts create mode 100644 apps/web/src/projectScriptRuns.test.ts create mode 100644 apps/web/src/projectScriptRuns.ts create mode 100644 apps/web/src/projectScriptRunsStore.ts diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index faa71137db049..8b2760430be49 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -21,6 +21,7 @@ import { startHostFreezeToasts } from "./components/HostFreezeToastCoordinator"; import { startKeybindingsUpdateToasts } from "./components/KeybindingsUpdateToast"; import { startLegacyThreadMigrationToast } from "./components/LegacyThreadMigrationToast"; import { startPermissionUpdateNotices } from "./components/PermissionUpdateNotice"; +import { startProjectScriptRunCoordinator } from "./components/projectScriptRuns/ProjectScriptRunCoordinator"; import { startAgentOpenedPreviews } from "./components/preview/agentOpenedPreviews"; import { startMainAppLocationTracking } from "./components/sidebar/mainAppLocation"; import { startDesktopUpdateLaunchNotice } from "./components/sidebar/updateEverythingRun"; @@ -301,6 +302,7 @@ export function startAppServices(): AppRouter { startPermissionUpdateNotices(router); startThreadNotifications(appAtomRegistry, router); startGuideRunNotifications(appAtomRegistry, router); + startProjectScriptRunCoordinator(appAtomRegistry); if (isElectron) startDesktopUpdateLaunchNotice(); return router; diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index e4f3d690113e5..135642c941536 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -38,6 +38,7 @@ import { usePanelNavigationSuppression, } from "../panelAnimations"; import { BackgroundThreadAnnouncer } from "./BackgroundThreadAnnouncer"; +import { ProjectScriptRunsHost } from "./projectScriptRuns/ProjectScriptRunsHost"; import { HistorySwipeNavigation } from "./HistorySwipeNavigation"; import ThreadSidebar from "./Sidebar"; import { SidebarBrandWidthProbe } from "./sidebar/SidebarChrome"; @@ -490,6 +491,7 @@ export function AppSidebarLayout({ ) : null} {children} + {isElectron ? : null} diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index a94b9e9497c6b..7c0a8f918f30a 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -251,6 +251,7 @@ import { import { SidebarContent, SidebarGroup, useSidebar } from "./ui/sidebar"; import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome"; import { SidebarHeaderIconButton, SidebarThreadHeader } from "./sidebar/SidebarThreadHeader"; +import { ProjectScriptRunsControl } from "./projectScriptRuns/ProjectScriptRunsControl"; import { TooltipProvider } from "./ui/tooltip"; import { composerDraftHasUserContent, @@ -2983,6 +2984,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve 0} + runsControl={} projectScope={ void { + const watchers = new Map void>(); + const sync = (runs: Record) => { + for (const [runId, stop] of watchers) { + const run = runs[runId]; + if (run !== undefined && isProjectScriptRunActive(run)) continue; + watchers.delete(runId); + stop(); + } + for (const run of Object.values(runs)) { + if (!isProjectScriptRunActive(run) || watchers.has(run.id)) continue; + watchers.set(run.id, watchProjectScriptRun(registry, run)); + } + }; + + sync(useProjectScriptRunsStore.getState().runs); + const unsubscribe = useProjectScriptRunsStore.subscribe((state, previous) => { + if (state.runs !== previous.runs) sync(state.runs); + }); + + return () => { + unsubscribe(); + for (const stop of watchers.values()) stop(); + watchers.clear(); + }; +} + +function watchProjectScriptRun( + registry: AtomRegistry.AtomRegistry, + run: ProjectScriptRun, +): () => void { + const atom = terminalEnvironment.observe({ + environmentId: run.environmentId, + input: { threadId: run.threadId, terminalId: run.terminalId }, + }); + const sentinelPattern = projectScriptSentinelPattern(run.sentinel); + let cursor = INITIAL_TERMINAL_OUTPUT_CURSOR; + let lineBuffer = ""; + let tail: string[] = []; + let sawLive = false; + let stopped = false; + let unsubscribe: (() => void) | null = null; + let lostTimer: ReturnType | null = null; + + const stop = () => { + if (stopped) return; + stopped = true; + if (lostTimer !== null) { + clearTimeout(lostTimer); + lostTimer = null; + } + unsubscribe?.(); + }; + + const settle = (patch: ProjectScriptRunPatch) => { + if (stopped) return; + useProjectScriptRunsStore.getState().updateRun(run.id, { + ...patch, + outputTail: tail.slice(-PROJECT_SCRIPT_OUTPUT_TAIL_LINES).join("\n"), + endedAt: Date.now(), + }); + stop(); + }; + + lostTimer = setTimeout(() => { + if (!stopped && !sawLive) { + settle({ status: "lost", errorMessage: "The terminal is no longer available." }); + } + }, LOST_TERMINAL_GRACE_MS); + + const handleLine = (rawLine: string): boolean => { + const sentinel = sentinelPattern.exec(rawLine); + if (sentinel !== null) { + const parsed = Number(sentinel[1]); + const exitCode = Number.isFinite(parsed) ? parsed : null; + settle({ + status: exitCode === 0 ? "succeeded" : "failed", + exitCode, + errorMessage: + exitCode === 0 ? null : (tail.at(-1) ?? `Exited with code ${exitCode ?? "unknown"}.`), + }); + return true; + } + const cleaned = stripProjectScriptOutput(rawLine).trimEnd(); + if (cleaned.length === 0 || isProjectScriptWrapperLine(cleaned)) return false; + tail.push(cleaned.slice(0, 400)); + if (tail.length > PROJECT_SCRIPT_OUTPUT_TAIL_LINES) tail.shift(); + return false; + }; + + const onResult = (result: AsyncResult.AsyncResult) => { + if (stopped) return; + if (result._tag === "Failure") { + if (sawLive) { + settle({ status: "lost", errorMessage: "The terminal is no longer available." }); + } + return; + } + if (result._tag !== "Success") return; + const state = result.value; + if (state.status === "error") { + settle({ + status: "failed", + errorMessage: state.error ?? "The terminal failed to start.", + }); + return; + } + if (state.status === "exited") { + settle({ + status: "failed", + errorMessage: "The terminal exited before the command reported a result.", + }); + return; + } + if (state.status === "closed") { + if (sawLive) { + settle({ + status: "lost", + errorMessage: "The terminal closed before the command reported a result.", + }); + } + return; + } + + sawLive = true; + if (lostTimer !== null) { + clearTimeout(lostTimer); + lostTimer = null; + } + if ( + state.status === "running" && + useProjectScriptRunsStore.getState().runs[run.id]?.status === "starting" + ) { + useProjectScriptRunsStore.getState().updateRun(run.id, { status: "running" }); + } + + const update = readTerminalOutputUpdate(state.output, cursor); + cursor = update.cursor; + if (update.type === "reset") { + lineBuffer = ""; + tail = []; + } + if (update.type === "none") return; + lineBuffer += update.data; + const lines = lineBuffer.split(/\r\n|\r|\n/); + lineBuffer = lines.pop() ?? ""; + for (const line of lines) { + if (handleLine(line)) return; + } + }; + + unsubscribe = registry.subscribe(atom, onResult, { immediate: true }); + if (stopped) unsubscribe(); + return stop; +} diff --git a/apps/web/src/components/projectScriptRuns/ProjectScriptRunDetail.tsx b/apps/web/src/components/projectScriptRuns/ProjectScriptRunDetail.tsx new file mode 100644 index 0000000000000..b13989ea40c58 --- /dev/null +++ b/apps/web/src/components/projectScriptRuns/ProjectScriptRunDetail.tsx @@ -0,0 +1,195 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import { terminalOutputText } from "@t3tools/client-runtime/state/terminal"; +import { AuthTerminalReadScope } from "@t3tools/contracts"; +import { AsyncResult } from "effect/reactivity"; + +import { + isProjectScriptRunActive, + projectScriptOutputTail, + projectScriptRunStatusLabel, + type ProjectScriptRun, + type ProjectScriptRunStatus, +} from "../../projectScriptRuns"; +import { useEnvironmentScope } from "../../state/session"; +import { terminalEnvironment } from "../../state/terminal"; +import { cn } from "../../lib/utils"; +import { ProjectFavicon } from "../ProjectFavicon"; +import { Badge } from "../ui/badge"; +import { Button } from "../ui/button"; +import { + Dialog, + DialogDescription, + DialogFooter, + DialogHeader, + DialogPanel, + DialogPopup, + DialogTitle, +} from "../ui/dialog"; +import { ProjectScriptRunStatusIcon } from "./ProjectScriptRunStatusIcon"; + +function statusVariant(status: ProjectScriptRunStatus): "error" | "success" | "info" | "outline" { + if (status === "failed") return "error"; + if (status === "succeeded") return "success"; + if (status === "running" || status === "starting") return "info"; + return "outline"; +} + +export function ProjectScriptRunDetail({ + run, + project, + recentRuns, + canOperate, + onClose, + onSelectRun, + onStop, + onDismiss, + onOpenInTerminal, +}: { + readonly run: ProjectScriptRun; + readonly project: EnvironmentProject | null; + readonly recentRuns: ReadonlyArray; + readonly canOperate: boolean; + readonly onClose: () => void; + readonly onSelectRun: (runId: string) => void; + readonly onStop: (run: ProjectScriptRun) => void; + readonly onDismiss: (run: ProjectScriptRun) => void; + readonly onOpenInTerminal: (run: ProjectScriptRun) => void; +}) { + const observe = useAtomValue( + terminalEnvironment.observe({ + environmentId: run.environmentId, + input: { threadId: run.threadId, terminalId: run.terminalId }, + }), + ); + const buffer = AsyncResult.getOrElse(observe, () => null); + const liveText = buffer === null ? "" : terminalOutputText(buffer.output); + const output = liveText.length > 0 ? projectScriptOutputTail(liveText) : run.outputTail; + const canRead = useEnvironmentScope(run.environmentId, AuthTerminalReadScope); + const active = isProjectScriptRunActive(run); + + return ( + { + if (!open) onClose(); + }} + > + + + + + + {run.scriptName} + + + + + {project !== null ? ( + + ) : null} + + {run.threadScoped ? `${run.projectTitle} ยท ${run.threadTitle}` : run.projectTitle} + + + + + +
+
+ + {projectScriptRunStatusLabel(run.status)} + + {run.exitCode !== null ? Exit {run.exitCode} : null} + + {new Date(run.startedAt).toLocaleString()} + +
+ {run.errorMessage !== null ? ( +
+ {run.errorMessage} +
+ ) : null} +
+
Command
+
{run.command}
+
Directory
+
{run.cwd}
+
Terminal
+
{run.terminalId}
+
Scope
+
{run.threadScoped ? "Thread worktree" : "Project checkout"}
+
+
+              {output.length > 0 ? output : "No output yet."}
+            
+ {recentRuns.length > 1 ? ( +
+

Recent runs

+
+ {recentRuns.map((entry) => ( + + ))} +
+
+ ) : null} +
+
+ + {active ? ( + + ) : null} + {run.threadScoped ? ( + + ) : null} + + + +
+
+ ); +} diff --git a/apps/web/src/components/projectScriptRuns/ProjectScriptRunStatusIcon.tsx b/apps/web/src/components/projectScriptRuns/ProjectScriptRunStatusIcon.tsx new file mode 100644 index 0000000000000..a9cd006a791a6 --- /dev/null +++ b/apps/web/src/components/projectScriptRuns/ProjectScriptRunStatusIcon.tsx @@ -0,0 +1,30 @@ +import { + CircleAlertIcon, + CircleCheckIcon, + CircleHelpIcon, + CircleSlashIcon, + PlayIcon, + SquareIcon, +} from "lucide-react"; + +import type { ProjectScriptRunStatus } from "../../projectScriptRuns"; + +export function ProjectScriptRunStatusIcon({ + status, + className, +}: { + readonly status: ProjectScriptRunStatus | null; + readonly className?: string | undefined; +}) { + const iconClassName = className ?? "size-3.5"; + if (status === "failed") return ; + if (status === "running" || status === "starting") + return ; + if (status === "succeeded") + return ; + if (status === "stopped") + return ; + if (status === "lost") + return ; + return ; +} diff --git a/apps/web/src/components/projectScriptRuns/ProjectScriptRunsBar.tsx b/apps/web/src/components/projectScriptRuns/ProjectScriptRunsBar.tsx new file mode 100644 index 0000000000000..b6b38bebc6ce7 --- /dev/null +++ b/apps/web/src/components/projectScriptRuns/ProjectScriptRunsBar.tsx @@ -0,0 +1,83 @@ +import { SquareIcon, XIcon } from "lucide-react"; + +import { isProjectScriptRunActive, projectScriptRunStatusLabel } from "../../projectScriptRuns"; +import { cn } from "../../lib/utils"; +import { useProjectScriptRunActions } from "../../hooks/useProjectScriptRuns"; +import { ProjectFavicon } from "../ProjectFavicon"; +import { Button } from "../ui/button"; +import { ProjectScriptRunStatusIcon } from "./ProjectScriptRunStatusIcon"; + +export function ProjectScriptRunsBar() { + const { runsList, canOperate, projectForRun, stopRun, dismissRun, selectRun } = + useProjectScriptRunActions(); + const primary = runsList[0]; + if (primary === undefined) return null; + + const project = projectForRun(primary); + const active = isProjectScriptRunActive(primary); + const failed = primary.status === "failed"; + const remaining = runsList.length - 1; + + return ( +
+ + {active ? ( + + ) : ( + + )} +
+ ); +} diff --git a/apps/web/src/components/projectScriptRuns/ProjectScriptRunsControl.tsx b/apps/web/src/components/projectScriptRuns/ProjectScriptRunsControl.tsx new file mode 100644 index 0000000000000..ef39e42ba548e --- /dev/null +++ b/apps/web/src/components/projectScriptRuns/ProjectScriptRunsControl.tsx @@ -0,0 +1,142 @@ +import { HistoryIcon, PlayIcon } from "lucide-react"; +import { useState } from "react"; + +import { isProjectScriptRunActive, projectScriptRunStatusLabel } from "../../projectScriptRuns"; +import { + useProjectScriptMenuEntries, + useProjectScriptRunActions, +} from "../../hooks/useProjectScriptRuns"; +import { projectScriptMenuLabel } from "@t3tools/shared/projectScripts"; +import { ProjectFavicon } from "../ProjectFavicon"; +import { SidebarHeaderIconButton } from "../sidebar/SidebarThreadHeader"; +import { Button } from "../ui/button"; +import { ProjectScriptRunStatusIcon } from "./ProjectScriptRunStatusIcon"; +import { + Menu, + MenuGroup, + MenuGroupLabel, + MenuItem, + MenuItemLabel, + MenuPopup, + MenuSeparator, + MenuTrigger, +} from "../ui/menu"; + +export function ProjectScriptRunsControl() { + const { entries, showEnvironmentLabel } = useProjectScriptMenuEntries(); + const { runsList, activeRunCount, runScript, stopRun, selectRun } = useProjectScriptRunActions(); + const [menuOpen, setMenuOpen] = useState(false); + + return ( + + } + > + + {activeRunCount > 0 ? ( + + {activeRunCount} + + ) : null} + + + {entries.length === 0 ? ( + + Project actions +

+ No project actions configured. Add them in Settings, Projects, Actions. +

+
+ ) : ( + entries.map((entry, index) => { + const projectKey = `${entry.project.environmentId}:${entry.project.id}`; + return ( + + {index > 0 ? : null} + + + + + {entry.project.title} + + {showEnvironmentLabel && entry.environmentLabel.length > 0 ? ( + + {entry.environmentLabel} + + ) : null} + + + {entry.scripts.map((script) => { + const activeRun = runsList.find( + (run) => + run.environmentId === entry.project.environmentId && + run.projectId === entry.project.id && + run.scriptId === script.id && + isProjectScriptRunActive(run), + ); + const latestRun = runsList + .filter( + (run) => + run.environmentId === entry.project.environmentId && + run.projectId === entry.project.id && + run.scriptId === script.id && + !isProjectScriptRunActive(run), + ) + .sort((left, right) => right.startedAt - left.startedAt)[0]; + const canRun = entry.canOperate; + return ( + { + if (activeRun !== undefined) void stopRun(activeRun); + else void runScript(entry.project, script, entry.anchorThread); + }} + > + {projectScriptMenuLabel(script)} + + {activeRun !== undefined ? ( + {projectScriptRunStatusLabel(activeRun.status)} + ) : null} + + {activeRun === undefined && latestRun !== undefined ? ( + + ) : null} + + + ); + })} + + ); + }) + )} +
+
+ ); +} diff --git a/apps/web/src/components/projectScriptRuns/ProjectScriptRunsHost.tsx b/apps/web/src/components/projectScriptRuns/ProjectScriptRunsHost.tsx new file mode 100644 index 0000000000000..b5c79443e95f4 --- /dev/null +++ b/apps/web/src/components/projectScriptRuns/ProjectScriptRunsHost.tsx @@ -0,0 +1,40 @@ +import { useProjectScriptRunActions } from "../../hooks/useProjectScriptRuns"; +import { ProjectScriptRunDetail } from "./ProjectScriptRunDetail"; + +export function ProjectScriptRunsHost() { + const { + runsList, + selectedRun, + canOperate, + projectForRun, + stopRun, + dismissRun, + openRunInTerminal, + selectRun, + } = useProjectScriptRunActions(); + + if (selectedRun === null) return null; + + const recentRuns = runsList + .filter( + (run) => + run.environmentId === selectedRun.environmentId && + run.projectId === selectedRun.projectId && + run.scriptId === selectedRun.scriptId, + ) + .sort((left, right) => right.startedAt - left.startedAt); + + return ( + selectRun(null)} + onSelectRun={selectRun} + onStop={(run) => void stopRun(run)} + onDismiss={dismissRun} + onOpenInTerminal={openRunInTerminal} + /> + ); +} diff --git a/apps/web/src/components/sidebar/SidebarChrome.tsx b/apps/web/src/components/sidebar/SidebarChrome.tsx index dd41ddd2a0213..30f320c8a127a 100644 --- a/apps/web/src/components/sidebar/SidebarChrome.tsx +++ b/apps/web/src/components/sidebar/SidebarChrome.tsx @@ -38,6 +38,7 @@ import { SidebarThreadUndoNotice } from "./SidebarThreadUndoNotice"; import { SidebarProviderUpdatePill } from "./SidebarProviderUpdatePill"; import { SidebarUpdateArchitectureWarning, SidebarUpdatePill } from "./SidebarUpdatePill"; import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons"; +import { ProjectScriptRunsBar } from "../projectScriptRuns/ProjectScriptRunsBar"; import { observeResize } from "~/lib/observeResize"; export const SidebarChromeHeader = memo(function SidebarChromeHeader({ @@ -294,6 +295,7 @@ const SidebarUtilityMenu = memo(function SidebarUtilityMenu() { export const SidebarChromeFooter = memo(function SidebarChromeFooter() { return ( + diff --git a/apps/web/src/components/sidebar/SidebarThreadHeader.tsx b/apps/web/src/components/sidebar/SidebarThreadHeader.tsx index e400e03d27586..a5cc7c9cb1f91 100644 --- a/apps/web/src/components/sidebar/SidebarThreadHeader.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadHeader.tsx @@ -15,6 +15,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; export interface SidebarThreadHeaderProps { hasProjects: boolean; projectScope: ReactNode; + runsControl?: ReactNode; onNewProject: () => void; onNewThread: (event: ReactMouseEvent) => void; newThreadDisabled: boolean; @@ -34,6 +35,7 @@ export interface SidebarThreadHeaderProps { export function SidebarThreadHeader({ hasProjects, projectScope, + runsControl, onNewProject, onNewThread, newThreadDisabled, @@ -97,6 +99,7 @@ export function SidebarThreadHeader({ ) : null}
+ {runsControl} {hasProjects ? ( <> {projectScope} diff --git a/apps/web/src/hooks/useProjectScriptRuns.ts b/apps/web/src/hooks/useProjectScriptRuns.ts new file mode 100644 index 0000000000000..99d8f83cc08f7 --- /dev/null +++ b/apps/web/src/hooks/useProjectScriptRuns.ts @@ -0,0 +1,278 @@ +import { useNavigate } from "@tanstack/react-router"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import type { + EnvironmentProject, + EnvironmentThreadShell, +} from "@t3tools/client-runtime/state/shell"; +import { + AuthTerminalOperateScope, + DEFAULT_SERVER_SETTINGS, + type EnvironmentId, + type ProjectScript, +} from "@t3tools/contracts"; +import { + projectScriptRuntimeEnv, + projectScriptTerminalInput, + resolveProjectScripts, +} from "@t3tools/shared/projectScripts"; + +import { toastManager } from "../components/ui/toast"; +import { randomUUID } from "../lib/utils"; +import { + isProjectScriptRunActive, + PROJECT_SCRIPT_SENTINEL_ENV, + PROJECT_SCRIPT_SENTINEL_PREFIX, + projectActionsThreadId, + projectLastActivityTimestamp, + resolveProjectAnchorThread, + sortProjectScriptMenuEntries, + sortProjectScriptRuns, + wrapProjectScriptCommand, + type ProjectScriptMenuEntry, + type ProjectScriptRun, +} from "../projectScriptRuns"; +import { useProjectScriptRunsStore } from "../projectScriptRunsStore"; +import { useProjects, useQuietThreadShells, useServerConfigs } from "../state/entities"; +import { useEnvironmentIdentities } from "../state/environments"; +import { useEnvironmentsWithScope } from "../state/session"; +import { terminalEnvironment } from "../state/terminal"; +import { useAtomCommand } from "../state/use-atom-command"; +import { useTerminalUiStateStore } from "../terminalUiStateStore"; +import { buildThreadRouteParams } from "../threadRoutes"; + +const SCRIPT_TERMINAL_COLS = 120; +const SCRIPT_TERMINAL_ROWS = 30; + +function commandFailureMessage(result: Parameters[0]): string { + const error = squashAtomCommandFailure(result); + return error instanceof Error ? error.message : "The action could not start."; +} + +export function useProjectScriptRunActions() { + const projects = useProjects(); + const operateScopes = useEnvironmentsWithScope(projects, AuthTerminalOperateScope); + const openTerminal = useAtomCommand(terminalEnvironment.open, "project action open"); + const writeTerminal = useAtomCommand(terminalEnvironment.write, "project action write"); + const closeTerminal = useAtomCommand(terminalEnvironment.close, "project action close"); + const navigate = useNavigate(); + const runs = useProjectScriptRunsStore((state) => state.runs); + const selectedRunId = useProjectScriptRunsStore((state) => state.selectedRunId); + const startRun = useProjectScriptRunsStore((state) => state.startRun); + const updateRun = useProjectScriptRunsStore((state) => state.updateRun); + const removeRun = useProjectScriptRunsStore((state) => state.removeRun); + const clearFinished = useProjectScriptRunsStore((state) => state.clearFinished); + const selectRun = useProjectScriptRunsStore((state) => state.selectRun); + + const runsList = sortProjectScriptRuns(Object.values(runs)); + const selectedRun = selectedRunId === null ? null : (runs[selectedRunId] ?? null); + const canOperate = (environmentId: EnvironmentId) => operateScopes.has(environmentId); + const projectForRun = (run: ProjectScriptRun) => + projects.find( + (project) => project.environmentId === run.environmentId && project.id === run.projectId, + ) ?? null; + + const runScript = async ( + project: EnvironmentProject, + script: ProjectScript, + anchorThread: EnvironmentThreadShell | null, + ) => { + if (!canOperate(project.environmentId)) { + toastManager.add({ + type: "error", + title: "Cannot run project actions", + description: "This connection cannot run terminal commands.", + }); + return; + } + + const runId = randomUUID(); + const terminalId = `script-${script.id}-${runId.slice(0, 8)}`; + const sentinel = `${PROJECT_SCRIPT_SENTINEL_PREFIX}${runId.replaceAll("-", "")}:`; + const worktreePath = anchorThread?.worktreePath ?? null; + const cwd = worktreePath ?? project.workspaceRoot; + const threadId = anchorThread?.id ?? projectActionsThreadId(project.environmentId, project.id); + const threadTitle = anchorThread?.title ?? project.title; + const run: ProjectScriptRun = { + id: runId, + environmentId: project.environmentId, + projectId: project.id, + projectTitle: project.title, + scriptId: script.id, + scriptName: script.name, + command: script.command, + threadId, + threadTitle, + threadScoped: anchorThread !== null, + terminalId, + cwd, + worktreePath, + sentinel, + startedAt: Date.now(), + status: "starting", + exitCode: null, + errorMessage: null, + outputTail: "", + endedAt: null, + }; + + const openResult = await openTerminal({ + environmentId: project.environmentId, + input: { + threadId, + terminalId, + cwd, + ...(worktreePath !== null ? { worktreePath } : {}), + cols: SCRIPT_TERMINAL_COLS, + rows: SCRIPT_TERMINAL_ROWS, + env: projectScriptRuntimeEnv({ + project: { cwd: project.workspaceRoot }, + worktreePath, + extraEnv: { [PROJECT_SCRIPT_SENTINEL_ENV]: sentinel, COLORTERM: "" }, + }), + }, + }); + if (openResult._tag === "Failure") { + const message = isAtomCommandInterrupted(openResult) + ? "The run was interrupted." + : commandFailureMessage(openResult); + startRun({ ...run, status: "failed", errorMessage: message, endedAt: Date.now() }); + toastManager.add({ + type: "error", + title: `Could not run ${script.name}`, + description: message, + }); + return; + } + + startRun(run); + const writeResult = await writeTerminal({ + environmentId: project.environmentId, + input: { + threadId, + terminalId, + data: projectScriptTerminalInput(wrapProjectScriptCommand(script.command)), + }, + }); + if (writeResult._tag === "Failure") { + const message = isAtomCommandInterrupted(writeResult) + ? "The run was interrupted." + : commandFailureMessage(writeResult); + updateRun(runId, { status: "failed", errorMessage: message, endedAt: Date.now() }); + toastManager.add({ + type: "error", + title: `Could not run ${script.name}`, + description: message, + }); + } + }; + + const stopRun = async (run: ProjectScriptRun) => { + if (!isProjectScriptRunActive(run)) return; + updateRun(run.id, { status: "stopped", endedAt: Date.now() }); + const closeResult = await closeTerminal({ + environmentId: run.environmentId, + input: { threadId: run.threadId, terminalId: run.terminalId, deleteHistory: false }, + }); + if (closeResult._tag === "Failure" && !isAtomCommandInterrupted(closeResult)) { + await writeTerminal({ + environmentId: run.environmentId, + input: { threadId: run.threadId, terminalId: run.terminalId, data: "exit\n" }, + }); + } + }; + + const dismissRun = (run: ProjectScriptRun) => { + removeRun(run.id); + void closeTerminal({ + environmentId: run.environmentId, + input: { threadId: run.threadId, terminalId: run.terminalId, deleteHistory: true }, + }); + }; + + const clearFinishedRuns = () => { + for (const run of Object.values(runs)) { + if (isProjectScriptRunActive(run)) continue; + void closeTerminal({ + environmentId: run.environmentId, + input: { threadId: run.threadId, terminalId: run.terminalId, deleteHistory: true }, + }); + } + clearFinished(); + }; + + const openRunInTerminal = (run: ProjectScriptRun) => { + const threadRef = scopeThreadRef(run.environmentId, run.threadId); + useTerminalUiStateStore + .getState() + .ensureTerminal(threadRef, run.terminalId, { open: true, active: true }); + selectRun(null); + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(threadRef), + }); + }; + + return { + runs, + runsList, + selectedRun, + activeRunCount: runsList.filter(isProjectScriptRunActive).length, + canOperate, + projectForRun, + runScript, + stopRun, + dismissRun, + clearFinishedRuns, + openRunInTerminal, + selectRun, + }; +} + +export function useProjectScriptMenuEntries(): { + readonly entries: ReadonlyArray; + readonly showEnvironmentLabel: boolean; +} { + const projects = useProjects(); + const threads = useQuietThreadShells(); + const configs = useServerConfigs(); + const identities = useEnvironmentIdentities(); + const operateScopes = useEnvironmentsWithScope(projects, AuthTerminalOperateScope); + const labels = new Map( + identities.map((identity) => [identity.environmentId, identity.label] as const), + ); + const threadsByProject = new Map(); + for (const thread of threads) { + if (thread.archivedAt !== null || thread.deletedAt !== null) continue; + const key = `${thread.environmentId}\u0000${thread.projectId}`; + const existing = threadsByProject.get(key); + if (existing === undefined) threadsByProject.set(key, [thread]); + else existing.push(thread); + } + + const entries: ProjectScriptMenuEntry[] = []; + for (const project of projects) { + if (project.archivedAt != null || project.isScratch === true) continue; + const settings = configs.get(project.environmentId)?.settings ?? DEFAULT_SERVER_SETTINGS; + const scripts = resolveProjectScripts(settings, project); + if (scripts.length === 0) continue; + const projectThreads = + threadsByProject.get(`${project.environmentId}\u0000${project.id}`) ?? []; + entries.push({ + project, + scripts, + anchorThread: resolveProjectAnchorThread(projectThreads), + environmentLabel: labels.get(project.environmentId) ?? "", + lastActivity: projectLastActivityTimestamp(project, projectThreads), + canOperate: operateScopes.has(project.environmentId), + }); + } + + return { + entries: sortProjectScriptMenuEntries(entries), + showEnvironmentLabel: identities.length > 1, + }; +} diff --git a/apps/web/src/projectScriptRuns.test.ts b/apps/web/src/projectScriptRuns.test.ts new file mode 100644 index 0000000000000..b3c8e2140b0e0 --- /dev/null +++ b/apps/web/src/projectScriptRuns.test.ts @@ -0,0 +1,180 @@ +import type { + EnvironmentProject, + EnvironmentThreadShell, +} from "@t3tools/client-runtime/state/shell"; +import type { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { + isProjectScriptWrapperLine, + projectScriptOutputTail, + projectScriptSentinelPattern, + resolveProjectAnchorThread, + sortProjectScriptMenuEntries, + sortProjectScriptRuns, + stripProjectScriptOutput, + wrapProjectScriptCommand, + type ProjectScriptMenuEntry, + type ProjectScriptRun, +} from "./projectScriptRuns"; + +const environmentId = "env-1" as EnvironmentId; +const projectId = "project-1" as ProjectId; + +function thread( + overrides: Partial> & { readonly id: string }, +): EnvironmentThreadShell { + const { id, ...rest } = overrides; + return { + environmentId, + projectId, + title: id, + updatedAt: "2026-01-01T00:00:00.000Z", + createdAt: "2026-01-01T00:00:00.000Z", + settledAt: null, + unsettledAt: null, + archivedAt: null, + deletedAt: null, + ...rest, + id: id as ThreadId, + } as unknown as EnvironmentThreadShell; +} + +function project(id: string, title: string): EnvironmentProject { + return { + id: id as ProjectId, + environmentId, + title, + workspaceRoot: `/work/${id}`, + updatedAt: "2026-01-01T00:00:00.000Z", + createdAt: "2026-01-01T00:00:00.000Z", + scripts: [], + pinnedAt: null, + archivedAt: null, + } as unknown as EnvironmentProject; +} + +function run( + overrides: Partial & Pick, +): ProjectScriptRun { + return { + environmentId, + projectId, + projectTitle: "Project", + scriptId: overrides.id, + scriptName: overrides.id, + command: "true", + threadId: "thread-1" as ThreadId, + threadTitle: "Thread", + threadScoped: true, + terminalId: `terminal-${overrides.id}`, + cwd: "/work/project", + worktreePath: null, + sentinel: "__T3_SCRIPT_DONE__token:", + exitCode: null, + errorMessage: null, + outputTail: "", + endedAt: null, + ...overrides, + } as unknown as ProjectScriptRun; +} + +describe("project script runs", () => { + it("wraps a command with a sentinel read from the environment", () => { + const wrapped = wrapProjectScriptCommand("pnpm test"); + + expect(wrapped).toBe( + 'sh -c \'pnpm test\r__t3_status=$?\rprintf "\\n%s%s\\n" "$__T3_SCRIPT_SENTINEL" "$__t3_status"\'', + ); + }); + + it("escapes single quotes and keeps multi-line commands", () => { + const wrapped = wrapProjectScriptCommand("echo 'hi'\npnpm build"); + + expect(wrapped).toContain("echo '\\''hi'\\''"); + expect(wrapped).toContain("echo '\\''hi'\\''\rpnpm build"); + }); + + it("parses only the sentinel with its token", () => { + const pattern = projectScriptSentinelPattern("__T3_SCRIPT_DONE__abc:"); + + expect(pattern.exec("__T3_SCRIPT_DONE__abc:0")?.[1]).toBe("0"); + expect(pattern.exec("__T3_SCRIPT_DONE__abc:-2")?.[1]).toBe("-2"); + expect(pattern.exec("__T3_SCRIPT_DONE__other:0")).toBeNull(); + expect(pattern.exec("$__T3_SCRIPT_SENTINEL:0")).toBeNull(); + }); + + it("strips terminal control codes and keeps the tail", () => { + const text = "\x1b[31mfirst\x1b[0m\nsecond\nthird\n"; + + expect(stripProjectScriptOutput(text)).toBe("first\nsecond\nthird\n"); + expect(projectScriptOutputTail(text, 2)).toBe("second\nthird"); + }); + + it("recognizes the echoed wrapper lines", () => { + expect(isProjectScriptWrapperLine(" sh -c 'pnpm test'")).toBe(true); + expect(isProjectScriptWrapperLine('printf "$__T3_SCRIPT_SENTINEL"')).toBe(true); + expect(isProjectScriptWrapperLine("pnpm test failed")).toBe(false); + }); + + it("picks the most recently active thread and ignores archived threads", () => { + const older = thread({ + id: "older", + settledAt: "2026-01-02T00:00:00.000Z", + }); + const newer = thread({ + id: "newer", + unsettledAt: "2026-02-01T00:00:00.000Z", + }); + const archived = thread({ + id: "archived", + updatedAt: "2026-03-01T00:00:00.000Z", + archivedAt: "2026-03-02T00:00:00.000Z", + }); + + expect(resolveProjectAnchorThread([older, newer, archived])?.id).toBe("newer"); + expect(resolveProjectAnchorThread([])).toBeNull(); + }); + + it("orders menu entries by project activity", () => { + const entries: ProjectScriptMenuEntry[] = [ + { + project: project("slow", "Slow"), + scripts: [], + anchorThread: null, + environmentLabel: "Local", + lastActivity: 1, + canOperate: true, + }, + { + project: project("fast", "Fast"), + scripts: [], + anchorThread: null, + environmentLabel: "Local", + lastActivity: 3, + canOperate: true, + }, + ]; + + expect(sortProjectScriptMenuEntries(entries).map((entry) => entry.project.title)).toEqual([ + "Fast", + "Slow", + ]); + }); + + it("puts failures and active runs before finished runs", () => { + const runs = [ + run({ id: "succeeded", status: "succeeded", startedAt: 5 }), + run({ id: "failed", status: "failed", startedAt: 1 }), + run({ id: "running", status: "running", startedAt: 2 }), + run({ id: "starting", status: "starting", startedAt: 4 }), + ]; + + expect(sortProjectScriptRuns(runs).map((entry) => entry.id)).toEqual([ + "failed", + "running", + "starting", + "succeeded", + ]); + }); +}); diff --git a/apps/web/src/projectScriptRuns.ts b/apps/web/src/projectScriptRuns.ts new file mode 100644 index 0000000000000..92bbabb916465 --- /dev/null +++ b/apps/web/src/projectScriptRuns.ts @@ -0,0 +1,198 @@ +import type { + EnvironmentProject, + EnvironmentThreadShell, +} from "@t3tools/client-runtime/state/shell"; +import { toSortableTimestamp } from "@t3tools/client-runtime/state/thread-sort"; +import type { EnvironmentId, ProjectId, ProjectScript, ThreadId } from "@t3tools/contracts"; + +export type ProjectScriptRunStatus = + | "starting" + | "running" + | "succeeded" + | "failed" + | "stopped" + | "lost"; + +export interface ProjectScriptRun { + readonly id: string; + readonly environmentId: EnvironmentId; + readonly projectId: ProjectId; + readonly projectTitle: string; + readonly scriptId: string; + readonly scriptName: string; + readonly command: string; + readonly threadId: ThreadId; + readonly threadTitle: string; + readonly threadScoped: boolean; + readonly terminalId: string; + readonly cwd: string; + readonly worktreePath: string | null; + readonly sentinel: string; + readonly startedAt: number; + readonly status: ProjectScriptRunStatus; + readonly exitCode: number | null; + readonly errorMessage: string | null; + readonly outputTail: string; + readonly endedAt: number | null; +} + +export type ProjectScriptRunPatch = Partial< + Pick +>; + +export interface ProjectScriptMenuEntry { + readonly project: EnvironmentProject; + readonly scripts: ReadonlyArray; + readonly anchorThread: EnvironmentThreadShell | null; + readonly environmentLabel: string; + readonly lastActivity: number; + readonly canOperate: boolean; +} + +export const PROJECT_SCRIPT_SENTINEL_ENV = "__T3_SCRIPT_SENTINEL"; +export const PROJECT_SCRIPT_SENTINEL_PREFIX = "__T3_SCRIPT_DONE__"; +export const PROJECT_SCRIPT_OUTPUT_TAIL_LINES = 200; + +const PROJECT_ACTIONS_THREAD_PREFIX = "__project_actions__:"; + +/** A terminal key for project-scoped runs, which have no thread to attach to. */ +export function projectActionsThreadId( + environmentId: EnvironmentId, + projectId: ProjectId, +): ThreadId { + return `${PROJECT_ACTIONS_THREAD_PREFIX}${environmentId}:${projectId}` as ThreadId; +} + +const RUN_STATUS_RANK: Record = { + failed: 0, + running: 1, + starting: 2, + lost: 3, + stopped: 4, + succeeded: 5, +}; + +const ANSI_PATTERN = + /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][A-Za-z0-9]|\x1b[=>]/g; +const CONTROL_PATTERN = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g; + +export function isProjectScriptRunActive(run: ProjectScriptRun): boolean { + return run.status === "starting" || run.status === "running"; +} + +export function projectScriptRunStatusLabel(status: ProjectScriptRunStatus): string { + switch (status) { + case "starting": + return "Starting"; + case "running": + return "Running"; + case "succeeded": + return "Succeeded"; + case "failed": + return "Failed"; + case "stopped": + return "Stopped"; + case "lost": + return "Terminal lost"; + } +} + +export function sortProjectScriptRuns( + runs: ReadonlyArray, +): ReadonlyArray { + return [...runs].sort( + (left, right) => + RUN_STATUS_RANK[left.status] - RUN_STATUS_RANK[right.status] || + right.startedAt - left.startedAt, + ); +} + +function shellSingleQuote(value: string): string { + return `'${value.replaceAll("'", "'\\''")}'`; +} + +/** + * Runs the command in a child POSIX shell and prints an exit-code sentinel that the + * run coordinator parses from the terminal stream. The token travels in the + * environment, so the echoed command line never contains it. + */ +export function wrapProjectScriptCommand(command: string): string { + const body = command.replace(/\r?\n/g, "\r"); + const script = [ + body, + "__t3_status=$?", + `printf "\\n%s%s\\n" "$${PROJECT_SCRIPT_SENTINEL_ENV}" "$__t3_status"`, + ].join("\r"); + return `sh -c ${shellSingleQuote(script)}`; +} + +export function projectScriptSentinelPattern(sentinel: string): RegExp { + return new RegExp(`${escapeRegExp(sentinel)}(-?\\d+)`); +} + +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +export function stripProjectScriptOutput(text: string): string { + return text.replace(ANSI_PATTERN, "").replace(CONTROL_PATTERN, ""); +} + +export function projectScriptOutputTail( + text: string, + maxLines = PROJECT_SCRIPT_OUTPUT_TAIL_LINES, +): string { + const lines = stripProjectScriptOutput(text).split(/\r\n|\r|\n/); + if (lines.at(-1) === "") lines.pop(); + return lines.slice(-maxLines).join("\n").trimEnd(); +} + +/** Lines the shell echoes back for the typed wrapper, which are not command output. */ +export function isProjectScriptWrapperLine(line: string): boolean { + const trimmed = line.trimStart(); + return trimmed.startsWith("sh -c ") || trimmed.includes(`$${PROJECT_SCRIPT_SENTINEL_ENV}`); +} + +function projectThreadActivityTimestamp(thread: EnvironmentThreadShell): number { + let latest = Number.NEGATIVE_INFINITY; + for (const value of [thread.unsettledAt, thread.settledAt, thread.updatedAt, thread.createdAt]) { + const parsed = toSortableTimestamp(value ?? undefined); + if (parsed !== null && parsed > latest) latest = parsed; + } + return latest === Number.NEGATIVE_INFINITY ? 0 : latest; +} + +export function resolveProjectAnchorThread( + threads: ReadonlyArray, +): EnvironmentThreadShell | null { + let anchor: EnvironmentThreadShell | null = null; + let anchorTimestamp = Number.NEGATIVE_INFINITY; + for (const thread of threads) { + if (thread.archivedAt !== null || thread.deletedAt !== null) continue; + const timestamp = projectThreadActivityTimestamp(thread); + if (timestamp > anchorTimestamp) { + anchor = thread; + anchorTimestamp = timestamp; + } + } + return anchor; +} + +export function projectLastActivityTimestamp( + project: EnvironmentProject, + threads: ReadonlyArray, +): number { + const anchor = resolveProjectAnchorThread(threads); + if (anchor !== null) return projectThreadActivityTimestamp(anchor); + return toSortableTimestamp(project.updatedAt) ?? 0; +} + +export function sortProjectScriptMenuEntries( + entries: ReadonlyArray, +): ReadonlyArray { + return [...entries].sort( + (left, right) => + right.lastActivity - left.lastActivity || + left.project.title.localeCompare(right.project.title), + ); +} diff --git a/apps/web/src/projectScriptRunsStore.ts b/apps/web/src/projectScriptRunsStore.ts new file mode 100644 index 0000000000000..123a0a6796a62 --- /dev/null +++ b/apps/web/src/projectScriptRunsStore.ts @@ -0,0 +1,67 @@ +import { create } from "zustand"; +import { createJSONStorage, persist } from "zustand/middleware"; + +import { resolveStorage } from "./lib/storage"; +import type { ProjectScriptRun, ProjectScriptRunPatch } from "./projectScriptRuns"; + +interface ProjectScriptRunsStore { + readonly runs: Record; + readonly selectedRunId: string | null; + readonly startRun: (run: ProjectScriptRun) => void; + readonly updateRun: (runId: string, patch: ProjectScriptRunPatch) => void; + readonly removeRun: (runId: string) => void; + readonly clearFinished: () => void; + readonly selectRun: (runId: string | null) => void; +} + +const PROJECT_SCRIPT_RUNS_STORAGE_KEY = "t3code:project-script-runs:v1"; + +export const useProjectScriptRunsStore = create()( + persist( + (set) => ({ + runs: {}, + selectedRunId: null, + startRun: (run) => set((state) => ({ runs: { ...state.runs, [run.id]: run } })), + updateRun: (runId, patch) => + set((state) => { + const run = state.runs[runId]; + if (run === undefined) return state; + return { runs: { ...state.runs, [runId]: { ...run, ...patch } } }; + }), + removeRun: (runId) => + set((state) => { + if (state.runs[runId] === undefined) return state; + const runs = { ...state.runs }; + delete runs[runId]; + return { + runs, + selectedRunId: state.selectedRunId === runId ? null : state.selectedRunId, + }; + }), + clearFinished: () => + set((state) => ({ + runs: Object.fromEntries( + Object.entries(state.runs).filter( + ([, run]) => run.status === "starting" || run.status === "running", + ), + ), + selectedRunId: + state.selectedRunId !== null && + state.runs[state.selectedRunId] !== undefined && + (state.runs[state.selectedRunId]!.status === "starting" || + state.runs[state.selectedRunId]!.status === "running") + ? state.selectedRunId + : null, + })), + selectRun: (runId) => set({ selectedRunId: runId }), + }), + { + name: PROJECT_SCRIPT_RUNS_STORAGE_KEY, + version: 1, + storage: createJSONStorage(() => + resolveStorage(typeof window !== "undefined" ? window.sessionStorage : undefined), + ), + partialize: (state) => ({ runs: state.runs }), + }, + ), +); From 3e089f8780e47487cacb5d9e85ef51b4442354d1 Mon Sep 17 00:00:00 2001 From: Farseen M Date: Mon, 9 Nov 2026 18:03:17 +0530 Subject: [PATCH 2/6] fix(web): address project action review feedback Require terminal read as well as operate before starting a run, label the running icon as a status rather than an action, run the command body in a subshell so exit and set -e still emit the sentinel, and drop echoed wrapper output using a begin marker. The menu now computes entries only while open. Co-Authored-By: Claude Code --- .../ProjectScriptRunCoordinator.ts | 7 + .../ProjectScriptRunDetail.tsx | 6 +- .../ProjectScriptRunStatusIcon.tsx | 2 +- .../ProjectScriptRunsControl.tsx | 198 +++++++++--------- apps/web/src/hooks/useProjectScriptRuns.ts | 15 +- apps/web/src/projectScriptRuns.test.ts | 25 ++- apps/web/src/projectScriptRuns.ts | 35 +++- 7 files changed, 183 insertions(+), 105 deletions(-) diff --git a/apps/web/src/components/projectScriptRuns/ProjectScriptRunCoordinator.ts b/apps/web/src/components/projectScriptRuns/ProjectScriptRunCoordinator.ts index 915f46ff64b82..3411f6a5e6421 100644 --- a/apps/web/src/components/projectScriptRuns/ProjectScriptRunCoordinator.ts +++ b/apps/web/src/components/projectScriptRuns/ProjectScriptRunCoordinator.ts @@ -9,6 +9,7 @@ import { isProjectScriptRunActive, isProjectScriptWrapperLine, PROJECT_SCRIPT_OUTPUT_TAIL_LINES, + projectScriptBeginMarker, projectScriptSentinelPattern, stripProjectScriptOutput, type ProjectScriptRun, @@ -55,9 +56,11 @@ function watchProjectScriptRun( input: { threadId: run.threadId, terminalId: run.terminalId }, }); const sentinelPattern = projectScriptSentinelPattern(run.sentinel); + const beginMarker = projectScriptBeginMarker(run.sentinel); let cursor = INITIAL_TERMINAL_OUTPUT_CURSOR; let lineBuffer = ""; let tail: string[] = []; + let sawBegin = false; let sawLive = false; let stopped = false; let unsubscribe: (() => void) | null = null; @@ -102,6 +105,10 @@ function watchProjectScriptRun( }); return true; } + if (!sawBegin) { + if (rawLine.includes(beginMarker)) sawBegin = true; + return false; + } const cleaned = stripProjectScriptOutput(rawLine).trimEnd(); if (cleaned.length === 0 || isProjectScriptWrapperLine(cleaned)) return false; tail.push(cleaned.slice(0, 400)); diff --git a/apps/web/src/components/projectScriptRuns/ProjectScriptRunDetail.tsx b/apps/web/src/components/projectScriptRuns/ProjectScriptRunDetail.tsx index b13989ea40c58..7f28f5ba4d55d 100644 --- a/apps/web/src/components/projectScriptRuns/ProjectScriptRunDetail.tsx +++ b/apps/web/src/components/projectScriptRuns/ProjectScriptRunDetail.tsx @@ -8,6 +8,7 @@ import { isProjectScriptRunActive, projectScriptOutputTail, projectScriptRunStatusLabel, + projectScriptVisibleOutput, type ProjectScriptRun, type ProjectScriptRunStatus, } from "../../projectScriptRuns"; @@ -63,7 +64,10 @@ export function ProjectScriptRunDetail({ }), ); const buffer = AsyncResult.getOrElse(observe, () => null); - const liveText = buffer === null ? "" : terminalOutputText(buffer.output); + const liveText = + buffer === null + ? "" + : projectScriptVisibleOutput(terminalOutputText(buffer.output), run.sentinel); const output = liveText.length > 0 ? projectScriptOutputTail(liveText) : run.outputTail; const canRead = useEnvironmentScope(run.environmentId, AuthTerminalReadScope); const active = isProjectScriptRunActive(run); diff --git a/apps/web/src/components/projectScriptRuns/ProjectScriptRunStatusIcon.tsx b/apps/web/src/components/projectScriptRuns/ProjectScriptRunStatusIcon.tsx index a9cd006a791a6..f97b88d3e25c6 100644 --- a/apps/web/src/components/projectScriptRuns/ProjectScriptRunStatusIcon.tsx +++ b/apps/web/src/components/projectScriptRuns/ProjectScriptRunStatusIcon.tsx @@ -19,7 +19,7 @@ export function ProjectScriptRunStatusIcon({ const iconClassName = className ?? "size-3.5"; if (status === "failed") return ; if (status === "running" || status === "starting") - return ; + return ; if (status === "succeeded") return ; if (status === "stopped") diff --git a/apps/web/src/components/projectScriptRuns/ProjectScriptRunsControl.tsx b/apps/web/src/components/projectScriptRuns/ProjectScriptRunsControl.tsx index ef39e42ba548e..beab04dd0b747 100644 --- a/apps/web/src/components/projectScriptRuns/ProjectScriptRunsControl.tsx +++ b/apps/web/src/components/projectScriptRuns/ProjectScriptRunsControl.tsx @@ -11,6 +11,7 @@ import { ProjectFavicon } from "../ProjectFavicon"; import { SidebarHeaderIconButton } from "../sidebar/SidebarThreadHeader"; import { Button } from "../ui/button"; import { ProjectScriptRunStatusIcon } from "./ProjectScriptRunStatusIcon"; +import { useProjectScriptRunsStore } from "../../projectScriptRunsStore"; import { Menu, MenuGroup, @@ -23,8 +24,9 @@ import { } from "../ui/menu"; export function ProjectScriptRunsControl() { - const { entries, showEnvironmentLabel } = useProjectScriptMenuEntries(); - const { runsList, activeRunCount, runScript, stopRun, selectRun } = useProjectScriptRunActions(); + const activeRunCount = useProjectScriptRunsStore( + (state) => Object.values(state.runs).filter(isProjectScriptRunActive).length, + ); const [menuOpen, setMenuOpen] = useState(false); return ( @@ -43,100 +45,106 @@ export function ProjectScriptRunsControl() { align="end" className="max-h-[min(70vh,36rem)] w-48 max-w-[calc(100vw_-_2rem)] overflow-y-auto" > - {entries.length === 0 ? ( - - Project actions -

- No project actions configured. Add them in Settings, Projects, Actions. -

-
- ) : ( - entries.map((entry, index) => { - const projectKey = `${entry.project.environmentId}:${entry.project.id}`; - return ( - - {index > 0 ? : null} - - - - - {entry.project.title} - - {showEnvironmentLabel && entry.environmentLabel.length > 0 ? ( - - {entry.environmentLabel} - - ) : null} - - - {entry.scripts.map((script) => { - const activeRun = runsList.find( - (run) => - run.environmentId === entry.project.environmentId && - run.projectId === entry.project.id && - run.scriptId === script.id && - isProjectScriptRunActive(run), - ); - const latestRun = runsList - .filter( - (run) => - run.environmentId === entry.project.environmentId && - run.projectId === entry.project.id && - run.scriptId === script.id && - !isProjectScriptRunActive(run), - ) - .sort((left, right) => right.startedAt - left.startedAt)[0]; - const canRun = entry.canOperate; - return ( - { - if (activeRun !== undefined) void stopRun(activeRun); - else void runScript(entry.project, script, entry.anchorThread); - }} - > - {projectScriptMenuLabel(script)} - - {activeRun !== undefined ? ( - {projectScriptRunStatusLabel(activeRun.status)} - ) : null} - - {activeRun === undefined && latestRun !== undefined ? ( - - ) : null} - - - ); - })} - - ); - }) - )} + setMenuOpen(false)} /> ); } + +function ProjectScriptRunsMenu({ onClose }: { readonly onClose: () => void }) { + const { entries, showEnvironmentLabel } = useProjectScriptMenuEntries(); + const { runsList, runScript, stopRun, selectRun } = useProjectScriptRunActions(); + + if (entries.length === 0) { + return ( + + Project actions +

+ No project actions configured. Add them in Settings, Projects, Actions. +

+
+ ); + } + + return entries.map((entry, index) => { + const projectKey = `${entry.project.environmentId}:${entry.project.id}`; + return ( + + {index > 0 ? : null} + + + + + {entry.project.title} + + {showEnvironmentLabel && entry.environmentLabel.length > 0 ? ( + + {entry.environmentLabel} + + ) : null} + + + {entry.scripts.map((script) => { + const activeRun = runsList.find( + (run) => + run.environmentId === entry.project.environmentId && + run.projectId === entry.project.id && + run.scriptId === script.id && + isProjectScriptRunActive(run), + ); + const latestRun = runsList + .filter( + (run) => + run.environmentId === entry.project.environmentId && + run.projectId === entry.project.id && + run.scriptId === script.id && + !isProjectScriptRunActive(run), + ) + .sort((left, right) => right.startedAt - left.startedAt)[0]; + const canRun = entry.canOperate; + return ( + { + if (activeRun !== undefined) void stopRun(activeRun); + else void runScript(entry.project, script, entry.anchorThread); + }} + > + {projectScriptMenuLabel(script)} + + {activeRun !== undefined ? ( + {projectScriptRunStatusLabel(activeRun.status)} + ) : null} + + {activeRun === undefined && latestRun !== undefined ? ( + + ) : null} + + + ); + })} + + ); + }); +} diff --git a/apps/web/src/hooks/useProjectScriptRuns.ts b/apps/web/src/hooks/useProjectScriptRuns.ts index 99d8f83cc08f7..fb3cb51cad208 100644 --- a/apps/web/src/hooks/useProjectScriptRuns.ts +++ b/apps/web/src/hooks/useProjectScriptRuns.ts @@ -10,6 +10,7 @@ import type { } from "@t3tools/client-runtime/state/shell"; import { AuthTerminalOperateScope, + AuthTerminalReadScope, DEFAULT_SERVER_SETTINGS, type EnvironmentId, type ProjectScript, @@ -24,10 +25,12 @@ import { toastManager } from "../components/ui/toast"; import { randomUUID } from "../lib/utils"; import { isProjectScriptRunActive, + PROJECT_SCRIPT_BEGIN_ENV, PROJECT_SCRIPT_SENTINEL_ENV, PROJECT_SCRIPT_SENTINEL_PREFIX, projectActionsThreadId, projectLastActivityTimestamp, + projectScriptBeginMarker, resolveProjectAnchorThread, sortProjectScriptMenuEntries, sortProjectScriptRuns, @@ -55,6 +58,7 @@ function commandFailureMessage(result: Parameters operateScopes.has(environmentId); + const canRead = (environmentId: EnvironmentId) => readScopes.has(environmentId); const projectForRun = (run: ProjectScriptRun) => projects.find( (project) => project.environmentId === run.environmentId && project.id === run.projectId, @@ -80,11 +85,11 @@ export function useProjectScriptRunActions() { script: ProjectScript, anchorThread: EnvironmentThreadShell | null, ) => { - if (!canOperate(project.environmentId)) { + if (!canOperate(project.environmentId) || !canRead(project.environmentId)) { toastManager.add({ type: "error", title: "Cannot run project actions", - description: "This connection cannot run terminal commands.", + description: "This connection needs terminal read and operate permissions.", }); return; } @@ -131,7 +136,11 @@ export function useProjectScriptRunActions() { env: projectScriptRuntimeEnv({ project: { cwd: project.workspaceRoot }, worktreePath, - extraEnv: { [PROJECT_SCRIPT_SENTINEL_ENV]: sentinel, COLORTERM: "" }, + extraEnv: { + [PROJECT_SCRIPT_BEGIN_ENV]: projectScriptBeginMarker(sentinel), + [PROJECT_SCRIPT_SENTINEL_ENV]: sentinel, + COLORTERM: "", + }, }), }, }); diff --git a/apps/web/src/projectScriptRuns.test.ts b/apps/web/src/projectScriptRuns.test.ts index b3c8e2140b0e0..02ced0d33944c 100644 --- a/apps/web/src/projectScriptRuns.test.ts +++ b/apps/web/src/projectScriptRuns.test.ts @@ -7,8 +7,10 @@ import { describe, expect, it } from "vite-plus/test"; import { isProjectScriptWrapperLine, + projectScriptBeginMarker, projectScriptOutputTail, projectScriptSentinelPattern, + projectScriptVisibleOutput, resolveProjectAnchorThread, sortProjectScriptMenuEntries, sortProjectScriptRuns, @@ -84,7 +86,7 @@ describe("project script runs", () => { const wrapped = wrapProjectScriptCommand("pnpm test"); expect(wrapped).toBe( - 'sh -c \'pnpm test\r__t3_status=$?\rprintf "\\n%s%s\\n" "$__T3_SCRIPT_SENTINEL" "$__t3_status"\'', + 'sh -c \'printf "\\n%s\\n" "$__T3_SCRIPT_BEGIN"\r(\rpnpm test\r)\r__t3_status=$?\rprintf "\\n%s%s\\n" "$__T3_SCRIPT_SENTINEL" "$__t3_status"\'', ); }); @@ -113,10 +115,31 @@ describe("project script runs", () => { it("recognizes the echoed wrapper lines", () => { expect(isProjectScriptWrapperLine(" sh -c 'pnpm test'")).toBe(true); + expect(isProjectScriptWrapperLine("[~/project] sh -c 'pnpm test'")).toBe(true); + expect(isProjectScriptWrapperLine("quote> __t3_status=$?")).toBe(true); expect(isProjectScriptWrapperLine('printf "$__T3_SCRIPT_SENTINEL"')).toBe(true); expect(isProjectScriptWrapperLine("pnpm test failed")).toBe(false); }); + it("shows output after the begin marker without the wrapper or end sentinel", () => { + const sentinel = "__T3_SCRIPT_DONE__token:"; + const text = [ + '[~/project] sh -c \'printf "\\n%s\\n" "$__T3_SCRIPT_BEGIN"', + "quote> (", + "quote> pnpm test", + "quote> )", + "quote> __t3_status=$?", + projectScriptBeginMarker(sentinel), + "first line", + "second line", + `${sentinel}0`, + "[~/project]", + ].join("\r\n"); + + expect(projectScriptVisibleOutput(text, sentinel)).toBe("first line\nsecond line"); + expect(projectScriptVisibleOutput("plain output", sentinel)).toBe("plain output"); + }); + it("picks the most recently active thread and ignores archived threads", () => { const older = thread({ id: "older", diff --git a/apps/web/src/projectScriptRuns.ts b/apps/web/src/projectScriptRuns.ts index 92bbabb916465..839b3c12339f8 100644 --- a/apps/web/src/projectScriptRuns.ts +++ b/apps/web/src/projectScriptRuns.ts @@ -50,6 +50,7 @@ export interface ProjectScriptMenuEntry { } export const PROJECT_SCRIPT_SENTINEL_ENV = "__T3_SCRIPT_SENTINEL"; +export const PROJECT_SCRIPT_BEGIN_ENV = "__T3_SCRIPT_BEGIN"; export const PROJECT_SCRIPT_SENTINEL_PREFIX = "__T3_SCRIPT_DONE__"; export const PROJECT_SCRIPT_OUTPUT_TAIL_LINES = 200; @@ -112,20 +113,27 @@ function shellSingleQuote(value: string): string { } /** - * Runs the command in a child POSIX shell and prints an exit-code sentinel that the - * run coordinator parses from the terminal stream. The token travels in the - * environment, so the echoed command line never contains it. + * Runs the command in a child POSIX shell and prints a begin marker and an exit-code + * sentinel that the run coordinator parses from the terminal stream. The tokens travel + * in the environment, so the echoed command line never contains them. */ export function wrapProjectScriptCommand(command: string): string { const body = command.replace(/\r?\n/g, "\r"); const script = [ + `printf "\\n%s\\n" "$${PROJECT_SCRIPT_BEGIN_ENV}"`, + "(", body, + ")", "__t3_status=$?", `printf "\\n%s%s\\n" "$${PROJECT_SCRIPT_SENTINEL_ENV}" "$__t3_status"`, ].join("\r"); return `sh -c ${shellSingleQuote(script)}`; } +export function projectScriptBeginMarker(sentinel: string): string { + return `${sentinel}BEGIN`; +} + export function projectScriptSentinelPattern(sentinel: string): RegExp { return new RegExp(`${escapeRegExp(sentinel)}(-?\\d+)`); } @@ -150,7 +158,26 @@ export function projectScriptOutputTail( /** Lines the shell echoes back for the typed wrapper, which are not command output. */ export function isProjectScriptWrapperLine(line: string): boolean { const trimmed = line.trimStart(); - return trimmed.startsWith("sh -c ") || trimmed.includes(`$${PROJECT_SCRIPT_SENTINEL_ENV}`); + return ( + trimmed.includes("sh -c '") || + trimmed.includes("__t3_status") || + trimmed.includes(`$${PROJECT_SCRIPT_SENTINEL_ENV}`) + ); +} + +/** Terminal text after the begin marker, without the echoed wrapper or the end sentinel. */ +export function projectScriptVisibleOutput(text: string, sentinel: string): string { + const marker = projectScriptBeginMarker(sentinel); + const markerIndex = text.indexOf(marker); + if (markerIndex === -1) return text; + const afterMarker = text.slice(markerIndex + marker.length).replace(/^(?:\r\n|\r|\n)/, ""); + const endIndex = afterMarker.search(projectScriptSentinelPattern(sentinel)); + const body = endIndex === -1 ? afterMarker : afterMarker.slice(0, endIndex); + return body + .split(/\r\n|\r|\n/) + .filter((line) => !isProjectScriptWrapperLine(line)) + .join("\n") + .trimEnd(); } function projectThreadActivityTimestamp(thread: EnvironmentThreadShell): number { From a5b022e77ae855521c256dc96458cea17e8287a0 Mon Sep 17 00:00:00 2001 From: Farseen M Date: Mon, 16 Nov 2026 17:43:44 +0530 Subject: [PATCH 3/6] fix(web): finish project action run integration Send headless action input through the queued shell-startup write path and retain the reviewed run-state handling. --- .../ProjectScriptRunCoordinator.ts | 55 +++-- apps/web/src/hooks/useProjectScriptRuns.ts | 46 +++- apps/web/src/projectScriptRuns.test.ts | 212 ++++++++++++++++-- apps/web/src/projectScriptRuns.ts | 42 +++- apps/web/src/projectScriptRunsStore.ts | 18 ++ 5 files changed, 322 insertions(+), 51 deletions(-) diff --git a/apps/web/src/components/projectScriptRuns/ProjectScriptRunCoordinator.ts b/apps/web/src/components/projectScriptRuns/ProjectScriptRunCoordinator.ts index 3411f6a5e6421..2cff76eca992e 100644 --- a/apps/web/src/components/projectScriptRuns/ProjectScriptRunCoordinator.ts +++ b/apps/web/src/components/projectScriptRuns/ProjectScriptRunCoordinator.ts @@ -1,3 +1,4 @@ +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime"; import type { TerminalBufferState } from "@t3tools/client-runtime/state/terminal"; import { INITIAL_TERMINAL_OUTPUT_CURSOR, @@ -11,6 +12,7 @@ import { PROJECT_SCRIPT_OUTPUT_TAIL_LINES, projectScriptBeginMarker, projectScriptSentinelPattern, + projectScriptStoppedPatch, stripProjectScriptOutput, type ProjectScriptRun, type ProjectScriptRunPatch, @@ -76,7 +78,7 @@ function watchProjectScriptRun( unsubscribe?.(); }; - const settle = (patch: ProjectScriptRunPatch) => { + const settle = (patch: ProjectScriptRunPatch, closeTerminal = true) => { if (stopped) return; useProjectScriptRunsStore.getState().updateRun(run.id, { ...patch, @@ -84,11 +86,26 @@ function watchProjectScriptRun( endedAt: Date.now(), }); stop(); + if (!closeTerminal) return; + void runAtomCommand(registry, terminalEnvironment.close, { + environmentId: run.environmentId, + input: { threadId: run.threadId, terminalId: run.terminalId, deleteHistory: false }, + }); + }; + + const stopPending = () => useProjectScriptRunsStore.getState().pendingStopRunIds.has(run.id); + + const settleRequestedStop = () => { + const currentRun = useProjectScriptRunsStore.getState().runs[run.id]; + const stoppedPatch = + currentRun === undefined ? null : projectScriptStoppedPatch(currentRun, Date.now()); + if (stoppedPatch !== null) settle(stoppedPatch, false); }; lostTimer = setTimeout(() => { if (!stopped && !sawLive) { - settle({ status: "lost", errorMessage: "The terminal is no longer available." }); + if (stopPending()) settleRequestedStop(); + else settle({ status: "lost", errorMessage: "The terminal is no longer available." }); } }, LOST_TERMINAL_GRACE_MS); @@ -126,6 +143,21 @@ function watchProjectScriptRun( } if (result._tag !== "Success") return; const state = result.value; + + const update = readTerminalOutputUpdate(state.output, cursor); + cursor = update.cursor; + if (update.type === "reset") { + lineBuffer = ""; + tail = []; + } + if (update.type !== "none") { + lineBuffer += update.data; + const lines = lineBuffer.split(/\r\n|\r|\n/); + lineBuffer = (lines.pop() ?? "").slice(-4096); + for (const line of lines) { + if (handleLine(line)) return; + } + } if (state.status === "error") { settle({ status: "failed", @@ -141,7 +173,9 @@ function watchProjectScriptRun( return; } if (state.status === "closed") { - if (sawLive) { + if (stopPending()) { + settleRequestedStop(); + } else if (sawLive) { settle({ status: "lost", errorMessage: "The terminal closed before the command reported a result.", @@ -149,7 +183,6 @@ function watchProjectScriptRun( } return; } - sawLive = true; if (lostTimer !== null) { clearTimeout(lostTimer); @@ -161,20 +194,6 @@ function watchProjectScriptRun( ) { useProjectScriptRunsStore.getState().updateRun(run.id, { status: "running" }); } - - const update = readTerminalOutputUpdate(state.output, cursor); - cursor = update.cursor; - if (update.type === "reset") { - lineBuffer = ""; - tail = []; - } - if (update.type === "none") return; - lineBuffer += update.data; - const lines = lineBuffer.split(/\r\n|\r|\n/); - lineBuffer = lines.pop() ?? ""; - for (const line of lines) { - if (handleLine(line)) return; - } }; unsubscribe = registry.subscribe(atom, onResult, { immediate: true }); diff --git a/apps/web/src/hooks/useProjectScriptRuns.ts b/apps/web/src/hooks/useProjectScriptRuns.ts index fb3cb51cad208..23e5da909e5a5 100644 --- a/apps/web/src/hooks/useProjectScriptRuns.ts +++ b/apps/web/src/hooks/useProjectScriptRuns.ts @@ -31,9 +31,11 @@ import { projectActionsThreadId, projectLastActivityTimestamp, projectScriptBeginMarker, + projectScriptStopRollbackPatch, resolveProjectAnchorThread, sortProjectScriptMenuEntries, sortProjectScriptRuns, + projectScriptStoppedPatch, wrapProjectScriptCommand, type ProjectScriptMenuEntry, type ProjectScriptRun, @@ -57,6 +59,7 @@ function commandFailureMessage(result: Parameters state.removeRun); const clearFinished = useProjectScriptRunsStore((state) => state.clearFinished); const selectRun = useProjectScriptRunsStore((state) => state.selectRun); + const beginStop = useProjectScriptRunsStore((state) => state.beginStop); + const endStop = useProjectScriptRunsStore((state) => state.endStop); const runsList = sortProjectScriptRuns(Object.values(runs)); const selectedRun = selectedRunId === null ? null : (runs[selectedRunId] ?? null); @@ -94,6 +99,16 @@ export function useProjectScriptRunActions() { return; } + if (configs.get(project.environmentId)?.environment.platform.os === "windows") { + toastManager.add({ + type: "error", + title: "Cannot run project actions", + description: + "Sidebar actions are not supported on Windows. Run this action from its thread instead.", + }); + return; + } + const runId = randomUUID(); const terminalId = `script-${script.id}-${runId.slice(0, 8)}`; const sentinel = `${PROJECT_SCRIPT_SENTINEL_PREFIX}${runId.replaceAll("-", "")}:`; @@ -124,6 +139,7 @@ export function useProjectScriptRunActions() { endedAt: null, }; + const wrappedCommand = wrapProjectScriptCommand(script.command); const openResult = await openTerminal({ environmentId: project.environmentId, input: { @@ -163,7 +179,8 @@ export function useProjectScriptRunActions() { input: { threadId, terminalId, - data: projectScriptTerminalInput(wrapProjectScriptCommand(script.command)), + data: projectScriptTerminalInput(wrappedCommand), + afterShellStartup: true, }, }); if (writeResult._tag === "Failure") { @@ -180,18 +197,31 @@ export function useProjectScriptRunActions() { }; const stopRun = async (run: ProjectScriptRun) => { - if (!isProjectScriptRunActive(run)) return; - updateRun(run.id, { status: "stopped", endedAt: Date.now() }); + const previousRun = useProjectScriptRunsStore.getState().runs[run.id]; + if ( + previousRun === undefined || + !isProjectScriptRunActive(previousRun) || + useProjectScriptRunsStore.getState().pendingStopRunIds.has(run.id) + ) { + return; + } + + beginStop(run.id); const closeResult = await closeTerminal({ environmentId: run.environmentId, input: { threadId: run.threadId, terminalId: run.terminalId, deleteHistory: false }, }); - if (closeResult._tag === "Failure" && !isAtomCommandInterrupted(closeResult)) { - await writeTerminal({ - environmentId: run.environmentId, - input: { threadId: run.threadId, terminalId: run.terminalId, data: "exit\n" }, - }); + const currentRun = useProjectScriptRunsStore.getState().runs[run.id]; + if (currentRun !== undefined) { + if (closeResult._tag === "Success") { + const stoppedPatch = projectScriptStoppedPatch(currentRun, Date.now()); + if (stoppedPatch !== null) updateRun(run.id, stoppedPatch); + } else { + const rollbackPatch = projectScriptStopRollbackPatch(currentRun, previousRun); + if (rollbackPatch !== null) updateRun(run.id, rollbackPatch); + } } + endStop(run.id); }; const dismissRun = (run: ProjectScriptRun) => { diff --git a/apps/web/src/projectScriptRuns.test.ts b/apps/web/src/projectScriptRuns.test.ts index 02ced0d33944c..24b99a221f863 100644 --- a/apps/web/src/projectScriptRuns.test.ts +++ b/apps/web/src/projectScriptRuns.test.ts @@ -1,15 +1,30 @@ +// @effect-diagnostics nodeBuiltinImport:off - executes the wrapper in a real shell. +import * as NodeChildProcess from "node:child_process"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import type { EnvironmentProject, EnvironmentThreadShell, } from "@t3tools/client-runtime/state/shell"; import type { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts"; -import { describe, expect, it } from "vite-plus/test"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { Atom, AtomRegistry, AsyncResult } from "effect/reactivity"; +import { EMPTY_TERMINAL_BUFFER_STATE } from "@t3tools/client-runtime/state/terminal"; +import { startProjectScriptRunCoordinator } from "./components/projectScriptRuns/ProjectScriptRunCoordinator"; +import { terminalEnvironment } from "./state/terminal"; +import { useProjectScriptRunsStore } from "./projectScriptRunsStore"; + +vi.mock("./state/terminal", () => ({ terminalEnvironment: { observe: vi.fn(), close: {} } })); +vi.mock("@t3tools/client-runtime/state/runtime", () => ({ + runAtomCommand: vi.fn().mockResolvedValue({ _tag: "Success", value: undefined }), +})); import { isProjectScriptWrapperLine, projectScriptBeginMarker, projectScriptOutputTail, projectScriptSentinelPattern, + projectScriptStopRollbackPatch, + projectScriptStoppedPatch, projectScriptVisibleOutput, resolveProjectAnchorThread, sortProjectScriptMenuEntries, @@ -82,21 +97,6 @@ function run( } describe("project script runs", () => { - it("wraps a command with a sentinel read from the environment", () => { - const wrapped = wrapProjectScriptCommand("pnpm test"); - - expect(wrapped).toBe( - 'sh -c \'printf "\\n%s\\n" "$__T3_SCRIPT_BEGIN"\r(\rpnpm test\r)\r__t3_status=$?\rprintf "\\n%s%s\\n" "$__T3_SCRIPT_SENTINEL" "$__t3_status"\'', - ); - }); - - it("escapes single quotes and keeps multi-line commands", () => { - const wrapped = wrapProjectScriptCommand("echo 'hi'\npnpm build"); - - expect(wrapped).toContain("echo '\\''hi'\\''"); - expect(wrapped).toContain("echo '\\''hi'\\''\rpnpm build"); - }); - it("parses only the sentinel with its token", () => { const pattern = projectScriptSentinelPattern("__T3_SCRIPT_DONE__abc:"); @@ -200,4 +200,184 @@ describe("project script runs", () => { "succeeded", ]); }); + + it("does not replace completion recorded while Stop is pending", () => { + const runId = "stop-race"; + const activeRun = run({ id: runId, status: "running", startedAt: 0 }); + useProjectScriptRunsStore.setState({ runs: { [runId]: activeRun } }); + useProjectScriptRunsStore.getState().updateRun(runId, { + status: "succeeded", + exitCode: 0, + endedAt: 10, + }); + + const currentRun = useProjectScriptRunsStore.getState().runs[runId]!; + const stoppedPatch = projectScriptStoppedPatch(currentRun, 20); + if (stoppedPatch !== null) { + useProjectScriptRunsStore.getState().updateRun(runId, stoppedPatch); + } + + expect(useProjectScriptRunsStore.getState().runs[runId]).toMatchObject({ + status: "succeeded", + exitCode: 0, + endedAt: 10, + }); + useProjectScriptRunsStore.setState({ runs: {} }); + }); + + it("restores the active run if terminal close fails", () => { + const activeRun = run({ id: "stop-failure", status: "running", startedAt: 0 }); + const stoppedRun = { + ...activeRun, + status: "stopped" as const, + endedAt: 20, + }; + + expect(projectScriptStopRollbackPatch(stoppedRun, activeRun)).toEqual({ + status: "running", + errorMessage: null, + exitCode: null, + endedAt: null, + }); + expect( + projectScriptStopRollbackPatch({ ...activeRun, status: "succeeded" }, activeRun), + ).toBeNull(); + }); +}); + +it.each([0, 7, null])("reads buffered completion before shell exit (%s)", (exitCode) => { + const registry = AtomRegistry.make(); + const currentRun = run({ id: "buffered", status: "starting", startedAt: 0 }); + const text = + projectScriptBeginMarker(currentRun.sentinel) + + "\noutput\n" + + (exitCode === null ? "" : currentRun.sentinel + exitCode + "\n"); + const atom = Atom.make( + AsyncResult.success({ + ...EMPTY_TERMINAL_BUFFER_STATE, + status: "exited" as const, + output: { + ...EMPTY_TERMINAL_BUFFER_STATE.output, + chunks: [{ startOffset: 0, data: text, byteLength: text.length }], + retainedBytes: text.length, + nextOffset: text.length, + }, + }), + ); + vi.mocked(terminalEnvironment.observe).mockReturnValue(atom); + useProjectScriptRunsStore.setState({ runs: { [currentRun.id]: currentRun } }); + const stop = startProjectScriptRunCoordinator(registry); + try { + expect(useProjectScriptRunsStore.getState().runs[currentRun.id]).toMatchObject({ + status: exitCode === 0 ? "succeeded" : "failed", + exitCode, + outputTail: "output", + }); + } finally { + stop(); + registry.dispose(); + useProjectScriptRunsStore.setState({ runs: {}, pendingStopRunIds: new Set() }); + } +}); + +it("records a requested stop when the terminal closes", () => { + const registry = AtomRegistry.make(); + const currentRun = run({ id: "requested-stop", status: "running", startedAt: 0 }); + const atom = Atom.make( + AsyncResult.success({ + ...EMPTY_TERMINAL_BUFFER_STATE, + status: "closed" as const, + }), + ); + vi.mocked(terminalEnvironment.observe).mockReturnValue(atom); + useProjectScriptRunsStore.setState({ + runs: { [currentRun.id]: currentRun }, + pendingStopRunIds: new Set([currentRun.id]), + }); + const stop = startProjectScriptRunCoordinator(registry); + try { + expect(useProjectScriptRunsStore.getState().runs[currentRun.id]).toMatchObject({ + status: "stopped", + exitCode: null, + errorMessage: null, + }); + } finally { + stop(); + registry.dispose(); + useProjectScriptRunsStore.setState({ runs: {}, pendingStopRunIds: new Set() }); + } +}); + +it("keeps completion observed while a requested stop is pending", () => { + const registry = AtomRegistry.make(); + const currentRun = run({ id: "stop-completion", status: "running", startedAt: 0 }); + const text = + projectScriptBeginMarker(currentRun.sentinel) + "\noutput\n" + currentRun.sentinel + "0\n"; + const atom = Atom.make( + AsyncResult.success({ + ...EMPTY_TERMINAL_BUFFER_STATE, + status: "closed" as const, + output: { + ...EMPTY_TERMINAL_BUFFER_STATE.output, + chunks: [{ startOffset: 0, data: text, byteLength: text.length }], + retainedBytes: text.length, + nextOffset: text.length, + }, + }), + ); + vi.mocked(terminalEnvironment.observe).mockReturnValue(atom); + useProjectScriptRunsStore.setState({ + runs: { [currentRun.id]: currentRun }, + pendingStopRunIds: new Set([currentRun.id]), + }); + const stop = startProjectScriptRunCoordinator(registry); + try { + expect(useProjectScriptRunsStore.getState().runs[currentRun.id]).toMatchObject({ + status: "succeeded", + exitCode: 0, + outputTail: "output", + }); + } finally { + stop(); + registry.dispose(); + useProjectScriptRunsStore.setState({ runs: {}, pendingStopRunIds: new Set() }); + } +}); + +describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("POSIX project commands", () => { + it("runs commands in the user's shell and reports the exit code", () => { + const wrapped = wrapProjectScriptCommand("greet; [[ 1 == 1 ]]; exit 7"); + const output = NodeChildProcess.execFileSync( + "bash", + ["-c", "greet() { printf 'hello\\n'; };\n" + wrapped], + { + env: { + PATH: HostProcess.Environment.defaultValue().PATH, + __T3_SCRIPT_BEGIN: "begin", + __T3_SCRIPT_SENTINEL: "done:", + }, + encoding: "utf8", + }, + ); + + expect(output).toContain("hello"); + expect(output).toContain("done:7"); + }); + + it("runs quoted commands through the fallback shell", () => { + const output = NodeChildProcess.execFileSync( + "sh", + ["-c", wrapProjectScriptCommand("printf '%s' \"it's working\"", false)], + { + env: { + PATH: HostProcess.Environment.defaultValue().PATH, + __T3_SCRIPT_BEGIN: "begin", + __T3_SCRIPT_SENTINEL: "done:", + }, + encoding: "utf8", + }, + ); + expect(output).toContain("it's working"); + expect(output).toContain("done:0"); + }); }); diff --git a/apps/web/src/projectScriptRuns.ts b/apps/web/src/projectScriptRuns.ts index 839b3c12339f8..498b9ee3262f6 100644 --- a/apps/web/src/projectScriptRuns.ts +++ b/apps/web/src/projectScriptRuns.ts @@ -81,6 +81,32 @@ export function isProjectScriptRunActive(run: ProjectScriptRun): boolean { return run.status === "starting" || run.status === "running"; } +export function projectScriptStoppedPatch( + run: ProjectScriptRun, + endedAt: number, +): ProjectScriptRunPatch | null { + if (!isProjectScriptRunActive(run)) return null; + return { + status: "stopped", + errorMessage: null, + exitCode: null, + endedAt, + }; +} + +export function projectScriptStopRollbackPatch( + currentRun: ProjectScriptRun, + previousRun: ProjectScriptRun, +): ProjectScriptRunPatch | null { + if (currentRun.status !== "stopped" || !isProjectScriptRunActive(previousRun)) return null; + return { + status: previousRun.status, + errorMessage: previousRun.errorMessage, + exitCode: previousRun.exitCode, + endedAt: previousRun.endedAt, + }; +} + export function projectScriptRunStatusLabel(status: ProjectScriptRunStatus): string { switch (status) { case "starting": @@ -108,17 +134,15 @@ export function sortProjectScriptRuns( ); } -function shellSingleQuote(value: string): string { - return `'${value.replaceAll("'", "'\\''")}'`; -} - /** - * Runs the command in a child POSIX shell and prints a begin marker and an exit-code + * Runs the command in the current shell and prints a begin marker and an exit-code * sentinel that the run coordinator parses from the terminal stream. The tokens travel * in the environment, so the echoed command line never contains them. */ -export function wrapProjectScriptCommand(command: string): string { - const body = command.replace(/\r?\n/g, "\r"); +export function wrapProjectScriptCommand(command: string, useCurrentShell = true): string { + // The wrapper may be typed into a shell or passed as an initial command to a + // shell's -c, so every separator has to be a real line break. + const body = command.replace(/\r\n|\r/g, "\n"); const script = [ `printf "\\n%s\\n" "$${PROJECT_SCRIPT_BEGIN_ENV}"`, "(", @@ -126,8 +150,8 @@ export function wrapProjectScriptCommand(command: string): string { ")", "__t3_status=$?", `printf "\\n%s%s\\n" "$${PROJECT_SCRIPT_SENTINEL_ENV}" "$__t3_status"`, - ].join("\r"); - return `sh -c ${shellSingleQuote(script)}`; + ].join("\n"); + return useCurrentShell ? script : `sh -c '${script.replaceAll("'", "'\\''")}'`; } export function projectScriptBeginMarker(sentinel: string): string { diff --git a/apps/web/src/projectScriptRunsStore.ts b/apps/web/src/projectScriptRunsStore.ts index 123a0a6796a62..09c77d43fed39 100644 --- a/apps/web/src/projectScriptRunsStore.ts +++ b/apps/web/src/projectScriptRunsStore.ts @@ -7,11 +7,14 @@ import type { ProjectScriptRun, ProjectScriptRunPatch } from "./projectScriptRun interface ProjectScriptRunsStore { readonly runs: Record; readonly selectedRunId: string | null; + readonly pendingStopRunIds: ReadonlySet; readonly startRun: (run: ProjectScriptRun) => void; readonly updateRun: (runId: string, patch: ProjectScriptRunPatch) => void; readonly removeRun: (runId: string) => void; readonly clearFinished: () => void; readonly selectRun: (runId: string | null) => void; + readonly beginStop: (runId: string) => void; + readonly endStop: (runId: string) => void; } const PROJECT_SCRIPT_RUNS_STORAGE_KEY = "t3code:project-script-runs:v1"; @@ -21,6 +24,7 @@ export const useProjectScriptRunsStore = create()( (set) => ({ runs: {}, selectedRunId: null, + pendingStopRunIds: new Set(), startRun: (run) => set((state) => ({ runs: { ...state.runs, [run.id]: run } })), updateRun: (runId, patch) => set((state) => { @@ -54,6 +58,20 @@ export const useProjectScriptRunsStore = create()( : null, })), selectRun: (runId) => set({ selectedRunId: runId }), + beginStop: (runId) => + set((state) => { + if (state.pendingStopRunIds.has(runId)) return state; + const pendingStopRunIds = new Set(state.pendingStopRunIds); + pendingStopRunIds.add(runId); + return { pendingStopRunIds }; + }), + endStop: (runId) => + set((state) => { + if (!state.pendingStopRunIds.has(runId)) return state; + const pendingStopRunIds = new Set(state.pendingStopRunIds); + pendingStopRunIds.delete(runId); + return { pendingStopRunIds }; + }), }), { name: PROJECT_SCRIPT_RUNS_STORAGE_KEY, From 3f5940e572f23b56424b492e0871f0c92eeacaa8 Mon Sep 17 00:00:00 2001 From: Farseen M Date: Mon, 16 Nov 2026 18:56:22 +0530 Subject: [PATCH 4/6] fix(web): harden project action launches Use a portable completion wrapper and claim pending launches before opening a terminal so duplicate clicks cannot start the same action twice. --- .../ProjectScriptRunsControl.tsx | 34 +++-- apps/web/src/hooks/useProjectScriptRuns.ts | 129 +++++++++++------- apps/web/src/projectScriptRuns.test.ts | 18 +++ apps/web/src/projectScriptRuns.ts | 8 ++ apps/web/src/projectScriptRunsStore.ts | 20 ++- 5 files changed, 149 insertions(+), 60 deletions(-) diff --git a/apps/web/src/components/projectScriptRuns/ProjectScriptRunsControl.tsx b/apps/web/src/components/projectScriptRuns/ProjectScriptRunsControl.tsx index beab04dd0b747..971e99129857d 100644 --- a/apps/web/src/components/projectScriptRuns/ProjectScriptRunsControl.tsx +++ b/apps/web/src/components/projectScriptRuns/ProjectScriptRunsControl.tsx @@ -1,7 +1,11 @@ import { HistoryIcon, PlayIcon } from "lucide-react"; import { useState } from "react"; -import { isProjectScriptRunActive, projectScriptRunStatusLabel } from "../../projectScriptRuns"; +import { + isProjectScriptRunActive, + projectScriptLaunchKey, + projectScriptRunStatusLabel, +} from "../../projectScriptRuns"; import { useProjectScriptMenuEntries, useProjectScriptRunActions, @@ -53,7 +57,8 @@ export function ProjectScriptRunsControl() { function ProjectScriptRunsMenu({ onClose }: { readonly onClose: () => void }) { const { entries, showEnvironmentLabel } = useProjectScriptMenuEntries(); - const { runsList, runScript, stopRun, selectRun } = useProjectScriptRunActions(); + const { runsList, pendingLaunchKeys, runScript, stopRun, selectRun } = + useProjectScriptRunActions(); if (entries.length === 0) { return ( @@ -85,6 +90,12 @@ function ProjectScriptRunsMenu({ onClose }: { readonly onClose: () => void }) { {entry.scripts.map((script) => { + const launchKey = projectScriptLaunchKey( + entry.project.environmentId, + entry.project.id, + script.id, + ); + const launchPending = pendingLaunchKeys.has(launchKey); const activeRun = runsList.find( (run) => run.environmentId === entry.project.environmentId && @@ -101,7 +112,10 @@ function ProjectScriptRunsMenu({ onClose }: { readonly onClose: () => void }) { !isProjectScriptRunActive(run), ) .sort((left, right) => right.startedAt - left.startedAt)[0]; - const canRun = entry.canOperate; + const canRun = entry.canOperate && !launchPending; + const displayStatus = launchPending + ? "starting" + : (activeRun?.status ?? latestRun?.status ?? null); return ( void }) { > {projectScriptMenuLabel(script)} - {activeRun !== undefined ? ( - {projectScriptRunStatusLabel(activeRun.status)} + {displayStatus !== null ? ( + {projectScriptRunStatusLabel(displayStatus)} ) : null} - {activeRun === undefined && latestRun !== undefined ? ( + {!launchPending && activeRun === undefined && latestRun !== undefined ? (