TypeScript
feat(server): run a project action when a worktree thread settles (#16290)
Theo Browne079e4bccdcff
diff --git a/apps/mobile/src/features/terminal/terminalMenu.ts b/apps/mobile/src/features/terminal/terminalMenu.tsindex 47f3d08144a..1adec0d0397 100644--- a/apps/mobile/src/features/terminal/terminalMenu.ts+++ b/apps/mobile/src/features/terminal/terminalMenu.ts@@ -156,10 +156,6 @@ export function resolveProjectScriptTerminalId(input: {return nextTerminalId(input.existingTerminalIds, input.uniqueSuffix);}-export function projectScriptMenuLabel(script: ProjectScript): string {- return script.runOnWorktreeCreate ? `${script.name} (setup)` : script.name;-}-export function projectScriptMenuIcon(icon: ProjectScript["icon"]) {if (icon === "test") return "flask";if (icon === "lint") return "checklist";diff --git a/apps/mobile/src/features/threads/ThreadGitControls.tsx b/apps/mobile/src/features/threads/ThreadGitControls.tsxindex 737a6906b42..257fe6272de 100644--- a/apps/mobile/src/features/threads/ThreadGitControls.tsx+++ b/apps/mobile/src/features/threads/ThreadGitControls.tsx@@ -23,9 +23,9 @@ import {basename,getTerminalStatusLabel,projectScriptMenuIcon,- projectScriptMenuLabel,type TerminalMenuSession,} from "../terminal/terminalMenu";+import { projectScriptMenuLabel } from "@t3tools/shared/projectScripts";function truncateMiddle(value: string, maxLength: number): string {if (value.length <= maxLength) {diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.tsindex a7dd2a89c0b..6bc54e94e73 100644--- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts+++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts@@ -30,6 +30,7 @@ import * as Stream from "effect/Stream";import { TestClock } from "effect/testing";import * as GitManager from "../git/GitManager.ts";+import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";import * as PullRequestService from "../pullRequest/PullRequestService.ts";import * as ServerActivation from "../serverActivation.ts";import * as ServerSettings from "../serverSettings.ts";@@ -486,6 +487,12 @@ interface HarnessOptions {readonly pullRequestSummary?: PullRequestService.PullRequestService["Service"]["summary"];readonly existingWorktreePaths?: ReadonlyArray<string>;readonly onDispatch?: (command: AutoSettleCommand) => Effect.Effect<void>;+ /** Runs before each settle script start; a failure fails that start. */+ readonly onScriptRun?: (+ input: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput,+ ) => Effect.Effect<void>;+ /** Runs inside each `closeIdle` call. */+ readonly onCloseIdle?: () => Effect.Effect<void>;/** Threads `getThread` returns when a `thread.settled` event is handled. */readonly currentThreads?: ReadonlyArray<OrchestrationV2AppThread>;}@@ -514,6 +521,8 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:const invalidatedCwds = yield* Ref.make<ReadonlyArray<string>>([]);const domainEvents = yield* PubSub.unbounded<OrchestrationV2DomainEvent>();const closedIdle = yield* Queue.unbounded<{ readonly threadId: string }>();+ const scriptRuns =+ yield* Queue.unbounded<ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput>();const updateSettings = (patch: ServerSettingsPatch) =>Effect.gen(function* () {@@ -599,7 +608,15 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:dispatch,}),Layer.mock(TerminalManager.TerminalManager)({- closeIdle: (input) => Queue.offer(closedIdle, input).pipe(Effect.asVoid),+ closeIdle: (input) =>+ Queue.offer(closedIdle, input).pipe(Effect.andThen(options.onCloseIdle?.() ?? Effect.void)),+ }),+ Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({+ runForThread: (input) =>+ Queue.offer(scriptRuns, input).pipe(+ Effect.andThen(options.onScriptRun?.(input) ?? Effect.void),+ Effect.as({ status: "no-script" } as const),+ ),}),Layer.mock(GitManager.GitManager)({branchPullRequest,@@ -631,6 +648,7 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:summaryRecovery,invalidatedCwds,closedIdle,+ scriptRuns,publishEvent: (event: OrchestrationV2DomainEvent) => PubSub.publish(domainEvents, event),updateSettings,publishMerge: PubSub.publish(mergedPullRequests, {@@ -1010,6 +1028,7 @@ describe("ThreadSettlementServiceV2 terminals", () => {const appThread = (id: string,settledOverride: OrchestrationV2AppThread["settledOverride"],+ worktreePath: string | null = null,): OrchestrationV2AppThread => {const threadId = ThreadId.make(id);return {@@ -1023,7 +1042,7 @@ describe("ThreadSettlementServiceV2 terminals", () => {runtimeMode: "full-access",interactionMode: "default",branch: null,- worktreePath: null,+ worktreePath,activeProviderThreadId: null,lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },forkedFrom: null,@@ -1086,6 +1105,117 @@ describe("ThreadSettlementServiceV2 terminals", () => {}),),);++ it.effect("runs the settle script in the thread's own worktree", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const shared = appThread("shared-checkout-thread", "settled");+ const missing = appThread("removed-worktree-thread", "settled", "/worktrees/removed");+ const worktree = appThread("worktree-thread", "settled", "/worktrees/thread");+ const fixture = yield* makeHarness({+ snapshot: makeSnapshot([]),+ currentThreads: [shared, missing, worktree],+ existingWorktreePaths: ["/worktrees/thread"],+ });++ yield* Effect.gen(function* () {+ const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;+ yield* startHarness(service, fixture.activation, fixture.snapshotReads);+ // Events run in order, so the first run belongs to the last event+ // only if the shared checkout and the removed worktree were skipped.+ yield* fixture.publishEvent(settledEvent(shared));+ yield* fixture.publishEvent(settledEvent(missing));+ yield* fixture.publishEvent(settledEvent(worktree));+ const run = yield* Queue.take(fixture.scriptRuns);+ assert.strictEqual(run.threadId, worktree.id);+ assert.strictEqual(run.worktreePath, "/worktrees/thread");+ assert.strictEqual(run.trigger, "settle");+ }).pipe(Effect.provide(fixture.layer));+ }),+ ),+ );++ it.effect("skips the settle script for a thread re-engaged while its shells close", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const settled = appThread("reengaging-thread", "settled", "/worktrees/reengaging");+ const marker = appThread("marker-thread", "settled", "/worktrees/marker");+ const currentThreads = [settled, marker];+ const fixture = yield* makeHarness({+ snapshot: makeSnapshot([]),+ currentThreads,+ existingWorktreePaths: ["/worktrees/reengaging", "/worktrees/marker"],+ // The user sends a message while the first close checks processes.+ onCloseIdle: () =>+ Effect.sync(() => {+ currentThreads[0] = { ...settled, settledOverride: "active" };+ }),+ });++ yield* Effect.gen(function* () {+ const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;+ yield* startHarness(service, fixture.activation, fixture.snapshotReads);+ yield* fixture.publishEvent(settledEvent(settled));+ yield* fixture.publishEvent(settledEvent(marker));+ assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, marker.id);+ }).pipe(Effect.provide(fixture.layer));+ }),+ ),+ );++ it.effect("runs the settle script once when a settlement is re-emitted", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const repeated = appThread("repeated-thread", "settled", "/worktrees/repeated");+ const marker = appThread("marker-thread", "settled", "/worktrees/marker");+ const fixture = yield* makeHarness({+ snapshot: makeSnapshot([]),+ currentThreads: [repeated, marker],+ existingWorktreePaths: ["/worktrees/repeated", "/worktrees/marker"],+ });++ yield* Effect.gen(function* () {+ const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;+ yield* startHarness(service, fixture.activation, fixture.snapshotReads);+ // Settling an already settled thread emits the same settlement again.+ yield* fixture.publishEvent(settledEvent(repeated));+ yield* fixture.publishEvent(settledEvent(repeated));+ yield* fixture.publishEvent(settledEvent(marker));+ assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, repeated.id);+ assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, marker.id);+ }).pipe(Effect.provide(fixture.layer));+ }),+ ),+ );++ it.effect("retries the settle script on a re-emitted settlement after a failed start", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = appThread("failed-start-thread", "settled", "/worktrees/failed-start");+ const starts = yield* Ref.make(0);+ const fixture = yield* makeHarness({+ snapshot: makeSnapshot([]),+ currentThreads: [thread],+ existingWorktreePaths: ["/worktrees/failed-start"],+ onScriptRun: () =>+ Ref.updateAndGet(starts, (count) => count + 1).pipe(+ Effect.flatMap((count) =>+ count === 1 ? Effect.die(new Error("terminal failed to open")) : Effect.void,+ ),+ ),+ });++ yield* Effect.gen(function* () {+ const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;+ yield* startHarness(service, fixture.activation, fixture.snapshotReads);+ yield* fixture.publishEvent(settledEvent(thread));+ yield* fixture.publishEvent(settledEvent(thread));+ assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, thread.id);+ assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, thread.id);+ }).pipe(Effect.provide(fixture.layer));+ }),+ ),+ );});describe("ThreadSettlementServiceV2 single-thread sweeps", () => {diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.tsindex 7c64ce02804..620e1e498d7 100644--- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts+++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts@@ -20,6 +20,7 @@ import type * as Scope from "effect/Scope";import * as Stream from "effect/Stream";import * as GitManager from "../git/GitManager.ts";+import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";import * as PullRequestService from "../pullRequest/PullRequestService.ts";import * as ServerSettings from "../serverSettings.ts";import { forkParked } from "../serverActivation.ts";@@ -265,6 +266,10 @@ export const make = Effect.gen(function* () {const crypto = yield* Crypto.Crypto;const fileSystem = yield* FileSystem.FileSystem;const terminals = yield* TerminalManager.TerminalManager;+ const projectScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;+ // Settling a settled thread re-emits thread.settled with the same settledAt,+ // so this keeps the settle action to one run per settlement.+ const settleActionRunAt = new Map<ThreadId, number>();const sweep = Effect.fn("ThreadSettlementServiceV2.sweep")(function* (mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,@@ -514,20 +519,43 @@ export const make = Effect.gen(function* () {// Settling closes the thread's shells that sit at an idle prompt, so they stop// holding the worktree. A terminal running a command (a dev server, an- // editor) stays for the user to close.- const closeIdleTerminals = Effect.fn("ThreadSettlementServiceV2.closeIdleTerminals")(+ // editor) stays for the user to close. Then the project's settle script runs+ // in the thread's own worktree; a thread in the shared checkout skips it,+ // because other threads may still be working there.+ const cleanUpSettledThread = Effect.fn("ThreadSettlementServiceV2.cleanUpSettledThread")(function* (threadId: ThreadId) {// A thread re-engaged before this event ran keeps its shells.+ const settled = yield* projections.getThread(threadId);+ if (settled.settledOverride !== "settled") return;+ yield* terminals.closeIdle({ threadId });+ const worktreePath = settled.worktreePath;+ if (worktreePath === null || !(yield* fileSystem.exists(worktreePath))) return;+ // Closing and the worktree check wait on I/O. A thread re-engaged+ // meanwhile is working again, so its worktree is no place for cleanup.const thread = yield* projections.getThread(threadId);if (thread.settledOverride !== "settled") return;- yield* terminals.closeIdle({ threadId });+ const settledAtMs = toMillis(thread.settledAt);+ if (settledAtMs === null || settleActionRunAt.get(threadId) === settledAtMs) return;+ const run = yield* projectScripts.runForThread({+ threadId,+ projectId: thread.projectId,+ worktreePath,+ trigger: "settle",+ // A clean exit closes the script's shell so it does not hold the worktree.+ observeCompletion: {},+ });+ // Recorded after a successful start, so a failed start retries on the next event.+ settleActionRunAt.set(threadId, settledAtMs);+ if (run.status === "started" && run.completion) {+ yield* run.completion.pipe(Effect.forkDetach);+ }},(effect, threadId) =>effect.pipe(Effect.catchCause((cause) =>Cause.hasInterruptsOnly(cause)? Effect.failCause(cause)- : Effect.logWarning("closing idle terminals after settlement failed", {+ : Effect.logWarning("cleaning up a settled thread failed", {threadId,cause: Cause.pretty(cause),}),@@ -538,7 +566,7 @@ export const make = Effect.gen(function* () {const processEvent = (event: OrchestrationV2DomainEvent) => {switch (event.type) {case "thread.settled":- return closeIdleTerminals(event.threadId);+ return cleanUpSettledThread(event.threadId);case "thread.pull-request-synced":case "provider-session.detached":return worker.enqueue(event.threadId);diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.tsindex 01976a17359..a11fb1f42d1 100644--- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts+++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts@@ -2,6 +2,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto";import { assert, it, vi } from "@effect/vitest";import { ProjectId } from "@t3tools/contracts";import * as Effect from "effect/Effect";+import * as Fiber from "effect/Fiber";import * as Layer from "effect/Layer";import * as Option from "effect/Option";@@ -29,6 +30,9 @@ it.effect("resolves setup scripts through the standalone project service", () =>const write = vi.fn((_input: Parameters<TerminalManager.TerminalManager["Service"]["write"]>[0]) => Effect.void,);+ const closeIdle = vi.fn(+ (_input: Parameters<TerminalManager.TerminalManager["Service"]["closeIdle"]>[0]) => Effect.void,+ );const listeners: Array<Parameters<TerminalManager.TerminalManager["Service"]["subscribe"]>[0]> =[];const subscribe: TerminalManager.TerminalManager["Service"]["subscribe"] = (listener) =>@@ -52,6 +56,14 @@ it.effect("resolves setup scripts through the standalone project service", () =>icon: "configure" as const,runOnWorktreeCreate: true,},+ {+ id: "clean",+ name: "Clean",+ command: "cargo clean",+ icon: "build" as const,+ runOnWorktreeCreate: false,+ runOnSettle: true,+ },],createdAt: "2026-06-20T00:00:00.000Z",updatedAt: "2026-06-20T00:00:00.000Z",@@ -63,7 +75,7 @@ it.effect("resolves setup scripts through the standalone project service", () =>Layer.mock(ProjectService.ProjectService)({getById: () => Effect.succeed(Option.some(project)),}),- Layer.mock(TerminalManager.TerminalManager)({ open, write, subscribe }),+ Layer.mock(TerminalManager.TerminalManager)({ open, write, subscribe, closeIdle }),ServerSettings.layerTest(),NodeCrypto.layer,),@@ -117,5 +129,54 @@ it.effect("resolves setup scripts through the standalone project service", () =>});assert.deepEqual(lines, ["Downloading 10%", "Downloading 20%", "Done"]);yield* listener({ type: "closed", threadId: "thread-1", terminalId: "setup-setup" });++ const settle = yield* runner.runForThread({+ threadId: "thread-1",+ projectId,+ worktreePath: "/repo-worktree",+ trigger: "settle",+ });+ const settleTerminalId = settle.status === "started" ? settle.terminalId : "";+ assert.match(settleTerminalId, /^settle-clean-/);+ assert.equal(write.mock.calls.at(-1)?.[0].data, "cargo clean\r");++ // A clean run closes its shell once the prompt is back, not at the+ // sentinel, so the prompt redraw is not taken for new activity.+ const observedSettle = yield* runner.runForThread({+ threadId: "thread-1",+ projectId,+ worktreePath: "/repo-worktree",+ trigger: "settle",+ observeCompletion: {},+ });+ const observedTerminalId = observedSettle.status === "started" ? observedSettle.terminalId : "";+ // Each settle gets its own shell, so a busy one is never typed into.+ assert.notEqual(observedTerminalId, settleTerminalId);+ const token = /__T3_SETUP_DONE___(\w+):/.exec(write.mock.calls.at(-1)?.[0].data ?? "")?.[1];+ const settleListener = listeners.at(-1)!;+ const completion = yield* Effect.forkChild(+ observedSettle.status === "started" && observedSettle.completion+ ? observedSettle.completion+ : Effect.die("no completion"),+ );+ yield* settleListener({+ type: "output",+ threadId: "thread-1",+ terminalId: observedTerminalId,+ data: `\r\n__T3_SETUP_DONE___${token}:0\r\n`,+ });+ yield* Effect.yieldNow;+ assert.equal(closeIdle.mock.calls.length, 0);+ yield* settleListener({+ type: "output",+ threadId: "thread-1",+ terminalId: observedTerminalId,+ data: "$ ",+ });+ assert.deepEqual((yield* Fiber.join(completion)).exitCode, 0);+ assert.deepEqual(closeIdle.mock.calls[0]?.[0], {+ threadId: "thread-1",+ terminalId: observedTerminalId,+ });}).pipe(Effect.provide(layer));});diff --git a/apps/server/src/project/ProjectSetupScriptRunner.ts b/apps/server/src/project/ProjectSetupScriptRunner.tsindex 7b101226d5d..97361715627 100644--- a/apps/server/src/project/ProjectSetupScriptRunner.ts+++ b/apps/server/src/project/ProjectSetupScriptRunner.ts@@ -3,6 +3,7 @@ import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hosimport {projectScriptRuntimeEnv,resolveProjectScripts,+ settleProjectScript,setupProjectScript,} from "@t3tools/shared/projectScripts";@@ -60,6 +61,8 @@ export interface ProjectSetupScriptRunnerInput {readonly projectCwd?: string;readonly worktreePath: string;readonly preferredTerminalId?: string;+ /** Which project script to run. Defaults to the worktree setup script. */+ readonly trigger?: "setup" | "settle";readonly project?: {readonly id: ProjectId;readonly workspaceRoot: string;@@ -225,6 +228,9 @@ export const make = Effect.gen(function* () {Effect.gen(function* () {const startedAtMs = yield* Clock.currentTimeMillis;const done = yield* Deferred.make<ProjectSetupScriptCompletion>();+ // The shell redraws its prompt just after the sentinel. Closing before+ // that would read the redraw as new activity and keep an idle shell.+ const promptReturned = yield* Deferred.make<void>();let lineBuffer = "";let settled = false;@@ -278,15 +284,26 @@ export const make = Effect.gen(function* () {if (lineBuffer.length > PARTIAL_LINE_MAX_LENGTH) {lineBuffer = lineBuffer.slice(-PARTIAL_LINE_MAX_LENGTH);}- return Effect.forEach(lines, handleLine, { discard: true });+ return Effect.forEach(lines, handleLine, { discard: true }).pipe(+ // A prompt has no newline, so it is what remains once the sentinel is in.+ Effect.andThen(+ Effect.suspend(() =>+ settled && lineBuffer.length > 0+ ? Deferred.succeed(promptReturned, undefined).pipe(Effect.asVoid)+ : Effect.void,+ ),+ ),+ );}if (event.type === "exited" || event.type === "closed") {- return settle(null);+ return settle(null).pipe(Effect.andThen(Deferred.succeed(promptReturned, undefined)));}return Effect.void;});const completion = Deferred.await(done).pipe(+ // A shell with an empty prompt never prints one; do not wait forever.+ Effect.tap(() => Deferred.await(promptReturned).pipe(Effect.timeoutOption("1 second"))),Effect.ensuring(Effect.sync(() => unsubscribe())),);return { completion, unsubscribe };@@ -348,14 +365,23 @@ export const make = Effect.gen(function* () {}),),);- const script = setupProjectScript(resolveProjectScripts(settings, project));+ const trigger = input.trigger ?? "setup";+ const scripts = resolveProjectScripts(settings, project);+ const script =+ trigger === "settle" ? settleProjectScript(scripts) : setupProjectScript(scripts);if (!script) {return {status: "no-script",} as const;}- const terminalId = input.preferredTerminalId ?? `setup-${script.id}`;+ // A thread settles again after it is resumed, and an earlier settle shell+ // may still be busy; typing into it would feed its foreground program.+ const terminalId =+ input.preferredTerminalId ??+ (trigger === "settle"+ ? `settle-${script.id}-${(yield* crypto.randomUUIDv4.pipe(Effect.orDie)).slice(0, 8)}`+ : `setup-${script.id}`);const cwd = input.worktreePath;const env = {...projectScriptRuntimeEnv({diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 7fdc5e98a47..e6e1c792331 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -320,6 +320,7 @@ import {commandForProjectScript,nextProjectScriptId,projectScriptIdFromCommand,+ releaseClaimedRoles,} from "~/projectScripts";import { newDraftId, newMessageId, newThreadId } from "~/lib/utils";import { registerFaviconProjectForThread } from "~/browserFaviconStore";@@ -5231,14 +5232,10 @@ export default function ChatView(props: ChatViewProps) {activeProjectScripts.map((script) => script.id),);const nextScript = buildProjectScript(nextId, input);- const nextScripts = input.runOnWorktreeCreate- ? [- ...activeProjectScripts.map((script) =>- script.runOnWorktreeCreate ? { ...script, runOnWorktreeCreate: false } : script,- ),- nextScript,- ]- : [...activeProjectScripts, nextScript];+ const nextScripts = [+ ...activeProjectScripts.map((script) => releaseClaimedRoles(script, input)),+ nextScript,+ ];return persistProjectScripts({projectId: activeProject.id,@@ -5266,11 +5263,7 @@ export default function ChatView(props: ChatViewProps) {const updatedScript = buildProjectScript(existingScript.id, input);const nextScripts = activeProjectScripts.map((script) =>- script.id === scriptId- ? updatedScript- : input.runOnWorktreeCreate- ? { ...script, runOnWorktreeCreate: false }- : script,+ script.id === scriptId ? updatedScript : releaseClaimedRoles(script, input),);return persistProjectScripts({diff --git a/apps/web/src/components/ProjectScriptsControl.tsx b/apps/web/src/components/ProjectScriptsControl.tsxindex c51be069434..5bea0b46cd1 100644--- a/apps/web/src/components/ProjectScriptsControl.tsx+++ b/apps/web/src/components/ProjectScriptsControl.tsx@@ -12,6 +12,7 @@ import {isAtomCommandInterrupted,squashAtomCommandFailure,} from "@t3tools/client-runtime/state/runtime";+import { projectScriptMenuLabel } from "@t3tools/shared/projectScripts";import { ChevronDownIcon, DownloadIcon, PlusIcon, SettingsIcon, WrenchIcon } from "lucide-react";import React, { useCallback, useMemo, useState } from "react";@@ -147,6 +148,7 @@ export default function ProjectScriptsControl({icon: fileScript.icon ?? "play",runOnWorktreeCreate: fileScript.runOnWorktreeCreate ?? false,waitForSetup: fileScript.runOnWorktreeCreate === true && fileScript.async === false,+ runOnSettle: fileScript.runOnSettle ?? false,...(readEnvironmentScope(environmentId, AuthSettingsWriteScope) ? { keybinding: null } : {}),previewUrl: fileScript.previewUrl ?? null,autoOpenPreview: fileScript.previewUrl ? (fileScript.autoOpenPreview ?? false) : false,@@ -166,7 +168,7 @@ export default function ProjectScriptsControl({const importMenuItems = importableScripts.length > 0 && (<>- {primaryScript && <MenuSeparator />}+ {scripts.length > 0 && <MenuSeparator />}<MenuGroup><MenuGroupLabel>From t3.json</MenuGroupLabel>{importableScripts.map((fileScript) => (@@ -202,9 +204,7 @@ export default function ProjectScriptsControl({onClick={() => onRunScript?.(script)}><ScriptIcon icon={script.icon} className="size-4" />- <MenuItemLabel>- {script.runOnWorktreeCreate ? `${script.name} (setup)` : script.name}- </MenuItemLabel>+ <MenuItemLabel>{projectScriptMenuLabel(script)}</MenuItemLabel><span className="relative ms-auto flex h-6 min-w-6 items-center justify-end">{shortcutLabel &&(presentation === "menu" ? (@@ -266,7 +266,7 @@ export default function ProjectScriptsControl({</MenuShortcut></MenuItem>)}- {primaryScript || importableScripts.length > 0 ? (+ {scripts.length > 0 || importableScripts.length > 0 ? (<MenuSubopen={actionsMenuOpen.scripts}onOpenChange={(open) =>@@ -369,7 +369,9 @@ export default function ProjectScriptsControl({</MenuPopup></Menu></ActionGroup>- ) : importableScripts.length > 0 ? (+ ) : scripts.length > 0 || importableScripts.length > 0 ? (+ // No one-click action (only a settle action, or only t3.json imports),+ // so the saved actions stay reachable through this menu.isPanel ? (<divrole="group"@@ -408,11 +410,7 @@ export default function ProjectScriptsControl({<ChevronDownIcon className={THREAD_DETAILS_PANEL_CHEVRON_CLASS} /></MenuTrigger><MenuPopup align="end" anchor={panelAnchorRef} className="w-(--anchor-width)">- {importMenuItems}- <MenuItem onClick={openAddDialog}>- <PlusIcon className="size-4" />- Add action- </MenuItem>+ {scriptItems}</MenuPopup></Menu></div>@@ -433,13 +431,7 @@ export default function ProjectScriptsControl({</span><ChevronDownIcon className="size-3.5" /></MenuTrigger>- <MenuPopup align="end">- {importMenuItems}- <MenuItem onClick={openAddDialog}>- <PlusIcon className="size-4" />- Add action- </MenuItem>- </MenuPopup>+ <MenuPopup align="end">{scriptItems}</MenuPopup></Menu>)) : (diff --git a/apps/web/src/components/projectScriptEditor.permissions.test.tsx b/apps/web/src/components/projectScriptEditor.permissions.test.tsxindex eccdb0cf834..42d6bc35172 100644--- a/apps/web/src/components/projectScriptEditor.permissions.test.tsx+++ b/apps/web/src/components/projectScriptEditor.permissions.test.tsx@@ -64,6 +64,7 @@ const request: ProjectScriptEditorRequest = {icon: "test",runOnWorktreeCreate: false,waitForSetup: false,+ runOnSettle: false,keybinding: "mod+k",previewUrl: null,autoOpenPreview: false,diff --git a/apps/web/src/components/projectScriptEditor.tsx b/apps/web/src/components/projectScriptEditor.tsxindex a8a7e5e900e..19a246cf4be 100644--- a/apps/web/src/components/projectScriptEditor.tsx+++ b/apps/web/src/components/projectScriptEditor.tsx@@ -92,6 +92,7 @@ export interface NewProjectScriptInput {runOnWorktreeCreate: boolean;/** Setup scripts only: hold the agent until the script exits. */waitForSetup: boolean;+ runOnSettle: boolean;/** Omit to preserve the current shortcut when the form did not edit it. */keybinding?: string | null;/** Optional URL to open in the in-app preview when this script runs. */@@ -108,6 +109,7 @@ export const EMPTY_PROJECT_SCRIPT_INPUT: NewProjectScriptInput = {icon: "play",runOnWorktreeCreate: false,waitForSetup: false,+ runOnSettle: false,keybinding: null,previewUrl: null,autoOpenPreview: false,@@ -133,6 +135,7 @@ export function editorRequestForScript(icon: script.icon,runOnWorktreeCreate: script.runOnWorktreeCreate,waitForSetup: script.runOnWorktreeCreate && script.async === false,+ runOnSettle: script.runOnSettle ?? false,keybinding: keybindingValueForCommand(keybindings, commandForProjectScript(script.id)),previewUrl: script.previewUrl ?? null,autoOpenPreview: script.autoOpenPreview ?? false,@@ -175,6 +178,7 @@ export function ProjectScriptEditorDialog({const [iconPickerOpen, setIconPickerOpen] = useComposerMenuState(!canEditActions);const [runOnWorktreeCreate, setRunOnWorktreeCreate] = useState(false);const [waitForSetup, setWaitForSetup] = useState(false);+ const [runOnSettle, setRunOnSettle] = useState(false);const [keybinding, setKeybinding] = useState("");const [previewUrl, setPreviewUrl] = useState("");const [autoOpenPreview, setAutoOpenPreview] = useState(false);@@ -206,6 +210,7 @@ export function ProjectScriptEditorDialog({setIconPickerOpen(false);setRunOnWorktreeCreate(request.initial.runOnWorktreeCreate);setWaitForSetup(request.initial.waitForSetup);+ setRunOnSettle(request.initial.runOnSettle);setKeybinding(request.initial.keybinding ?? "");setPreviewUrl(request.initial.previewUrl ?? "");setAutoOpenPreview(request.initial.autoOpenPreview);@@ -279,6 +284,7 @@ export function ProjectScriptEditorDialog({icon,runOnWorktreeCreate,waitForSetup: runOnWorktreeCreate && waitForSetup,+ runOnSettle,...((request.scriptId === null && canChangeKeybinding) || changesKeybinding? { keybinding: keybindingRule?.key ?? null }: {}),@@ -443,6 +449,13 @@ export function ProjectScriptEditorDialog({onCheckedChange={(checked) => setWaitForSetup(Boolean(checked))}/></label>+ <label className="flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm dark:border-transparent dark:bg-white/[0.035]">+ <span>Run in the thread's worktree when the thread settles</span>+ <Switch+ checked={runOnSettle}+ onCheckedChange={(checked) => setRunOnSettle(Boolean(checked))}+ />+ </label><labelclassName={`flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm dark:border-transparent dark:bg-white/[0.035] ${previewUrl.trim().length === 0 ? "opacity-60" : ""diff --git a/apps/web/src/components/settings/ProjectActionsList.tsx b/apps/web/src/components/settings/ProjectActionsList.tsxindex e28cafc4e78..cc19de17746 100644--- a/apps/web/src/components/settings/ProjectActionsList.tsx+++ b/apps/web/src/components/settings/ProjectActionsList.tsx@@ -38,6 +38,11 @@ export function ProjectActionsList({setup</span>) : null}+ {script.runOnSettle ? (+ <span className="shrink-0 rounded-sm border border-border/60 px-1.5 py-px text-2xs font-normal text-muted-foreground">+ on settle+ </span>+ ) : null}{script.previewUrl ? (<span className="shrink-0 rounded-sm border border-border/60 px-1.5 py-px text-2xs font-normal text-muted-foreground max-sm:hidden">preview · desktop onlydiff --git a/apps/web/src/components/settings/ProjectActionsSettings.tsx b/apps/web/src/components/settings/ProjectActionsSettings.tsxindex 1392da91607..dcd8b0f7533 100644--- a/apps/web/src/components/settings/ProjectActionsSettings.tsx+++ b/apps/web/src/components/settings/ProjectActionsSettings.tsx@@ -115,6 +115,7 @@ export function ProjectActionsSettings() {icon: fileScript.icon ?? "play",runOnWorktreeCreate: fileScript.runOnWorktreeCreate ?? false,waitForSetup: fileScript.runOnWorktreeCreate === true && fileScript.async === false,+ runOnSettle: fileScript.runOnSettle ?? false,keybinding: null,previewUrl: fileScript.previewUrl ?? null,autoOpenPreview: fileScript.previewUrl ? (fileScript.autoOpenPreview ?? false) : false,diff --git a/apps/web/src/components/settings/useProjectScriptSettings.ts b/apps/web/src/components/settings/useProjectScriptSettings.tsindex ee10913dc14..16be0901bd9 100644--- a/apps/web/src/components/settings/useProjectScriptSettings.ts+++ b/apps/web/src/components/settings/useProjectScriptSettings.ts@@ -28,6 +28,7 @@ import {buildProjectScript,commandForProjectScript,nextProjectScriptId,+ releaseClaimedRoles,} from "../../projectScripts";import { useProjects } from "../../state/entities";import { serverEnvironment } from "../../state/server";@@ -194,11 +195,7 @@ export function useProjectScriptSettings(return persist((current) => {const updated = current.map((script) =>- script.id === id- ? next- : input.runOnWorktreeCreate- ? { ...script, runOnWorktreeCreate: false }- : script,+ script.id === id ? next : releaseClaimedRoles(script, input),);return scriptId === null ? [...updated, next] : updated;},diff --git a/apps/web/src/projectScripts.test.ts b/apps/web/src/projectScripts.test.tsindex a1ed2afb989..d03c97d878e 100644--- a/apps/web/src/projectScripts.test.ts+++ b/apps/web/src/projectScripts.test.ts@@ -4,6 +4,8 @@ import { describe, expect, it } from "vite-plus/test";import {projectScriptCwd,projectScriptRuntimeEnv,+ projectScriptMenuLabel,+ settleProjectScript,setupProjectScript,} from "@t3tools/shared/projectScripts";@@ -13,6 +15,7 @@ import {nextProjectScriptId,primaryProjectScript,projectScriptIdFromCommand,+ releaseClaimedRoles,} from "./projectScripts";describe("projectScripts helpers", () => {@@ -24,6 +27,7 @@ describe("projectScripts helpers", () => {icon: "debug",runOnWorktreeCreate: false,waitForSetup: false,+ runOnSettle: false,previewUrl: "http://localhost:5733",autoOpenPreview: true,}),@@ -46,6 +50,7 @@ describe("projectScripts helpers", () => {icon: "test",runOnWorktreeCreate: false,waitForSetup: false,+ runOnSettle: false,previewUrl: null,autoOpenPreview: false,}),@@ -65,6 +70,7 @@ describe("projectScripts helpers", () => {icon: "configure",previewUrl: null,autoOpenPreview: false,+ runOnSettle: false,} as const;expect(buildProjectScript("setup", { ...input, runOnWorktreeCreate: true, waitForSetup: true }),@@ -108,7 +114,7 @@ describe("projectScripts helpers", () => {expect(nextProjectScriptId("!!!", [])).toBe("script");});- it("resolves primary and setup scripts", () => {+ it("resolves primary, setup, and settle scripts", () => {const scripts = [{id: "setup",@@ -117,6 +123,14 @@ describe("projectScripts helpers", () => {icon: "configure" as const,runOnWorktreeCreate: true,},+ {+ id: "clean",+ name: "Clean",+ command: "cargo clean",+ icon: "build" as const,+ runOnWorktreeCreate: false,+ runOnSettle: true,+ },{id: "test",name: "Test",@@ -128,6 +142,53 @@ describe("projectScripts helpers", () => {expect(primaryProjectScript(scripts)?.id).toBe("test");expect(setupProjectScript(scripts)?.id).toBe("setup");+ expect(settleProjectScript(scripts)?.id).toBe("clean");+ // Cleanup is never the one-click run button, even when it is all there is.+ expect(primaryProjectScript(scripts.filter((script) => script.id === "clean"))).toBeNull();+ });++ it("labels every lifecycle role a script runs in", () => {+ const script = {+ id: "both",+ name: "Both",+ command: "true",+ icon: "play" as const,+ runOnWorktreeCreate: true,+ };+ expect(projectScriptMenuLabel(script)).toBe("Both (setup)");+ expect(projectScriptMenuLabel({ ...script, runOnSettle: true })).toBe(+ "Both (setup, on settle)",+ );+ expect(projectScriptMenuLabel({ ...script, runOnWorktreeCreate: false })).toBe("Both");+ });++ it("moves the setup and settle roles to the script that claims them", () => {+ const input = {+ name: "Next",+ command: "true",+ icon: "play",+ waitForSetup: false,+ previewUrl: null,+ autoOpenPreview: false,+ } as const;+ const holder = {+ id: "holder",+ name: "Holder",+ command: "true",+ icon: "play" as const,+ runOnWorktreeCreate: true,+ runOnSettle: true,+ };++ expect(+ releaseClaimedRoles(holder, { ...input, runOnWorktreeCreate: false, runOnSettle: true }),+ ).toMatchObject({ runOnWorktreeCreate: true, runOnSettle: false });+ expect(+ releaseClaimedRoles(holder, { ...input, runOnWorktreeCreate: true, runOnSettle: false }),+ ).toMatchObject({ runOnWorktreeCreate: false, runOnSettle: true });+ expect(+ releaseClaimedRoles(holder, { ...input, runOnWorktreeCreate: false, runOnSettle: false }),+ ).toBe(holder);});it("builds default runtime env for scripts", () => {diff --git a/apps/web/src/projectScripts.ts b/apps/web/src/projectScripts.tsindex f0bcb530141..6cf7b4a67f6 100644--- a/apps/web/src/projectScripts.ts+++ b/apps/web/src/projectScripts.ts@@ -13,6 +13,7 @@ export interface ProjectScriptInput {readonly icon: ProjectScript["icon"];readonly runOnWorktreeCreate: ProjectScript["runOnWorktreeCreate"];readonly waitForSetup: boolean;+ readonly runOnSettle: boolean;readonly previewUrl: Exclude<ProjectScript["previewUrl"], undefined> | null;readonly autoOpenPreview: boolean;}@@ -25,6 +26,7 @@ export function buildProjectScript(id: string, input: ProjectScriptInput): Projeicon: input.icon,runOnWorktreeCreate: input.runOnWorktreeCreate,...(input.runOnWorktreeCreate && input.waitForSetup ? { async: false } : {}),+ ...(input.runOnSettle ? { runOnSettle: true } : {}),...(input.previewUrl === null? {}: {@@ -34,6 +36,24 @@ export function buildProjectScript(id: string, input: ProjectScriptInput): Proje};}+/**+ * A project runs at most one setup script and one settle script, so saving a+ * script that claims either role takes it from the script that held it.+ */+export function releaseClaimedRoles(+ script: ProjectScript,+ saved: ProjectScriptInput,+): ProjectScript {+ const releaseSetup = saved.runOnWorktreeCreate && script.runOnWorktreeCreate;+ const releaseSettle = saved.runOnSettle && script.runOnSettle === true;+ if (!releaseSetup && !releaseSettle) return script;+ return {+ ...script,+ ...(releaseSetup ? { runOnWorktreeCreate: false } : {}),+ ...(releaseSettle ? { runOnSettle: false } : {}),+ };+}+function normalizeScriptId(value: string): string {const cleaned = value.trim()@@ -87,6 +107,6 @@ export function nextProjectScriptId(name: string, existingIds: Iterable<string>)}export function primaryProjectScript(scripts: ReadonlyArray<ProjectScript>): ProjectScript | null {- const regular = scripts.find((script) => !script.runOnWorktreeCreate);- return regular ?? scripts[0] ?? null;+ const regular = scripts.find((script) => !script.runOnWorktreeCreate && !script.runOnSettle);+ return regular ?? scripts.find((script) => !script.runOnSettle) ?? null;}diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.mdindex aed09c04279..80af3a815b6 100644--- a/docs/user/thread-sidebar.md+++ b/docs/user/thread-sidebar.md@@ -134,6 +134,13 @@ sending an answer or restarting the agent. Settling also closes the thread'sterminals that wait at an idle prompt, and keeps their output. A terminal thatruns a command, such as a dev server, stays open.+To reclaim disk space from settled work, turn on **Run in the thread's worktree when the+thread settles** for one of the project's actions, or set `"runOnSettle": true` on a+`t3.json` script, for example `cargo clean`. It runs each time a thread in its own+worktree settles, manually or automatically, even if a terminal there still runs a+command such as a dev server. Threads in the project's main checkout skip it. Its terminal+closes when the command succeeds and stays open when it fails.+On web and desktop, press a thread's **Settle** button and drag up or down tosettle every thread in that section between it and the one you release on.The **Un-settle** and **Wake** buttons work the same way in their sections.diff --git a/packages/contracts/src/project.ts b/packages/contracts/src/project.tsindex 97997ef3dee..d1d13e82ac3 100644--- a/packages/contracts/src/project.ts+++ b/packages/contracts/src/project.ts@@ -36,6 +36,8 @@ export const ProjectScript = Schema.Struct({command: TrimmedNonEmptyString,icon: ProjectScriptIcon,runOnWorktreeCreate: Schema.Boolean,+ /** Run in the thread's worktree each time the thread settles. */+ runOnSettle: Schema.optional(Schema.Boolean),/** Start the agent while setup runs unless explicitly disabled. */async: Schema.optional(Schema.Boolean),previewUrl: Schema.optional(TrimmedNonEmptyString),diff --git a/packages/contracts/src/t3ProjectFile.ts b/packages/contracts/src/t3ProjectFile.tsindex 357c5ad8a90..5b3274be634 100644--- a/packages/contracts/src/t3ProjectFile.ts+++ b/packages/contracts/src/t3ProjectFile.ts@@ -43,6 +43,12 @@ export const T3ProjectFileScript = Schema.Struct({"When true, the script runs automatically after a worktree is created for a new thread.",}),),+ runOnSettle: Schema.optionalKey(+ Schema.Boolean.annotate({+ description:+ "When true, the script runs in the thread's worktree each time the thread settles, for example to delete build output. Threads without their own worktree skip it.",+ }),+ ),async: Schema.optionalKey(Schema.Boolean.annotate({description:diff --git a/packages/shared/src/projectScripts.ts b/packages/shared/src/projectScripts.tsindex 5cb988753a3..691376e7236 100644--- a/packages/shared/src/projectScripts.ts+++ b/packages/shared/src/projectScripts.ts@@ -73,3 +73,16 @@ export function projectScriptRuntimeEnv(export function setupProjectScript(scripts: readonly ProjectScript[]): ProjectScript | null {return scripts.find((script) => script.runOnWorktreeCreate) ?? null;}++/** Menu label naming the lifecycle roles a script runs in, e.g. "Clean (on settle)". */+export function projectScriptMenuLabel(script: ProjectScript): string {+ const roles = [+ ...(script.runOnWorktreeCreate ? ["setup"] : []),+ ...(script.runOnSettle ? ["on settle"] : []),+ ];+ return roles.length === 0 ? script.name : `${script.name} (${roles.join(", ")})`;+}++export function settleProjectScript(scripts: readonly ProjectScript[]): ProjectScript | null {+ return scripts.find((script) => script.runOnSettle === true) ?? null;+}diff --git a/packages/shared/src/t3ProjectFile.test.ts b/packages/shared/src/t3ProjectFile.test.tsindex 42045cc4284..782262fc6e2 100644--- a/packages/shared/src/t3ProjectFile.test.ts+++ b/packages/shared/src/t3ProjectFile.test.ts@@ -51,6 +51,7 @@ describe("buildT3ProjectFileJsonSchema", () => {"icon","name","previewUrl",+ "runOnSettle","runOnWorktreeCreate",]);});