+ {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..1f3d252918a46
--- /dev/null
+++ b/apps/web/src/hooks/useProjectScriptRuns.ts
@@ -0,0 +1,346 @@
+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,
+ AuthTerminalReadScope,
+ 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_BEGIN_ENV,
+ PROJECT_SCRIPT_SENTINEL_ENV,
+ PROJECT_SCRIPT_SENTINEL_PREFIX,
+ projectActionsThreadId,
+ projectLastActivityTimestamp,
+ projectScriptBeginMarker,
+ projectScriptLaunchKey,
+ projectScriptStopRollbackPatch,
+ resolveProjectAnchorThread,
+ sortProjectScriptMenuEntries,
+ sortProjectScriptRuns,
+ projectScriptStoppedPatch,
+ 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 configs = useServerConfigs();
+ const operateScopes = useEnvironmentsWithScope(projects, AuthTerminalOperateScope);
+ const readScopes = useEnvironmentsWithScope(projects, AuthTerminalReadScope);
+ 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 beginStop = useProjectScriptRunsStore((state) => state.beginStop);
+ const endStop = useProjectScriptRunsStore((state) => state.endStop);
+ const pendingLaunchKeys = useProjectScriptRunsStore((state) => state.pendingLaunchKeys);
+ const beginLaunch = useProjectScriptRunsStore((state) => state.beginLaunch);
+ const endLaunch = useProjectScriptRunsStore((state) => state.endLaunch);
+
+ const runsList = sortProjectScriptRuns(Object.values(runs));
+ const selectedRun = selectedRunId === null ? null : (runs[selectedRunId] ?? null);
+ const canOperate = (environmentId: EnvironmentId) => 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,
+ ) ?? null;
+
+ const runScript = async (
+ project: EnvironmentProject,
+ script: ProjectScript,
+ anchorThread: EnvironmentThreadShell | null,
+ ) => {
+ if (!canOperate(project.environmentId) || !canRead(project.environmentId)) {
+ toastManager.add({
+ type: "error",
+ title: "Cannot run project actions",
+ description: "This connection needs terminal read and operate permissions.",
+ });
+ 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 launchKey = projectScriptLaunchKey(project.environmentId, project.id, script.id);
+ const alreadyActive = Object.values(useProjectScriptRunsStore.getState().runs).some(
+ (run) =>
+ run.environmentId === project.environmentId &&
+ run.projectId === project.id &&
+ run.scriptId === script.id &&
+ isProjectScriptRunActive(run),
+ );
+ if (alreadyActive) return;
+ if (!beginLaunch(launchKey)) 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 launch = async () => {
+ 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_BEGIN_ENV]: projectScriptBeginMarker(sentinel),
+ [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 wrappedCommand = wrapProjectScriptCommand(
+ script.command,
+ openResult.value.shell ?? null,
+ );
+ const writeResult = await writeTerminal({
+ environmentId: project.environmentId,
+ input: {
+ threadId,
+ terminalId,
+ data: projectScriptTerminalInput(wrappedCommand),
+ afterShellStartup: true,
+ },
+ });
+ 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,
+ });
+ }
+ };
+
+ try {
+ await launch();
+ } catch (error) {
+ endLaunch(launchKey);
+ throw error;
+ }
+ endLaunch(launchKey);
+ };
+
+ const stopRun = async (run: ProjectScriptRun) => {
+ 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 },
+ });
+ 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) => {
+ 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,
+ pendingLaunchKeys,
+ 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..f1dd9ad9243c9
--- /dev/null
+++ b/apps/web/src/projectScriptRuns.test.ts
@@ -0,0 +1,410 @@
+// @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, 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,
+ projectScriptLaunchKey,
+ projectScriptOutputTail,
+ projectScriptSentinelPattern,
+ projectScriptStopRollbackPatch,
+ projectScriptStoppedPatch,
+ projectScriptVisibleOutput,
+ 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("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(false);
+ expect(isProjectScriptWrapperLine("[~/project] sh -c 'pnpm test'")).toBe(false);
+ 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",
+ "command failed: sh -c 'pnpm test'",
+ `${sentinel}0`,
+ "[~/project]",
+ ].join("\r\n");
+
+ expect(projectScriptVisibleOutput(text, sentinel)).toBe(
+ "first line\nsecond line\ncommand failed: sh -c 'pnpm test'",
+ );
+ expect(projectScriptVisibleOutput("plain output", sentinel)).toBe("plain output");
+ });
+
+ 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",
+ ]);
+ });
+
+ 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("claims only one pending launch for a project action", () => {
+ const key = projectScriptLaunchKey(environmentId, projectId, "dev");
+ const store = useProjectScriptRunsStore.getState();
+
+ expect(store.beginLaunch(key)).toBe(true);
+ expect(useProjectScriptRunsStore.getState().beginLaunch(key)).toBe(false);
+
+ store.endLaunch(key);
+ expect(useProjectScriptRunsStore.getState().pendingLaunchKeys.has(key)).toBe(false);
+ expect(useProjectScriptRunsStore.getState().beginLaunch(key)).toBe(true);
+ useProjectScriptRunsStore.getState().endLaunch(key);
+ });
+
+ it("wraps headless actions in a shell-portable child shell", () => {
+ expect(wrapProjectScriptCommand("pnpm dev", "/usr/bin/fish")).toMatch(/^sh -c /);
+ });
+});
+
+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.each([
+ ["greet; [[ 1 == 1 ]]; exit 7", 7],
+ ["greet; printf x &&", 2],
+ ])("runs %s in the user's shell and reports exit %s", (command, exitCode) => {
+ const wrapped = wrapProjectScriptCommand(command, "/bin/bash");
+ 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",
+ },
+ );
+
+ if (exitCode === 7) expect(output).toContain("hello");
+ expect(output).toContain(`done:${exitCode}`);
+ });
+
+ it.each(["/usr/bin/fish", null])(
+ "runs quoted commands through the fallback shell (%s)",
+ (shell) => {
+ const output = NodeChildProcess.execFileSync(
+ "sh",
+ ["-c", wrapProjectScriptCommand("printf '%s' \"it's working\"", shell)],
+ {
+ 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
new file mode 100644
index 0000000000000..41db27c8272bc
--- /dev/null
+++ b/apps/web/src/projectScriptRuns.ts
@@ -0,0 +1,256 @@
+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_BEGIN_ENV = "__T3_SCRIPT_BEGIN";
+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;
+}
+
+export function projectScriptLaunchKey(
+ environmentId: EnvironmentId,
+ projectId: ProjectId,
+ scriptId: string,
+): string {
+ return `${environmentId}\u0000${projectId}\u0000${scriptId}`;
+}
+
+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 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":
+ 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,
+ );
+}
+
+/**
+ * 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, shell: string | null = null): 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}"`,
+ "(",
+ `eval '${body.replaceAll("'", "'\\''")}'`,
+ ")",
+ "__t3_status=$?",
+ `printf "\\n%s%s\\n" "$${PROJECT_SCRIPT_SENTINEL_ENV}" "$__t3_status"`,
+ ].join("\n");
+ const shellName = shell?.split(/[/\\]/).at(-1);
+ const executor =
+ shellName !== undefined && /^(?:ba|z|da|k|a)?sh$/.test(shellName) ? "eval" : "sh -c";
+ return `${executor} '${script.replaceAll("'", "'\\''")}'`;
+}
+
+export function projectScriptBeginMarker(sentinel: string): string {
+ return `${sentinel}BEGIN`;
+}
+
+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.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 {
+ 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..8225da7373bf2
--- /dev/null
+++ b/apps/web/src/projectScriptRunsStore.ts
@@ -0,0 +1,103 @@
+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 pendingStopRunIds: ReadonlySet;
+ readonly pendingLaunchKeys: 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;
+ readonly beginLaunch: (key: string) => boolean;
+ readonly endLaunch: (key: string) => void;
+}
+
+const PROJECT_SCRIPT_RUNS_STORAGE_KEY = "t3code:project-script-runs:v1";
+
+export const useProjectScriptRunsStore = create()(
+ persist(
+ (set, get) => ({
+ runs: {},
+ selectedRunId: null,
+ pendingStopRunIds: new Set(),
+ pendingLaunchKeys: new Set(),
+ 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 }),
+ 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 };
+ }),
+ beginLaunch: (key) => {
+ if (get().pendingLaunchKeys.has(key)) return false;
+ const pendingLaunchKeys = new Set(get().pendingLaunchKeys);
+ pendingLaunchKeys.add(key);
+ set({ pendingLaunchKeys });
+ return true;
+ },
+ endLaunch: (key) =>
+ set((state) => {
+ if (!state.pendingLaunchKeys.has(key)) return state;
+ const pendingLaunchKeys = new Set(state.pendingLaunchKeys);
+ pendingLaunchKeys.delete(key);
+ return { pendingLaunchKeys };
+ }),
+ }),
+ {
+ name: PROJECT_SCRIPT_RUNS_STORAGE_KEY,
+ version: 1,
+ storage: createJSONStorage(() =>
+ resolveStorage(typeof window !== "undefined" ? window.sessionStorage : undefined),
+ ),
+ partialize: (state) => ({ runs: state.runs }),
+ },
+ ),
+);
diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts
index 48ba0d643c822..cf5a4e47f0068 100644
--- a/packages/contracts/src/terminal.ts
+++ b/packages/contracts/src/terminal.ts
@@ -131,6 +131,7 @@ export const TerminalSessionSnapshot = Schema.Struct({
exitCode: Schema.NullOr(Schema.Int),
exitSignal: Schema.NullOr(Schema.Int),
label: Schema.String.check(Schema.isMaxLength(128)),
+ shell: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)),
updatedAt: Schema.String,
sequence: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
// The PTY grid every renderer of this terminal should draw; absent from older servers.