11import { ProjectId } from "@t3tools/contracts" ;
2+ import { HostProcessPlatform } from "@t3tools/shared/hostProcess" ;
23import {
34 projectScriptRuntimeEnv ,
45 resolveProjectScripts ,
56 setupProjectScript ,
67} from "@t3tools/shared/projectScripts" ;
8+ import * as Clock from "effect/Clock" ;
79import * as Context from "effect/Context" ;
10+ import * as Deferred from "effect/Deferred" ;
811import * as Effect from "effect/Effect" ;
912import * as Layer from "effect/Layer" ;
1013import * as Option from "effect/Option" ;
@@ -22,8 +25,24 @@ export interface ProjectSetupScriptRunnerResultStarted {
2225 readonly status : "started" ;
2326 readonly scriptId : string ;
2427 readonly scriptName : string ;
28+ readonly scriptCommand : string ;
2529 readonly terminalId : string ;
2630 readonly cwd : string ;
31+ /**
32+ * Resolves when the script's shell prints the completion sentinel. The
33+ * exit code is null when the terminal exited or was closed before the
34+ * sentinel arrived. Only present when `observeCompletion` was requested.
35+ */
36+ readonly completion ?: Effect . Effect < ProjectSetupScriptCompletion > ;
37+ }
38+
39+ export interface ProjectSetupScriptCompletion {
40+ readonly exitCode : number | null ;
41+ readonly durationMs : number ;
42+ }
43+
44+ export interface ProjectSetupScriptOutputLine {
45+ readonly line : string ;
2746}
2847
2948export type ProjectSetupScriptRunnerResult =
@@ -36,6 +55,14 @@ export interface ProjectSetupScriptRunnerInput {
3655 readonly projectCwd ?: string ;
3756 readonly worktreePath : string ;
3857 readonly preferredTerminalId ?: string ;
58+ /**
59+ * Wrap the command so the shell reports its exit code back through the
60+ * terminal stream, and forward cleaned output lines while it runs. The
61+ * bootstrap flow uses this to drive the worktree setup card.
62+ */
63+ readonly observeCompletion ?: {
64+ readonly onOutputLine ?: ( line : string ) => Effect . Effect < void > ;
65+ } ;
3966}
4067
4168export class ProjectSetupScriptOperationError extends Schema . TaggedError < ProjectSetupScriptOperationError > ( ) (
@@ -84,10 +111,112 @@ export class ProjectSetupScriptRunner extends Context.Service<
84111> ( ) ( "t3/project/ProjectSetupScriptRunner" ) { }
85112
86113/** @public Service construction is part of the canonical Effect module API. */
114+ /** Marker the wrapped setup command echoes so the exit code can be read from the PTY stream. */
115+ const COMPLETION_SENTINEL_PREFIX = "__T3_SETUP_DONE__:" ;
116+ const COMPLETION_SENTINEL_PATTERN = / _ _ T 3 _ S E T U P _ D O N E _ _ : ( - ? \d + ) / ;
117+ const OUTPUT_LINE_MAX_LENGTH = 400 ;
118+
119+ /** Removes ANSI escape sequences and cursor controls so lines can be shown as plain text. */
120+ function stripTerminalControl ( text : string ) : string {
121+ return (
122+ text
123+ . replace (
124+ // eslint-disable-next-line no-control-regex
125+ / \x1b \[ [ 0 - 9 ; ? ] * [ - / ] * [ @ - ~ ] | \x1b \] [ ^ \x07 \x1b ] * (?: \x07 | \x1b \\ ) | \x1b [ ( ) ] [ A - Z a - z 0 - 9 ] | \x1b [ = > ] / g,
126+ "" ,
127+ )
128+ // eslint-disable-next-line no-control-regex
129+ . replace ( / [ \x00 - \x08 \x0b \x0c \x0e - \x1f \x7f ] / g, "" )
130+ ) ;
131+ }
132+
133+ /**
134+ * Builds the shell line for the setup script. On POSIX shells the user's
135+ * command runs in a subshell so `&&` chains and `cd` cannot leak, then the
136+ * exit status is echoed. PowerShell reports `$LASTEXITCODE` or falls back to
137+ * the success flag.
138+ */
139+ function wrapCommandForCompletion ( command : string , platform : NodeJS . Platform ) : string {
140+ if ( platform === "win32" ) {
141+ return `& { ${ command } }; if ($null -ne $LASTEXITCODE) { $__t3c = $LASTEXITCODE } elseif ($?) { $__t3c = 0 } else { $__t3c = 1 }; Write-Host "${ COMPLETION_SENTINEL_PREFIX } $__t3c"` ;
142+ }
143+ return `( ${ command } ); printf '\\n${ COMPLETION_SENTINEL_PREFIX } %s\\n' "$?"` ;
144+ }
145+
87146export const make = Effect . gen ( function * ( ) {
88147 const projectionSnapshotQuery = yield * ProjectionSnapshotQuery . ProjectionSnapshotQuery ;
89148 const terminalManager = yield * TerminalManager . TerminalManager ;
90149 const serverSettings = yield * ServerSettings . ServerSettingsService ;
150+ const platform = yield * HostProcessPlatform ;
151+
152+ /**
153+ * Watches the setup terminal for the completion sentinel. Terminal output is
154+ * a byte stream, so partial lines are buffered until a newline. The
155+ * subscription is torn down once the sentinel, an exit, or a close arrives.
156+ */
157+ const observeTerminalCompletion = ( input : {
158+ readonly threadId : string ;
159+ readonly terminalId : string ;
160+ readonly onOutputLine : ( ( line : string ) => Effect . Effect < void > ) | undefined ;
161+ } ) =>
162+ Effect . gen ( function * ( ) {
163+ const startedAtMs = yield * Clock . currentTimeMillis ;
164+ const done = yield * Deferred . make < ProjectSetupScriptCompletion > ( ) ;
165+ let lineBuffer = "" ;
166+ let settled = false ;
167+
168+ const settle = ( exitCode : number | null ) =>
169+ Effect . suspend ( ( ) => {
170+ if ( settled ) return Effect . void ;
171+ settled = true ;
172+ return Clock . currentTimeMillis . pipe (
173+ Effect . flatMap ( ( nowMs ) =>
174+ Deferred . succeed ( done , { exitCode, durationMs : nowMs - startedAtMs } ) ,
175+ ) ,
176+ Effect . asVoid ,
177+ ) ;
178+ } ) ;
179+
180+ const handleLine = ( rawLine : string ) =>
181+ Effect . suspend ( ( ) => {
182+ const sentinel = COMPLETION_SENTINEL_PATTERN . exec ( rawLine ) ;
183+ if ( sentinel ) {
184+ const parsed = Number ( sentinel [ 1 ] ) ;
185+ return settle ( Number . isFinite ( parsed ) ? parsed : null ) ;
186+ }
187+ const cleaned = stripTerminalControl ( rawLine ) . trimEnd ( ) ;
188+ // The echoed command line itself contains the sentinel prefix; hide it.
189+ if (
190+ cleaned . length === 0 ||
191+ cleaned . includes ( COMPLETION_SENTINEL_PREFIX ) ||
192+ input . onOutputLine === undefined
193+ ) {
194+ return Effect . void ;
195+ }
196+ return input . onOutputLine ( cleaned . slice ( 0 , OUTPUT_LINE_MAX_LENGTH ) ) ;
197+ } ) ;
198+
199+ const unsubscribe = yield * terminalManager . subscribe ( ( event ) => {
200+ if ( event . threadId !== input . threadId || event . terminalId !== input . terminalId ) {
201+ return Effect . void ;
202+ }
203+ if ( event . type === "output" ) {
204+ lineBuffer += event . data ;
205+ const lines = lineBuffer . split ( / \r ? \n / ) ;
206+ lineBuffer = lines . pop ( ) ?? "" ;
207+ return Effect . forEach ( lines , handleLine , { discard : true } ) ;
208+ }
209+ if ( event . type === "exited" || event . type === "closed" ) {
210+ return settle ( null ) ;
211+ }
212+ return Effect . void ;
213+ } ) ;
214+
215+ const completion = Deferred . await ( done ) . pipe (
216+ Effect . ensuring ( Effect . sync ( ( ) => unsubscribe ( ) ) ) ,
217+ ) ;
218+ return completion ;
219+ } ) ;
91220
92221 const runForThread : ProjectSetupScriptRunner [ "Service" ] [ "runForThread" ] = Effect . fn (
93222 "ProjectSetupScriptRunner.runForThread" ,
@@ -154,6 +283,10 @@ export const make = Effect.gen(function* () {
154283 project : { cwd : project . workspaceRoot } ,
155284 worktreePath : input . worktreePath ,
156285 } ) ;
286+ const observe = input . observeCompletion ;
287+ const commandLine = observe
288+ ? wrapCommandForCompletion ( script . command , platform )
289+ : script . command ;
157290
158291 yield * terminalManager
159292 . open ( {
@@ -173,11 +306,20 @@ export const make = Effect.gen(function* () {
173306 } ) ,
174307 ) ,
175308 ) ;
309+ // Subscribe before writing so the sentinel cannot race past the listener.
310+ const completion = observe
311+ ? yield * observeTerminalCompletion ( {
312+ threadId : input . threadId ,
313+ terminalId,
314+ onOutputLine : observe . onOutputLine ,
315+ } )
316+ : undefined ;
317+
176318 yield * terminalManager
177319 . write ( {
178320 threadId : input . threadId ,
179321 terminalId,
180- data : `${ script . command } \r` ,
322+ data : `${ commandLine } \r` ,
181323 } )
182324 . pipe (
183325 Effect . mapError (
@@ -194,8 +336,10 @@ export const make = Effect.gen(function* () {
194336 status : "started" ,
195337 scriptId : script . id ,
196338 scriptName : script . name ,
339+ scriptCommand : script . command ,
197340 terminalId,
198341 cwd,
342+ ...( completion ? { completion } : { } ) ,
199343 } as const ;
200344 } ) ;
201345
0 commit comments